@telnyx/ai-agent-widget 0.33.8 → 0.33.9-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 _w=Object.defineProperty;var yw=(ot,z,Gt)=>z in ot?_w(ot,z,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):ot[z]=Gt;var j=(ot,z,Gt)=>yw(ot,typeof z!="symbol"?z+"":z,Gt);(function(){"use strict";var ot,z,Gt,qt,Kr,Yr,Xr,Jr,Is,Rs,As,Zr,Vi={},Qr=[],Xh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Bi=Array.isArray;function dt(t,e){for(var i in e)t[i]=e[i];return t}function xs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Je(t,e,i){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?ot.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Ui(t,r,n,s,null)}function Ui(t,e,i,n,s){var o={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Gt,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function ut(t){return t.children}function rt(t,e){this.props=t,this.context=e}function di(t,e){if(e==null)return t.__?di(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?di(t):null}function ea(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return ea(t)}}function Ls(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!En.__r++||Kr!=z.debounceRendering)&&((Kr=z.debounceRendering)||Yr)(En)}function En(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(Xr),t=qt.shift(),a=qt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=dt({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),Ds(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??di(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,oa(o,i,r),i.__e!=s&&ea(i)));En.__r=0}function ta(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,_,v,b,w=n&&n.__k||Qr,C=e.length;for(l=Jh(i,e,w,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Vi:w[p.__i]||Vi,p.__i=d,b=Ds(t,p,h,s,o,r,a,l,c,u),_=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Os(h.ref,null,p),u.push(p.ref,p.__c||_,p)),v==null&&_!=null&&(v=_),4&p.__u||h.__k===p.__k?l=ia(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:_&&(l=_.nextSibling),p.__u&=-7);return i.__e=v,l}function Jh(t,e,i,n,s){var o,r,a,l,c,u=i.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Ui(null,r,null,null,null):Bi(r)?Ui(ut,{children:r},null,null,null):r.constructor==null&&r.__b>0?Ui(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=Zh(r,i,l,d))!=-1&&(d--,(a=i[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=i[o])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=di(a)),aa(a,a));return n}function ia(t,e,i){var n,s;if(typeof t.type=="function"){for(n=t.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=t,e=ia(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=di(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ht(t,e){return e=e||[],t==null||typeof t=="boolean"||(Bi(t)?t.some(function(i){ht(i,e)}):e.push(t)),e}function Zh(t,e,i,n){var s,o,r=t.key,a=t.type,l=e[i];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return i;if(n>(l!=null&&(2&l.__u)==0?1:0))for(s=i-1,o=i+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 na(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Xh.test(e)?i:i+"px"}function kn(t,e,i,n,s){var o,r;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||na(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||na(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Jr,"$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]=i,i?n?i.u=n.u:(i.u=Is,t.addEventListener(e,o?As:Rs,o)):t.removeEventListener(e,o?As:Rs,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]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function sa(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Is++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function Ds(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,_,v,b,w,C,k,L,R,O,T,E,g,m,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(w=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],L=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(w,L):(e.__c=d=new rt(w,L),d.constructor=f,d.render=ef),k&&k.sub(d),d.props=w,d.state||(d.state={}),d.context=L,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=dt({},d.__s)),dt(d.__s,f.getDerivedStateFromProps(w,d.__s))),p=d.props,_=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&w!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,L),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,L)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=w,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(w,d.__s,L),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,_,v)})}if(d.context=L,d.props=w,d.__P=t,d.__e=!1,O=z.__r,T=0,C){for(d.state=d.__s,d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),E=0;E<d._sb.length;E++)d.__h.push(d._sb[E]);d._sb=[]}else do d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++T<25);d.state=d.__s,d.getChildContext!=null&&(n=dt(dt({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,_)),g=u,u!=null&&u.type===ut&&u.key==null&&(g=ra(u.props.children)),a=ta(t,Bi(g)?g:[g],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(S){if(e.__v=null,l||o!=null)if(S.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--;)xs(o[m]);else e.__e=i.__e,e.__k=i.__k;z.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Qh(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function oa(t,e,i){for(var n=0;n<i.length;n++)Os(i[n],i[++n],i[++n]);z.__c&&z.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){z.__e(o,s.__v)}})}function ra(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Bi(t)?t.map(ra):dt({},t)}function Qh(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,_,v,b=i.props,w=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(w);t=document.createElementNS(s,C,w.is&&w),a&&(z.__m&&z.__m(e,o),a=!1),o=null}if(C==null)b===w||a&&t.data==w||(t.data=w);else{if(o=o&&ot.call(t.childNodes),b=i.props||Vi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in w)){if(c=="value"&&"defaultValue"in w||c=="checked"&&"defaultChecked"in w)continue;kn(t,c,null,p,s)}}for(c in w)p=w[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?_=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||kn(t,c,p,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),ta(e.type=="template"?t.content:t,Bi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&di(i,0),a,l),o!=null)for(c=o.length;c--;)xs(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=b[c])&&kn(t,c,_,b[c],s),c="checked",v!=null&&v!=t[c]&&kn(t,c,v,b[c],s))}return t}function Os(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){z.__e(s,i)}}function aa(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Os(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&aa(n[s],e,i||typeof t.type!="function");i||xs(t.__e),t.__c=t.__=t.__e=void 0}function ef(t,e,i){return this.constructor(t,i)}function In(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ds(e,t=(!n&&i||e).__k=Je(ut,null,[t]),s||Vi,Vi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?ot.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),oa(o,t,r)}function la(t,e){In(t,e,la)}function Ms(t,e,i){var n,s,o,r,a=dt({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?n=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?ot.call(arguments,2):i),Ui(t.type,a,n||t.key,s||t.ref,null)}function kt(t){function e(i){var n,s;return this.getChildContext||(n=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&n.forEach(function(r){r.__e=!0,Ls(r)})},this.sub=function(o){n.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){n&&n.delete(o),r&&r.call(o)}}),i.children}return e.__c="__cC"+Zr++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}ot=Qr.slice,z={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Gt=0,rt.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=dt({},this.state),typeof t=="function"&&(t=t(dt({},i),this.props)),t&&dt(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ls(this))},rt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ls(this))},rt.prototype.render=ut,qt=[],Yr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Xr=function(t,e){return t.__v.__b-e.__v.__b},En.__r=0,Jr=/(PointerCapture)$|Capture$/i,Is=0,Rs=sa(!1),As=sa(!0),Zr=0;var tf=0;function D(t,e,i,n,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:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tf,__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 z.vnode&&z.vnode(c),c}function Ps(){return(Ps=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t}).apply(this,arguments)}var nf=["context","children"];function sf(t){this.getChildContext=function(){return t.context};var e=t.children,i=function(n,s){if(n==null)return{};var o,r,a={},l=Object.keys(n);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=n[o]);return a}(t,nf);return Ms(e,i)}function of(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Je(sf,Ps({},this._props,{context:t.detail.context}),function e(i,n){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;var s=[],o={},r=0,a=i.attributes,l=i.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[ca(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Je(da,{name:u},c):s[r]=c}var d=n?Je(da,null,s):s;return Je(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?la:In)(this._vdom,this._root)}function ca(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function rf(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[ca(t)]=i,this._vdom=Ms(this._vdom,n),In(this._vdom,this._root)}}function af(){In(this._vdom=null,this._root)}function da(t,e){var i=this;return Je("slot",Ps({},t,{ref:function(n){n?(i.ref=n,i._listener||(i._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function lf(t,e,i,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=of,s.prototype.attributeChangedCallback=rf,s.prototype.disconnectedCallback=af,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=i,i.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 Mt,_e,Ns,ua,$i=0,ha=[],Se=z,fa=Se.__b,pa=Se.__r,ga=Se.diffed,ma=Se.__c,va=Se.unmount,_a=Se.__;function ui(t,e){Se.__h&&Se.__h(_e,t,$i||e),$i=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return $i=1,ya(wa,t)}function ya(t,e,i){var n=ui(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):wa(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=_e,!_e.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=ui(Mt++,3);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Fs(t,e){var i=ui(Mt++,4);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function ue(t){return $i=5,Ze(function(){return{current:t}},[])}function Ze(t,e){var i=ui(Mt++,7);return Us(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function He(t,e){return $i=8,Ze(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=ui(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function cf(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Vs(){var t=ui(Mt++,11);if(!t.__){for(var e=_e.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var i=e.__m||(e.__m=[0,0]);t.__="P"+i[0]+"-"+i[1]++}return t.__}function df(){for(var t;t=ha.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Rn),t.__H.__h.forEach(Bs),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,fa&&fa(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),_a&&_a(t,e)},Se.__r=function(t){pa&&pa(t),Mt=0;var e=(_e=t.__c).__H;e&&(Ns===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Rn),e.__h.forEach(Bs),e.__h=[],Mt=0)),Ns=_e},Se.diffed=function(t){ga&&ga(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ha.push(e)!==1&&ua===Se.requestAnimationFrame||((ua=Se.requestAnimationFrame)||uf)(df)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Ns=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Rn),i.__h=i.__h.filter(function(n){return!n.__||Bs(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),ma&&ma(t,e)},Se.unmount=function(t){va&&va(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Rn(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var ba=typeof requestAnimationFrame=="function";function uf(t){var e,i=function(){clearTimeout(n),ba&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);ba&&(e=requestAnimationFrame(i))}function Rn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Bs(t){var e=_e;t.__c=t.__(),_e=e}function Us(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function wa(t,e){return typeof e=="function"?e(t):e}const ji={},Sa=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ca=t=>"init"in t,$s=t=>!!t.write,Ta=t=>"v"in t||"e"in t,An=t=>{if("e"in t)throw t.e;if((ji?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},xn=new WeakMap,Ea=t=>{var e;return Ln(t)&&!!((e=xn.get(t))!=null&&e[0])},hf=t=>{const e=xn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},ka=(t,e)=>{let i=xn.get(t);if(!i){i=[!0,new Set],xn.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Ln=t=>typeof(t==null?void 0:t.then)=="function",Ia=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},js=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Ln(e))for(const r of n.d.keys())Ia(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Ln(o)&&hf(o))},Ra=(t,e,i)=>{var n;const s=new Set;for(const o of((n=i.get(t))==null?void 0:n.t)||[])i.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},ff=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Ws=()=>{const t={},e=new WeakMap,i=n=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(n)),(o=e.get(n))==null||o.forEach(r=>r())};return i.add=(n,s)=>{const o=n||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)}},i},pf=t=>(t.c||(t.c=Ws()),t.m||(t.m=Ws()),t.u||(t.u=Ws()),t.f||(t.f=ff()),t),gf=Symbol(),Aa=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...p)=>h.read(...p),l=(h,...p)=>h.write(...p),c=(h,p)=>{var _;return(_=h.unstable_onInit)==null?void 0:_.call(h,p)},u=(h,p)=>{var _;return(_=h.onMount)==null?void 0:_.call(h,p)},...d)=>{const h=d[0]||(T=>{if((ji?"production":void 0)!=="production"&&!T)throw new Error("Atom is undefined or null");let E=t.get(T);return E||(E={d:new Map,p:new Set,n:0},t.set(T,E),c==null||c(T,O)),E}),p=d[1]||(()=>{const T=[],E=g=>{try{g()}catch(m){T.push(m)}};do{r.f&&E(r.f);const g=new Set,m=g.add.bind(g);n.forEach(f=>{var S;return(S=e.get(f))==null?void 0:S.l.forEach(m)}),n.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),g.forEach(E),n.size&&_()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),_=d[2]||(()=>{const T=[],E=new WeakSet,g=new WeakSet,m=Array.from(n);for(;m.length;){const f=m[m.length-1],S=h(f);if(g.has(f)){m.pop();continue}if(E.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if((ji?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");g.add(f),m.pop();continue}E.add(f);for(const I of Ra(f,S,e))E.has(I)||m.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let A=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){A=!0;break}A&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const g=h(T);if(Ta(g)&&(e.has(T)&&i.get(T)!==g.n||Array.from(g.d).every(([M,F])=>v(M).n===F)))return g;g.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),_(),p())},S=M=>{var F;if(Sa(T,M)){const $=h(M);if(!Ta($))if(Ca(M))js(M,M.init,h);else throw new Error("no atom init");return An($)}const H=v(M);try{return An(H)}finally{g.d.set(M,H.n),Ea(g.v)&&Ia(T,g.v,H),(F=e.get(M))==null||F.t.add(T),m||f()}};let I,A;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(ji?"production":void 0)!=="production"&&!$s(T)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&$s(T)&&(A=(...M)=>{if((ji?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return w(T,...M)}finally{_(),p()}}),A}},P=g.n;try{const M=a(T,S,x);return js(T,M,h),Ln(M)&&(ka(M,()=>I==null?void 0:I.abort()),M.then(f,f)),g}catch(M){return delete g.v,g.e=M,++g.n,g}finally{m=!1,P!==g.n&&i.get(T)===P&&(i.set(T,g.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const g=E.pop(),m=h(g);for(const f of Ra(g,m,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),w=d[5]||((T,...E)=>{let g=!0;const m=S=>An(v(S)),f=(S,...I)=>{var A;const x=h(S);try{if(Sa(T,S)){if(!Ca(S))throw new Error("atom not writable");const P=x.n,M=I[0];js(S,M,h),C(S),P!==x.n&&(n.add(S),(A=r.c)==null||A.call(r,S),b(S));return}else return w(S,...I)}finally{g||(_(),p())}};try{return l(T,m,f,...E)}finally{g=!1}}),C=d[6]||(T=>{var E;const g=h(T),m=e.get(T);if(m&&!Ea(g.v)){for(const[f,S]of g.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(T),m.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of m.d||[])if(!g.d.has(f)){m.d.delete(f);const S=L(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const g=h(T);let m=e.get(T);if(!m){v(T);for(const f of g.d.keys())k(f).t.add(T);if(m={l:new Set,d:new Set(g.d.keys()),t:new Set},e.set(T,m),(E=r.m)==null||E.call(r,T),$s(T)){const f=()=>{let S=!0;const I=(...A)=>{try{return w(T,...A)}finally{S||(_(),p())}};try{const A=u(T,I);A&&(m.u=()=>{S=!0;try{A()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return m}),L=d[8]||(T=>{var E;const g=h(T);let m=e.get(T);if(m&&!m.l.size&&!Array.from(m.t).some(f=>{var S;return(S=e.get(f))==null?void 0:S.d.has(T)})){m.u&&o.add(m.u),m=void 0,e.delete(T),(E=r.u)==null||E.call(r,T);for(const f of g.d.keys()){const S=L(f);S==null||S.t.delete(T)}return}return m}),R=[t,e,i,n,s,o,r,a,l,c,u,h,p,_,v,b,w,C,k,L],O={get:T=>An(v(T)),set:(T,...E)=>{try{return w(T,...E)}finally{_(),p()}},sub:(T,E)=>{const m=k(T).l;return m.add(E),p(),()=>{m.delete(E),L(T),p()}}};return Object.defineProperty(O,gf,{value:R}),O},mf=pf,xa=ka,Hs={};let vf=0;function Dn(t,e){const i=`atom${++vf}`,n={toString(){return(Hs?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=_f,n.write=yf),n}function _f(t){return t(this)}function yf(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const bf=()=>{let t=0;const e=mf({}),i=new WeakMap,n=new WeakMap,s=Aa(i,n,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=i.get(a);l.m=n.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=i.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),i),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function wf(){return(Hs?"production":void 0)!=="production"?bf():Aa()}let Wi;function Sf(){return Wi||(Wi=wf(),(Hs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Wi),globalThis.__JOTAI_DEFAULT_STORE__!==Wi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Wi}function La(t,e){for(var i in e)t[i]=e[i];return t}function Da(t,e){for(var i in t)if(i!=="__source"&&!(i in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}var Oa=Fs;function Ma(t,e){this.props=t,this.context=e}(Ma.prototype=new rt).isPureReactComponent=!0,Ma.prototype.shouldComponentUpdate=function(t,e){return Da(this.props,t)||Da(this.state,e)};var Pa=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Pa&&Pa(t)};var Cf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Tf(t){function e(i){var n=La({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=Cf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Na=function(t,e){return t==null?null:ht(ht(t).map(e))},Ef={map:Na,forEach:Na,count:function(t){return t?ht(t).length:0},only:function(t){var e=ht(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ht},kf=z.__e;z.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}kf(t,e,i,n)};var Fa=z.unmount;function Va(t,e,i){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=La({},t)).__c!=null&&(t.__c.__P===i&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return Va(n,e,i)})),t}function Ba(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Ba(n,e,i)}),t.__c&&t.__c.__P===e&&(t.__e&&i.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=i)),t}function Gs(){this.__u=0,this.o=null,this.__b=null}function Ua(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function On(){this.i=null,this.l=null}z.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Fa&&Fa(t)},(Gs.prototype=new rt).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Ua(n.__v),o=!1,r=function(){o||(o=!0,i.__R=null,s?s(a):a())};i.__R=r;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=Ba(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(r,r)},Gs.prototype.componentWillUnmount=function(){this.o=[]},Gs.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var i=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=Va(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Je(ut,null,t.fallback);return s&&(s.__u&=-33),[Je(ut,null,e.__a?null:t.children),s]};var $a=function(t,e,i){if(++i[1]===i[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(i=t.i;i;){for(;i.length>3;)i.pop()();if(i[1]<i[0])break;t.i=i=i[2]}};(On.prototype=new rt).__a=function(t){var e=this,i=Ua(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),$a(e,t,n)):s()};i?i(o):o()}},On.prototype.render=function(t){this.i=null,this.l=new Map;var e=ht(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var i=e.length;i--;)this.l.set(e[i],this.i=[1,0,this.i]);return t.children},On.prototype.componentDidUpdate=On.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){$a(t,i,e)})};var ja=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,If=/^(?: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]/,Rf=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Af=/[A-Z0-9]/g,xf=typeof document<"u",Lf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};rt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(rt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Wa=z.event;function Df(){}function Of(){return this.cancelBubble}function Mf(){return this.defaultPrevented}z.event=function(t){return Wa&&(t=Wa(t)),t.persist=Df,t.isPropagationStopped=Of,t.isDefaultPrevented=Mf,t.nativeEvent=t};var Pf={enumerable:!1,configurable:!0,get:function(){return this.class}},Ha=z.vnode;z.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||xf&&r==="children"&&n==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in i&&i.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"||n!=="input"&&n!=="textarea"||Lf(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Rf.test(r)&&(r=l):l=r="oninput":o&&If.test(r)?r=r.replace(Af,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}n=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ht(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=ht(i.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),i.class&&!i.className?(s.class=i.class,Object.defineProperty(s,"className",Pf)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=ja,Ha&&Ha(t)};var Ga=z.__r;z.__r=function(t){Ga&&Ga(t),t.__c};var qa=z.diffed;z.diffed=function(t){qa&&qa(t);var e=t.props,i=t.__e;i!=null&&t.type==="textarea"&&"value"in e&&e.value!==i.value&&(i.value=e.value==null?"":e.value)};function za(t){return!!t&&t.$$typeof===ja}function Nf(t){return za(t)?Ms.apply(null,arguments):t}var Ka={};const Ff={},Vf=kt(void 0);function Ya(t){return De(Vf)||Sf()}const qs=t=>typeof(t==null?void 0:t.then)=="function",zs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Bf=Ka.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(zs(t),t)}),Ks=new WeakMap,Xa=(t,e)=>{let i=Ks.get(t);return i||(i=new Promise((n,s)=>{let o=t;const r=c=>u=>{o===c&&n(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();qs(c)?(Ks.set(c,i),o=c,c.then(r(c),a(c)),xa(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),xa(t,l)}),Ks.set(t,i)),i};function Ys(t,e){const{delay:i,unstable_promiseStatus:n=!Ka.use}={},s=Ya(),[[o,r,a],l]=ya(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);qs(d)&&zs(Xa(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),cf(c),qs(c)){const u=Xa(c,()=>s.get(t));return n&&zs(u),Bf(u)}return c}function Mn(t,e){const i=Ya();return He((...s)=>{if((Ff?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Ja(t,e){return[Ys(t),Mn(t)]}const Xs=kt({});function Pn(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const Js=typeof window<"u",Za=Js?Fs:xe,Nn=kt(null);function Zs(t,e){t.indexOf(e)===-1&&t.push(e)}function Qs(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const It=(t,e,i)=>i>e?e:i<t?t:i;let eo=()=>{};const Rt={},Qa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function el(t){return typeof t=="object"&&t!==null}const tl=t=>/^0[^.\s]+$/u.test(t);function to(t){let e;return()=>(e===void 0&&(e=t()),e)}const Qe=t=>t,Uf=(t,e)=>i=>e(t(i)),Hi=(...t)=>t.reduce(Uf),Gi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class io{constructor(){this.subscriptions=[]}add(e){return Zs(this.subscriptions,e),()=>Qs(this.subscriptions,e)}notify(e,i,n){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,i,n);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,i,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ft=t=>t*1e3,pt=t=>t/1e3;function il(t,e){return e?t*(1e3/e):0}const nl=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,$f=1e-7,jf=12;function Wf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=nl(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>$f&&++a<jf);return r}function qi(t,e,i,n){if(t===e&&i===n)return Qe;const s=o=>Wf(o,0,1,t,i);return o=>o===0||o===1?o:nl(s(o),e,n)}const sl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ol=t=>e=>1-t(1-e),rl=qi(.33,1.53,.69,.99),no=ol(rl),al=sl(no),ll=t=>(t*=2)<1?.5*no(t):.5*(2-Math.pow(2,-10*(t-1))),so=t=>1-Math.sin(Math.acos(t)),cl=ol(so),dl=sl(so),Hf=qi(.42,0,1,1),Gf=qi(0,0,.58,1),ul=qi(.42,0,.58,1),qf=t=>Array.isArray(t)&&typeof t[0]!="number",hl=t=>Array.isArray(t)&&typeof t[0]=="number",zf={linear:Qe,easeIn:Hf,easeInOut:ul,easeOut:Gf,circIn:so,circInOut:dl,circOut:cl,backIn:no,backInOut:al,backOut:rl,anticipate:ll},Kf=t=>typeof t=="string",fl=t=>{if(hl(t)){eo(t.length===4);const[e,i,n,s]=t;return qi(e,i,n,s)}else if(Kf(t))return zf[t];return t},Fn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],pl={value:null};function Yf(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,p=!1)=>{const v=p&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&pl.value&&pl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Xf=40;function gl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Fn.reduce((k,L)=>(k[L]=Yf(o,e?L:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:_}=r,v=()=>{const k=Rt.useManualTiming?s.timestamp:performance.now();i=!1,Rt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Xf),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),_.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:Fn.reduce((k,L)=>{const R=r[L];return k[L]=(O,T=!1,E=!1)=>(i||b(),R.schedule(O,T,E)),k},{}),cancel:k=>{for(let L=0;L<Fn.length;L++)r[Fn[L]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:oo}=gl(typeof requestAnimationFrame<"u"?requestAnimationFrame:Qe,!0);let Vn;function Jf(){Vn=void 0}const Ge={now:()=>(Vn===void 0&&Ge.set(Pe.isProcessing||Rt.useManualTiming?Pe.timestamp:performance.now()),Vn),set:t=>{Vn=t,queueMicrotask(Jf)}},ml=t=>e=>typeof e=="string"&&e.startsWith(t),ro=ml("--"),Zf=ml("var(--"),ao=t=>Zf(t)?Qf.test(t.split("/*")[0].trim()):!1,Qf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,hi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},zi={...hi,transform:t=>It(0,1,t)},Bn={...hi,default:1},Ki=t=>Math.round(t*1e5)/1e5,lo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ep(t){return t==null}const tp=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,co=(t,e)=>i=>!!(typeof i=="string"&&tp.test(i)&&i.startsWith(t)||e&&!ep(i)&&Object.prototype.hasOwnProperty.call(i,e)),vl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(lo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},ip=t=>It(0,255,t),uo={...hi,transform:t=>Math.round(ip(t))},zt={test:co("rgb","red"),parse:vl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+uo.transform(t)+", "+uo.transform(e)+", "+uo.transform(i)+", "+Ki(zi.transform(n))+")"};function np(t){let e="",i="",n="",s="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),n=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),n=t.substring(3,4),s=t.substring(4,5),e+=e,i+=i,n+=n,s+=s),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:s?parseInt(s,16)/255:1}}const ho={test:co("#"),parse:np,transform:zt.transform},Yi=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Yi("deg"),gt=Yi("%"),K=Yi("px"),sp=Yi("vh"),op=Yi("vw"),_l={...gt,parse:t=>gt.parse(t)/100,transform:t=>gt.transform(t*100)},fi={test:co("hsl","hue"),parse:vl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+gt.transform(Ki(e))+", "+gt.transform(Ki(i))+", "+Ki(zi.transform(n))+")"},Ie={test:t=>zt.test(t)||ho.test(t)||fi.test(t),parse:t=>zt.test(t)?zt.parse(t):fi.test(t)?fi.parse(t):ho.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):fi.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},rp=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ap(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(lo))==null?void 0:e.length)||0)+(((i=t.match(rp))==null?void 0:i.length)||0)>0}const yl="number",bl="color",lp="var",cp="var(",wl="${}",dp=/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 Xi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(dp,l=>(Ie.test(l)?(n.color.push(o),s.push(bl),i.push(Ie.parse(l))):l.startsWith(cp)?(n.var.push(o),s.push(lp),i.push(l)):(n.number.push(o),s.push(yl),i.push(parseFloat(l))),++o,wl)).split(wl);return{values:i,split:a,indexes:n,types:s}}function Sl(t){return Xi(t).values}function Cl(t){const{split:e,types:i}=Xi(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===yl?o+=Ki(s[r]):a===bl?o+=Ie.transform(s[r]):o+=s[r]}return o}}const up=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function hp(t){const e=Sl(t);return Cl(t)(e.map(up))}const Ft={test:ap,parse:Sl,createTransformer:Cl,getAnimatableNone:hp};function fo(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function fp({hue:t,saturation:e,lightness:i,alpha:n}){t/=360,e/=100,i/=100;let s=0,o=0,r=0;if(!e)s=o=r=i;else{const a=i<.5?i*(1+e):i+e-i*e,l=2*i-a;s=fo(l,a,t+1/3),o=fo(l,a,t),r=fo(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Un(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,po=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},pp=[ho,zt,fi],gp=t=>pp.find(e=>e.test(t));function Tl(t){const e=gp(t);if(!e)return!1;let i=e.parse(t);return e===fi&&(i=fp(i)),i}const El=(t,e)=>{const i=Tl(t),n=Tl(e);if(!i||!n)return Un(t,e);const s={...i};return o=>(s.red=po(i.red,n.red,o),s.green=po(i.green,n.green,o),s.blue=po(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},go=new Set(["none","hidden"]);function mp(t,e){return go.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function vp(t,e){return i=>Ce(t,e,i)}function mo(t){return typeof t=="number"?vp:typeof t=="string"?ao(t)?Un:Ie.test(t)?El:bp:Array.isArray(t)?kl:typeof t=="object"?Ie.test(t)?El:_p:Un}function kl(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>mo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function _p(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=mo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function yp(t,e){const i=[],n={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][n[o]],a=t.values[r]??0;i[s]=a,n[o]++}return i}const bp=(t,e)=>{const i=Ft.createTransformer(e),n=Xi(t),s=Xi(e);return n.indexes.var.length===s.indexes.var.length&&n.indexes.color.length===s.indexes.color.length&&n.indexes.number.length>=s.indexes.number.length?go.has(t)&&!s.values.length||go.has(e)&&!n.values.length?mp(t,e):Hi(kl(yp(n,s),s.values),i):Un(t,e)};function Il(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):mo(t)(t,e)}const wp=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:Ge.now()}},Rl=(t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let o=0;o<s;o++)n+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${n.substring(0,n.length-2)})`},$n=2e4;function vo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<$n;)e+=i,n=t.next(e);return e>=$n?1/0:e}function Sp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(vo(n),$n);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:pt(s)}}const Cp=5;function Al(t,e,i){const n=Math.max(e-Cp,0);return il(i-t(n),e-n)}const Te={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},_o=.001;function Tp({duration:t=Te.duration,bounce:e=Te.bounce,velocity:i=Te.velocity,mass:n=Te.mass}){let s,o,r=1-e;r=It(Te.minDamping,Te.maxDamping,r),t=It(Te.minDuration,Te.maxDuration,pt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,p=yo(c,r),_=Math.exp(-d);return _o-h/p*_},o=c=>{const d=c*r*t,h=d*i+i,p=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-d),v=yo(Math.pow(c,2),r);return(-s(c)+_o>0?-1:1)*((h-p)*_)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-_o+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=kp(s,o,a);if(t=ft(t),isNaN(l))return{stiffness:Te.stiffness,damping:Te.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const Ep=12;function kp(t,e,i){let n=i;for(let s=1;s<Ep;s++)n=n-t(n)/e(n);return n}function yo(t,e){return t*Math.sqrt(1-e*e)}const Ip=["duration","bounce"],Rp=["stiffness","damping","mass"];function xl(t,e){return e.some(i=>t[i]!==void 0)}function Ap(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!xl(t,Rp)&&xl(t,Ip))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*It(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Te.mass,stiffness:s,damping:o}}else{const i=Tp(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function jn(t=Te.visualDuration,e=Te.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:p}=Ap({...i,velocity:-pt(i.velocity||0)}),_=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,w=pt(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Te.restSpeed.granular:Te.restSpeed.default),s||(s=C?Te.restDelta.granular:Te.restDelta.default);let k;if(v<1){const R=yo(w,v);k=O=>{const T=Math.exp(-v*w*O);return r-T*((_+v*w*b)/R*Math.sin(R*O)+b*Math.cos(R*O))}}else if(v===1)k=R=>r-Math.exp(-w*R)*(b+(_+w*b)*R);else{const R=w*Math.sqrt(v*v-1);k=O=>{const T=Math.exp(-v*w*O),E=Math.min(R*O,300);return r-T*((_+v*w*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const L={calculatedDuration:p&&d||null,next:R=>{const O=k(R);if(p)a.done=R>=d;else{let T=R===0?_:0;v<1&&(T=R===0?ft(_):Al(k,R,O));const E=Math.abs(T)<=n,g=Math.abs(r-O)<=s;a.done=E&&g}return a.value=a.done?r:O,a},toString:()=>{const R=Math.min(vo(L),$n),O=Rl(T=>L.next(R*T).value,R,30);return R+"ms "+O},toTransition:()=>{}};return L}jn.applyToOptions=t=>{const e=Sp(t,100,jn);return t.ease=e.ease,t.duration=ft(e.duration),t.type="keyframes",t};function bo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=E=>a!==void 0&&E<a||l!==void 0&&E>l,_=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let v=i*e;const b=d+v,w=r===void 0?b:r(b);w!==b&&(v=w-d);const C=E=>-v*Math.exp(-E/n),k=E=>w+C(E),L=E=>{const g=C(E),m=k(E);h.done=Math.abs(g)<=c,h.value=h.done?w:m};let R,O;const T=E=>{p(h.value)&&(R=E,O=jn({keyframes:[h.value,_(h.value)],velocity:Al(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let g=!1;return!O&&R===void 0&&(g=!0,L(E),T(E)),R!==void 0&&E>=R?O.next(E-R):(!g&&L(E),h)}}}function xp(t,e,i){const n=[],s=i||Rt.mix||Il,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||Qe:e;a=Hi(l,a)}n.push(a)}return n}function Lp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(eo(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=xp(e,n,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=Gi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Dp(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Gi(0,e,n);t.push(Ce(i,1,s))}}function Op(t){const e=[0];return Dp(e,t.length-1),e}function Mp(t,e){return t.map(i=>i*e)}function Pp(t,e){return t.map(()=>e||ul).splice(0,t.length-1)}function Ji({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=qf(n)?n.map(fl):fl(n),o={done:!1,value:e[0]},r=Mp(i&&i.length===e.length?i:Op(e),t),a=Lp(r,e,{ease:Array.isArray(s)?s:Pp(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Np=t=>t!==null;function wo(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Np),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Fp={decay:bo,inertia:bo,tween:Ji,keyframes:Ji,spring:jn};function Ll(t){typeof t.type=="string"&&(t.type=Fp[t.type])}class So{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const Vp=t=>t/100;class Co extends So{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==Ge.now()&&this.tick(Ge.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(n=this.options).onStop)==null||s.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Ll(e);const{type:i=Ji,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Ji;l!==Ji&&typeof a[0]!="number"&&(this.mixKeyframes=Hi(Vp,Il(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=vo(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:p,type:_,onUpdate:v,finalKeyframe:b}=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)),i?this.currentTime=e:this.updateTime(e);const w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,L=n;if(d){const E=Math.min(this.currentTime,s)/a;let g=Math.floor(E),m=E%1;!m&&E>=1&&(m=1),m===1&&g--,g=Math.min(g,d+1),!!(g%2)&&(h==="reverse"?(m=1-m,p&&(m-=p/a)):h==="mirror"&&(L=r)),k=It(0,1,m)*a}const R=C?{done:!1,value:u[0]}:L.next(k);o&&(R.value=o(R.value));let{done:O}=R;!C&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return T&&_!==bo&&(R.value=wo(u,this.options,b,this.speed)),v&&v(R.value),T&&this.finish(),R}then(e,i){return this.finished.then(e,i)}get duration(){return pt(this.calculatedDuration)}get time(){return pt(this.currentTime)}set time(e){var i;e=ft(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),(i=this.driver)==null||i.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Ge.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=pt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=wp,startTime:i}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=i??n),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(Ge.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.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 i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function Bp(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,To=t=>{const e=Kt(Math.atan2(t[1],t[0]));return Eo(e)},Up={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:To,rotateZ:To,skewX:t=>Kt(Math.atan(t[1])),skewY:t=>Kt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Eo=t=>(t=t%360,t<0&&(t+=360),t),Dl=To,Ol=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ml=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),$p={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ol,scaleY:Ml,scale:t=>(Ol(t)+Ml(t))/2,rotateX:t=>Eo(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>Eo(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Dl,rotate:Dl,skewX:t=>Kt(Math.atan(t[4])),skewY:t=>Kt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ko(t){return t.includes("scale")?1:0}function Io(t,e){if(!t||t==="none")return ko(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=$p,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Up,s=a}if(!s)return ko(e);const o=n[e],r=s[1].split(",").map(Wp);return typeof o=="function"?o(r):r[o]}const jp=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Io(i,e)};function Wp(t){return parseFloat(t.trim())}const pi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],gi=new Set(pi),Pl=t=>t===hi||t===K,Hp=new Set(["x","y","z"]),Gp=pi.filter(t=>!Hp.has(t));function qp(t){const e=[];return Gp.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Yt={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),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})=>Io(e,"x"),y:(t,{transform:e})=>Io(e,"y")};Yt.translateX=Yt.x,Yt.translateY=Yt.y;const Xt=new Set;let Ro=!1,Ao=!1,xo=!1;function Nl(){if(Ao){const t=Array.from(Xt).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=qp(n);s.length&&(i.set(n,s),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const s=i.get(n);s&&s.forEach(([o,r])=>{var a;(a=n.getValue(o))==null||a.set(r)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}Ao=!1,Ro=!1,Xt.forEach(t=>t.complete(xo)),Xt.clear()}function Fl(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ao=!0)})}function zp(){xo=!0,Fl(),Nl(),xo=!1}class Lo{constructor(e,i,n,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=n,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Xt.add(this),Ro||(Ro=!0,we.read(Fl),we.resolveKeyframes(Nl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:n,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(n&&i){const a=n.readValue(i,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Bp(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Xt.delete(this)}cancel(){this.state==="scheduled"&&(Xt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Kp=t=>t.startsWith("--");function Yp(t,e,i){Kp(e)?t.style.setProperty(e,i):t.style[e]=i}const Xp=to(()=>window.ScrollTimeline!==void 0),Jp={};function Zp(t,e){const i=to(t);return()=>Jp[e]??i()}const Vl=Zp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zi=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,Bl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zi([0,.65,.55,1]),circOut:Zi([.55,0,1,.45]),backIn:Zi([.31,.01,.66,-.59]),backOut:Zi([.33,1.53,.69,.99])};function Ul(t,e){if(t)return typeof t=="function"?Vl()?Rl(t,e):"ease-out":hl(t)?Zi(t):Array.isArray(t)?t.map(i=>Ul(i,e)||Bl.easeOut):Bl[t]}function Qp(t,e,i,{delay:n=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:i};l&&(u.offset=l);const d=Ul(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function $l(t){return typeof t=="function"&&"applyToOptions"in t}function eg({type:t,...e}){return $l(t)&&Vl()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class tg extends So{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,eo(typeof e.type!="string");const c=eg(e);this.animation=Qp(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=wo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Yp(i,n,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.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,i;this.isPseudoElement||(i=(e=this.animation).commitStyles)==null||i.call(e)}get duration(){var i,n;const e=((n=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:n.call(i).duration)||0;return pt(Number(e))}get time(){return pt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=ft(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:i}){var n;return this.allowFlatten&&((n=this.animation.effect)==null||n.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Xp()?(this.animation.timeline=e,Qe):i(this)}}const jl={anticipate:ll,backInOut:al,circInOut:dl};function ig(t){return t in jl}function ng(t){typeof t.ease=="string"&&ig(t.ease)&&(t.ease=jl[t.ease])}const Wl=10;class sg extends tg{constructor(e){ng(e),Ll(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:n,onComplete:s,element:o,...r}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const a=new Co({...r,autoplay:!1}),l=ft(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Wl).value,a.sample(l).value,Wl),a.stop()}}const Hl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function og(t){const e=t[0];if(t.length===1)return!0;for(let i=0;i<t.length;i++)if(t[i]!==e)return!0}function rg(t,e,i,n){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=Hl(s,e),a=Hl(o,e);return!r||!a?!1:og(t)||(i==="spring"||$l(i))&&n}function Do(t){return el(t)&&"offsetHeight"in t}const ag=new Set(["opacity","clipPath","filter","transform"]),lg=to(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function cg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Do((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return lg()&&i&&ag.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const dg=40;class ug extends So{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var _;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=Ge.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},p=(u==null?void 0:u.KeyframeResolver)||Lo;this.keyframeResolver=new p(a,(v,b,w)=>this.onKeyframesResolved(v,b,h,!w),l,c,u),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,i,n,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=n;this.resolvedAt=Ge.now(),rg(e,o,r,a)||((Rt.instantAnimations||!l)&&(u==null||u(wo(e,n,i))),e[0]=e[e.length-1],n.duration=0,n.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>dg?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&cg(h)?new sg({...h,element:h.motionValue.owner.current}):new Co(h);p.finished.then(()=>this.notifyFinished()).catch(Qe),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),zp()),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 hg=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function fg(t){const e=hg.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Gl(t,e,i=1){const[n,s]=fg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Qa(r)?parseFloat(r):r}return ao(s)?Gl(s,e,i+1):s}function Oo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const ql=new Set(["width","height","top","left","right","bottom",...pi]),pg={test:t=>t==="auto",parse:t=>t},zl=t=>e=>e.test(t),Kl=[hi,K,gt,Nt,op,sp,pg],Yl=t=>Kl.find(zl(t));function gg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||tl(t):!0}const mg=new Set(["brightness","contrast","saturate","opacity"]);function vg(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(lo)||[];if(!n)return t;const s=i.replace(n,"");let o=mg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const _g=/\b([a-z-]*)\(.*?\)/gu,Mo={...Ft,getAnimatableNone:t=>{const e=t.match(_g);return e?e.map(vg).join(" "):t}},Xl={...hi,transform:Math.round},Po={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Bn,scaleX:Bn,scaleY:Bn,scaleZ:Bn,skew:Nt,skewX:Nt,skewY:Nt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:zi,originX:_l,originY:_l,originZ:K},zIndex:Xl,fillOpacity:zi,strokeOpacity:zi,numOctaves:Xl},yg={...Po,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:Mo,WebkitFilter:Mo},Jl=t=>yg[t];function Zl(t,e){let i=Jl(t);return i!==Mo&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const bg=new Set(["auto","none","0"]);function wg(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!bg.has(o)&&Xi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Zl(i,s)}class Sg extends Lo{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),ao(c))){const u=Gl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!ql.has(n)||e.length!==2)return;const[s,o]=e,r=Yl(s),a=Yl(o);if(r!==a)if(Pl(r)&&Pl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Yt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||gg(e[s]))&&n.push(s);n.length&&wg(e,n,i)}measureInitialState(){const{element:e,unresolvedKeyframes:i,name:n}=this;if(!e||!e.current)return;n==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Yt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i[0]=this.measuredOrigin;const s=i[i.length-1];s!==void 0&&e.getValue(n,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:i,unresolvedKeyframes:n}=this;if(!e||!e.current)return;const s=e.getValue(i);s&&s.jump(this.measuredOrigin,!1);const o=n.length-1,r=n[o];n[o]=Yt[i](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 Cg(t,e,i){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let n=document;const s=(i==null?void 0:i[t])??n.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Ql=(t,e)=>e&&typeof t=="number"?e.transform(t):t,ec=30,Tg=t=>!isNaN(parseFloat(t));class Eg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=Ge.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),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=i.owner}setCurrent(e){this.current=e,this.updatedAt=Ge.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Tg(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new io);const n=this.events[e].add(i);return e==="change"?()=>{n(),we.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e,i=!0){!i||!this.passiveEffect?this.updateAndNotify(e,i):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,i,n){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&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=Ge.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>ec)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,ec);return il(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),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,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function mi(t,e){return new Eg(t,e)}const{schedule:No}=gl(queueMicrotask,!1),at={x:!1,y:!1};function tc(){return at.x||at.y}function kg(t){return t==="x"||t==="y"?at[t]?null:(at[t]=!0,()=>{at[t]=!1}):at.x||at.y?null:(at.x=at.y=!0,()=>{at.x=at.y=!1})}function ic(t,e){const i=Cg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function nc(t){return!(t.pointerType==="touch"||tc())}function Ig(t,e,i={}){const[n,s,o]=ic(t,i),r=a=>{if(!nc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{nc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const sc=(t,e)=>e?t===e?!0:sc(t,e.parentElement):!1,Fo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Rg=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ag(t){return Rg.has(t.tagName)||t.tabIndex!==-1}const Wn=new WeakSet;function oc(t){return e=>{e.key==="Enter"&&t(e)}}function Vo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const xg=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=oc(()=>{if(Wn.has(i))return;Vo(i,"down");const s=oc(()=>{Vo(i,"up")}),o=()=>Vo(i,"cancel");i.addEventListener("keyup",s,e),i.addEventListener("blur",o,e)});i.addEventListener("keydown",n,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),e)};function rc(t){return Fo(t)&&!tc()}function Lg(t,e,i={}){const[n,s,o]=ic(t,i),r=a=>{const l=a.currentTarget;if(!rc(a))return;Wn.add(l);const c=e(l,a),u=(p,_)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Wn.has(l)&&Wn.delete(l),rc(p)&&typeof c=="function"&&c(p,{success:_})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||sc(l,p.target))},h=p=>{u(p,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Do(a)&&(a.addEventListener("focus",c=>xg(c,s)),!Ag(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ac(t){return el(t)&&"ownerSVGElement"in t}function Dg(t){return ac(t)&&t.tagName==="svg"}const Be=t=>!!(t&&t.getVelocity),Og=[...Kl,Ie,Ft],Mg=t=>Og.find(zl(t)),Qi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Pg extends rt{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Do(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=i.offsetHeight||0,o.width=i.offsetWidth||0,o.top=i.offsetTop,o.left=i.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Ng({children:t,isPresent:e,anchorX:i,root:n}){const s=Vs(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(Qi);return Oa(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const p=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=n??document.head;return v.appendChild(_),_.sheet&&_.sheet.insertRule(`
1
+ var Sw=Object.defineProperty;var Cw=(rt,K,Gt)=>K in rt?Sw(rt,K,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):rt[K]=Gt;var j=(rt,K,Gt)=>Cw(rt,typeof K!="symbol"?K+"":K,Gt);(function(){"use strict";var rt,K,Gt,qt,Jr,Zr,Qr,ea,Is,Rs,As,ta,Bi={},ia=[],Yh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Vi=Array.isArray;function ut(t,e){for(var i in e)t[i]=e[i];return t}function xs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ze(t,e,i){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?rt.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Ui(t,r,n,s,null)}function Ui(t,e,i,n,s){var o={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Gt,__i:-1,__u:0};return s==null&&K.vnode!=null&&K.vnode(o),o}function ht(t){return t.children}function at(t,e){this.props=t,this.context=e}function di(t,e){if(e==null)return t.__?di(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?di(t):null}function na(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return na(t)}}function Ls(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!En.__r++||Jr!=K.debounceRendering)&&((Jr=K.debounceRendering)||Zr)(En)}function En(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(Qr),t=qt.shift(),a=qt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=ut({},n)).__v=n.__v+1,K.vnode&&K.vnode(i),Ds(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??di(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,la(o,i,r),i.__e!=s&&na(i)));En.__r=0}function sa(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,_,v,b,w=n&&n.__k||ia,C=e.length;for(l=Xh(i,e,w,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Bi:w[p.__i]||Bi,p.__i=d,b=Ds(t,p,h,s,o,r,a,l,c,u),_=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Os(h.ref,null,p),u.push(p.ref,p.__c||_,p)),v==null&&_!=null&&(v=_),4&p.__u||h.__k===p.__k?l=oa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:_&&(l=_.nextSibling),p.__u&=-7);return i.__e=v,l}function Xh(t,e,i,n,s){var o,r,a,l,c,u=i.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Ui(null,r,null,null,null):Vi(r)?Ui(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Ui(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=Jh(r,i,l,d))!=-1&&(d--,(a=i[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=i[o])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=di(a)),da(a,a));return n}function oa(t,e,i){var n,s;if(typeof t.type=="function"){for(n=t.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=t,e=oa(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=di(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ft(t,e){return e=e||[],t==null||typeof t=="boolean"||(Vi(t)?t.some(function(i){ft(i,e)}):e.push(t)),e}function Jh(t,e,i,n){var s,o,r=t.key,a=t.type,l=e[i];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return i;if(n>(l!=null&&(2&l.__u)==0?1:0))for(s=i-1,o=i+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 ra(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Yh.test(e)?i:i+"px"}function kn(t,e,i,n,s){var o,r;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||ra(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||ra(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(ea,"$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]=i,i?n?i.u=n.u:(i.u=Is,t.addEventListener(e,o?As:Rs,o)):t.removeEventListener(e,o?As:Rs,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]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function aa(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Is++;else if(e.t<i.u)return;return i(K.event?K.event(e):e)}}}function Ds(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,_,v,b,w,C,k,L,R,O,T,E,g,m,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=K.__b)&&u(e);e:if(typeof f=="function")try{if(w=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],L=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(w,L):(e.__c=d=new at(w,L),d.constructor=f,d.render=Qh),k&&k.sub(d),d.props=w,d.state||(d.state={}),d.context=L,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ut({},d.__s)),ut(d.__s,f.getDerivedStateFromProps(w,d.__s))),p=d.props,_=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&w!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,L),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,L)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=w,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(w,d.__s,L),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,_,v)})}if(d.context=L,d.props=w,d.__P=t,d.__e=!1,O=K.__r,T=0,C){for(d.state=d.__s,d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),E=0;E<d._sb.length;E++)d.__h.push(d._sb[E]);d._sb=[]}else do d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++T<25);d.state=d.__s,d.getChildContext!=null&&(n=ut(ut({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,_)),g=u,u!=null&&u.type===ht&&u.key==null&&(g=ca(u.props.children)),a=sa(t,Vi(g)?g:[g],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(S){if(e.__v=null,l||o!=null)if(S.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--;)xs(o[m]);else e.__e=i.__e,e.__k=i.__k;K.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Zh(i.__e,e,i,n,s,o,r,l,c);return(u=K.diffed)&&u(e),128&e.__u?void 0:a}function la(t,e,i){for(var n=0;n<i.length;n++)Os(i[n],i[++n],i[++n]);K.__c&&K.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){K.__e(o,s.__v)}})}function ca(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Vi(t)?t.map(ca):ut({},t)}function Zh(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,_,v,b=i.props,w=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(w);t=document.createElementNS(s,C,w.is&&w),a&&(K.__m&&K.__m(e,o),a=!1),o=null}if(C==null)b===w||a&&t.data==w||(t.data=w);else{if(o=o&&rt.call(t.childNodes),b=i.props||Bi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in w)){if(c=="value"&&"defaultValue"in w||c=="checked"&&"defaultChecked"in w)continue;kn(t,c,null,p,s)}}for(c in w)p=w[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?_=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||kn(t,c,p,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),sa(e.type=="template"?t.content:t,Vi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&di(i,0),a,l),o!=null)for(c=o.length;c--;)xs(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=b[c])&&kn(t,c,_,b[c],s),c="checked",v!=null&&v!=t[c]&&kn(t,c,v,b[c],s))}return t}function Os(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){K.__e(s,i)}}function da(t,e,i){var n,s;if(K.unmount&&K.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Os(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){K.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&da(n[s],e,i||typeof t.type!="function");i||xs(t.__e),t.__c=t.__=t.__e=void 0}function Qh(t,e,i){return this.constructor(t,i)}function In(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),K.__&&K.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ds(e,t=(!n&&i||e).__k=Ze(ht,null,[t]),s||Bi,Bi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?rt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),la(o,t,r)}function ua(t,e){In(t,e,ua)}function Ms(t,e,i){var n,s,o,r,a=ut({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?n=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?rt.call(arguments,2):i),Ui(t.type,a,n||t.key,s||t.ref,null)}function kt(t){function e(i){var n,s;return this.getChildContext||(n=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&n.forEach(function(r){r.__e=!0,Ls(r)})},this.sub=function(o){n.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){n&&n.delete(o),r&&r.call(o)}}),i.children}return e.__c="__cC"+ta++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}rt=ia.slice,K={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Gt=0,at.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ut({},this.state),typeof t=="function"&&(t=t(ut({},i),this.props)),t&&ut(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ls(this))},at.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ls(this))},at.prototype.render=ht,qt=[],Zr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Qr=function(t,e){return t.__v.__b-e.__v.__b},En.__r=0,ea=/(PointerCapture)$|Capture$/i,Is=0,Rs=aa(!1),As=aa(!0),ta=0;var ef=0;function D(t,e,i,n,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:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ef,__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 K.vnode&&K.vnode(c),c}function Ps(){return(Ps=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t}).apply(this,arguments)}var tf=["context","children"];function nf(t){this.getChildContext=function(){return t.context};var e=t.children,i=function(n,s){if(n==null)return{};var o,r,a={},l=Object.keys(n);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=n[o]);return a}(t,tf);return Ms(e,i)}function sf(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ze(nf,Ps({},this._props,{context:t.detail.context}),function e(i,n){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;var s=[],o={},r=0,a=i.attributes,l=i.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[ha(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Ze(fa,{name:u},c):s[r]=c}var d=n?Ze(fa,null,s):s;return Ze(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?ua:In)(this._vdom,this._root)}function ha(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function of(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[ha(t)]=i,this._vdom=Ms(this._vdom,n),In(this._vdom,this._root)}}function rf(){In(this._vdom=null,this._root)}function fa(t,e){var i=this;return Ze("slot",Ps({},t,{ref:function(n){n?(i.ref=n,i._listener||(i._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function af(t,e,i,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=sf,s.prototype.attributeChangedCallback=of,s.prototype.disconnectedCallback=rf,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=i,i.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 Mt,_e,Ns,pa,$i=0,ga=[],Se=K,ma=Se.__b,va=Se.__r,_a=Se.diffed,ya=Se.__c,ba=Se.unmount,wa=Se.__;function ui(t,e){Se.__h&&Se.__h(_e,t,$i||e),$i=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return $i=1,Sa(Ta,t)}function Sa(t,e,i){var n=ui(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):Ta(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=_e,!_e.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=ui(Mt++,3);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Fs(t,e){var i=ui(Mt++,4);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function ue(t){return $i=5,Qe(function(){return{current:t}},[])}function Qe(t,e){var i=ui(Mt++,7);return Us(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ge(t,e){return $i=8,Qe(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=ui(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function lf(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Bs(){var t=ui(Mt++,11);if(!t.__){for(var e=_e.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var i=e.__m||(e.__m=[0,0]);t.__="P"+i[0]+"-"+i[1]++}return t.__}function cf(){for(var t;t=ga.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Rn),t.__H.__h.forEach(Vs),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,ma&&ma(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),wa&&wa(t,e)},Se.__r=function(t){va&&va(t),Mt=0;var e=(_e=t.__c).__H;e&&(Ns===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Rn),e.__h.forEach(Vs),e.__h=[],Mt=0)),Ns=_e},Se.diffed=function(t){_a&&_a(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ga.push(e)!==1&&pa===Se.requestAnimationFrame||((pa=Se.requestAnimationFrame)||df)(cf)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Ns=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Rn),i.__h=i.__h.filter(function(n){return!n.__||Vs(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),ya&&ya(t,e)},Se.unmount=function(t){ba&&ba(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Rn(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var Ca=typeof requestAnimationFrame=="function";function df(t){var e,i=function(){clearTimeout(n),Ca&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Ca&&(e=requestAnimationFrame(i))}function Rn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Vs(t){var e=_e;t.__c=t.__(),_e=e}function Us(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ta(t,e){return typeof e=="function"?e(t):e}const ji={},Ea=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ka=t=>"init"in t,$s=t=>!!t.write,Ia=t=>"v"in t||"e"in t,An=t=>{if("e"in t)throw t.e;if((ji?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},xn=new WeakMap,Ra=t=>{var e;return Ln(t)&&!!((e=xn.get(t))!=null&&e[0])},uf=t=>{const e=xn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},Aa=(t,e)=>{let i=xn.get(t);if(!i){i=[!0,new Set],xn.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Ln=t=>typeof(t==null?void 0:t.then)=="function",xa=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},js=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Ln(e))for(const r of n.d.keys())xa(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Ln(o)&&uf(o))},La=(t,e,i)=>{var n;const s=new Set;for(const o of((n=i.get(t))==null?void 0:n.t)||[])i.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},hf=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Hs=()=>{const t={},e=new WeakMap,i=n=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(n)),(o=e.get(n))==null||o.forEach(r=>r())};return i.add=(n,s)=>{const o=n||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)}},i},ff=t=>(t.c||(t.c=Hs()),t.m||(t.m=Hs()),t.u||(t.u=Hs()),t.f||(t.f=hf()),t),pf=Symbol(),Da=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...p)=>h.read(...p),l=(h,...p)=>h.write(...p),c=(h,p)=>{var _;return(_=h.unstable_onInit)==null?void 0:_.call(h,p)},u=(h,p)=>{var _;return(_=h.onMount)==null?void 0:_.call(h,p)},...d)=>{const h=d[0]||(T=>{if((ji?"production":void 0)!=="production"&&!T)throw new Error("Atom is undefined or null");let E=t.get(T);return E||(E={d:new Map,p:new Set,n:0},t.set(T,E),c==null||c(T,O)),E}),p=d[1]||(()=>{const T=[],E=g=>{try{g()}catch(m){T.push(m)}};do{r.f&&E(r.f);const g=new Set,m=g.add.bind(g);n.forEach(f=>{var S;return(S=e.get(f))==null?void 0:S.l.forEach(m)}),n.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),g.forEach(E),n.size&&_()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),_=d[2]||(()=>{const T=[],E=new WeakSet,g=new WeakSet,m=Array.from(n);for(;m.length;){const f=m[m.length-1],S=h(f);if(g.has(f)){m.pop();continue}if(E.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if((ji?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");g.add(f),m.pop();continue}E.add(f);for(const I of La(f,S,e))E.has(I)||m.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let A=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){A=!0;break}A&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const g=h(T);if(Ia(g)&&(e.has(T)&&i.get(T)!==g.n||Array.from(g.d).every(([M,F])=>v(M).n===F)))return g;g.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),_(),p())},S=M=>{var F;if(Ea(T,M)){const U=h(M);if(!Ia(U))if(ka(M))js(M,M.init,h);else throw new Error("no atom init");return An(U)}const G=v(M);try{return An(G)}finally{g.d.set(M,G.n),Ra(g.v)&&xa(T,g.v,G),(F=e.get(M))==null||F.t.add(T),m||f()}};let I,A;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(ji?"production":void 0)!=="production"&&!$s(T)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&$s(T)&&(A=(...M)=>{if((ji?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return w(T,...M)}finally{_(),p()}}),A}},N=g.n;try{const M=a(T,S,x);return js(T,M,h),Ln(M)&&(Aa(M,()=>I==null?void 0:I.abort()),M.then(f,f)),g}catch(M){return delete g.v,g.e=M,++g.n,g}finally{m=!1,N!==g.n&&i.get(T)===N&&(i.set(T,g.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const g=E.pop(),m=h(g);for(const f of La(g,m,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),w=d[5]||((T,...E)=>{let g=!0;const m=S=>An(v(S)),f=(S,...I)=>{var A;const x=h(S);try{if(Ea(T,S)){if(!ka(S))throw new Error("atom not writable");const N=x.n,M=I[0];js(S,M,h),C(S),N!==x.n&&(n.add(S),(A=r.c)==null||A.call(r,S),b(S));return}else return w(S,...I)}finally{g||(_(),p())}};try{return l(T,m,f,...E)}finally{g=!1}}),C=d[6]||(T=>{var E;const g=h(T),m=e.get(T);if(m&&!Ra(g.v)){for(const[f,S]of g.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(T),m.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of m.d||[])if(!g.d.has(f)){m.d.delete(f);const S=L(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const g=h(T);let m=e.get(T);if(!m){v(T);for(const f of g.d.keys())k(f).t.add(T);if(m={l:new Set,d:new Set(g.d.keys()),t:new Set},e.set(T,m),(E=r.m)==null||E.call(r,T),$s(T)){const f=()=>{let S=!0;const I=(...A)=>{try{return w(T,...A)}finally{S||(_(),p())}};try{const A=u(T,I);A&&(m.u=()=>{S=!0;try{A()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return m}),L=d[8]||(T=>{var E;const g=h(T);let m=e.get(T);if(m&&!m.l.size&&!Array.from(m.t).some(f=>{var S;return(S=e.get(f))==null?void 0:S.d.has(T)})){m.u&&o.add(m.u),m=void 0,e.delete(T),(E=r.u)==null||E.call(r,T);for(const f of g.d.keys()){const S=L(f);S==null||S.t.delete(T)}return}return m}),R=[t,e,i,n,s,o,r,a,l,c,u,h,p,_,v,b,w,C,k,L],O={get:T=>An(v(T)),set:(T,...E)=>{try{return w(T,...E)}finally{_(),p()}},sub:(T,E)=>{const m=k(T).l;return m.add(E),p(),()=>{m.delete(E),L(T),p()}}};return Object.defineProperty(O,pf,{value:R}),O},gf=ff,Oa=Aa,Ws={};let mf=0;function Dn(t,e){const i=`atom${++mf}`,n={toString(){return(Ws?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=vf,n.write=_f),n}function vf(t){return t(this)}function _f(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const yf=()=>{let t=0;const e=gf({}),i=new WeakMap,n=new WeakMap,s=Da(i,n,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=i.get(a);l.m=n.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=i.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),i),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function bf(){return(Ws?"production":void 0)!=="production"?yf():Da()}let Hi;function wf(){return Hi||(Hi=bf(),(Ws?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Hi),globalThis.__JOTAI_DEFAULT_STORE__!==Hi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Hi}function Ma(t,e){for(var i in e)t[i]=e[i];return t}function Pa(t,e){for(var i in t)if(i!=="__source"&&!(i in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}var Na=Fs;function Fa(t,e){this.props=t,this.context=e}(Fa.prototype=new at).isPureReactComponent=!0,Fa.prototype.shouldComponentUpdate=function(t,e){return Pa(this.props,t)||Pa(this.state,e)};var Ba=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ba&&Ba(t)};var Sf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Cf(t){function e(i){var n=Ma({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=Sf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Va=function(t,e){return t==null?null:ft(ft(t).map(e))},Tf={map:Va,forEach:Va,count:function(t){return t?ft(t).length:0},only:function(t){var e=ft(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ft},Ef=K.__e;K.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}Ef(t,e,i,n)};var Ua=K.unmount;function $a(t,e,i){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=Ma({},t)).__c!=null&&(t.__c.__P===i&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return $a(n,e,i)})),t}function ja(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return ja(n,e,i)}),t.__c&&t.__c.__P===e&&(t.__e&&i.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=i)),t}function Gs(){this.__u=0,this.o=null,this.__b=null}function Ha(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function On(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Ua&&Ua(t)},(Gs.prototype=new at).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Ha(n.__v),o=!1,r=function(){o||(o=!0,i.__R=null,s?s(a):a())};i.__R=r;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=ja(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(r,r)},Gs.prototype.componentWillUnmount=function(){this.o=[]},Gs.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var i=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=$a(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Ze(ht,null,t.fallback);return s&&(s.__u&=-33),[Ze(ht,null,e.__a?null:t.children),s]};var Wa=function(t,e,i){if(++i[1]===i[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(i=t.i;i;){for(;i.length>3;)i.pop()();if(i[1]<i[0])break;t.i=i=i[2]}};(On.prototype=new at).__a=function(t){var e=this,i=Ha(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Wa(e,t,n)):s()};i?i(o):o()}},On.prototype.render=function(t){this.i=null,this.l=new Map;var e=ft(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var i=e.length;i--;)this.l.set(e[i],this.i=[1,0,this.i]);return t.children},On.prototype.componentDidUpdate=On.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Wa(t,i,e)})};var Ga=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,kf=/^(?: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]/,If=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Rf=/[A-Z0-9]/g,Af=typeof document<"u",xf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};at.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(at.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var qa=K.event;function Lf(){}function Df(){return this.cancelBubble}function Of(){return this.defaultPrevented}K.event=function(t){return qa&&(t=qa(t)),t.persist=Lf,t.isPropagationStopped=Df,t.isDefaultPrevented=Of,t.nativeEvent=t};var Mf={enumerable:!1,configurable:!0,get:function(){return this.class}},za=K.vnode;K.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||Af&&r==="children"&&n==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in i&&i.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"||n!=="input"&&n!=="textarea"||xf(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":If.test(r)&&(r=l):l=r="oninput":o&&kf.test(r)?r=r.replace(Rf,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}n=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),i.class&&!i.className?(s.class=i.class,Object.defineProperty(s,"className",Mf)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=Ga,za&&za(t)};var Ka=K.__r;K.__r=function(t){Ka&&Ka(t),t.__c};var Ya=K.diffed;K.diffed=function(t){Ya&&Ya(t);var e=t.props,i=t.__e;i!=null&&t.type==="textarea"&&"value"in e&&e.value!==i.value&&(i.value=e.value==null?"":e.value)};function Xa(t){return!!t&&t.$$typeof===Ga}function Pf(t){return Xa(t)?Ms.apply(null,arguments):t}var Ja={};const Nf={},Ff=kt(void 0);function Za(t){return De(Ff)||wf()}const qs=t=>typeof(t==null?void 0:t.then)=="function",zs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Bf=Ja.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(zs(t),t)}),Ks=new WeakMap,Qa=(t,e)=>{let i=Ks.get(t);return i||(i=new Promise((n,s)=>{let o=t;const r=c=>u=>{o===c&&n(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();qs(c)?(Ks.set(c,i),o=c,c.then(r(c),a(c)),Oa(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),Oa(t,l)}),Ks.set(t,i)),i};function Ys(t,e){const{delay:i,unstable_promiseStatus:n=!Ja.use}={},s=Za(),[[o,r,a],l]=Sa(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);qs(d)&&zs(Qa(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),lf(c),qs(c)){const u=Qa(c,()=>s.get(t));return n&&zs(u),Bf(u)}return c}function Mn(t,e){const i=Za();return Ge((...s)=>{if((Nf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function el(t,e){return[Ys(t),Mn(t)]}const Xs=kt({});function Pn(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const Js=typeof window<"u",tl=Js?Fs:xe,Nn=kt(null);function Zs(t,e){t.indexOf(e)===-1&&t.push(e)}function Qs(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const It=(t,e,i)=>i>e?e:i<t?t:i;let eo=()=>{};const Rt={},il=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function nl(t){return typeof t=="object"&&t!==null}const sl=t=>/^0[^.\s]+$/u.test(t);function to(t){let e;return()=>(e===void 0&&(e=t()),e)}const et=t=>t,Vf=(t,e)=>i=>e(t(i)),Wi=(...t)=>t.reduce(Vf),Gi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class io{constructor(){this.subscriptions=[]}add(e){return Zs(this.subscriptions,e),()=>Qs(this.subscriptions,e)}notify(e,i,n){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,i,n);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,i,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const pt=t=>t*1e3,gt=t=>t/1e3;function ol(t,e){return e?t*(1e3/e):0}const rl=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Uf=1e-7,$f=12;function jf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=rl(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Uf&&++a<$f);return r}function qi(t,e,i,n){if(t===e&&i===n)return et;const s=o=>jf(o,0,1,t,i);return o=>o===0||o===1?o:rl(s(o),e,n)}const al=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ll=t=>e=>1-t(1-e),cl=qi(.33,1.53,.69,.99),no=ll(cl),dl=al(no),ul=t=>(t*=2)<1?.5*no(t):.5*(2-Math.pow(2,-10*(t-1))),so=t=>1-Math.sin(Math.acos(t)),hl=ll(so),fl=al(so),Hf=qi(.42,0,1,1),Wf=qi(0,0,.58,1),pl=qi(.42,0,.58,1),Gf=t=>Array.isArray(t)&&typeof t[0]!="number",gl=t=>Array.isArray(t)&&typeof t[0]=="number",qf={linear:et,easeIn:Hf,easeInOut:pl,easeOut:Wf,circIn:so,circInOut:fl,circOut:hl,backIn:no,backInOut:dl,backOut:cl,anticipate:ul},zf=t=>typeof t=="string",ml=t=>{if(gl(t)){eo(t.length===4);const[e,i,n,s]=t;return qi(e,i,n,s)}else if(zf(t))return qf[t];return t},Fn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],vl={value:null};function Kf(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,p=!1)=>{const v=p&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&vl.value&&vl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Yf=40;function _l(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Fn.reduce((k,L)=>(k[L]=Kf(o,e?L:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:_}=r,v=()=>{const k=Rt.useManualTiming?s.timestamp:performance.now();i=!1,Rt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Yf),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),_.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:Fn.reduce((k,L)=>{const R=r[L];return k[L]=(O,T=!1,E=!1)=>(i||b(),R.schedule(O,T,E)),k},{}),cancel:k=>{for(let L=0;L<Fn.length;L++)r[Fn[L]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:oo}=_l(typeof requestAnimationFrame<"u"?requestAnimationFrame:et,!0);let Bn;function Xf(){Bn=void 0}const qe={now:()=>(Bn===void 0&&qe.set(Pe.isProcessing||Rt.useManualTiming?Pe.timestamp:performance.now()),Bn),set:t=>{Bn=t,queueMicrotask(Xf)}},yl=t=>e=>typeof e=="string"&&e.startsWith(t),ro=yl("--"),Jf=yl("var(--"),ao=t=>Jf(t)?Zf.test(t.split("/*")[0].trim()):!1,Zf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,hi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},zi={...hi,transform:t=>It(0,1,t)},Vn={...hi,default:1},Ki=t=>Math.round(t*1e5)/1e5,lo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Qf(t){return t==null}const ep=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,co=(t,e)=>i=>!!(typeof i=="string"&&ep.test(i)&&i.startsWith(t)||e&&!Qf(i)&&Object.prototype.hasOwnProperty.call(i,e)),bl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(lo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},tp=t=>It(0,255,t),uo={...hi,transform:t=>Math.round(tp(t))},zt={test:co("rgb","red"),parse:bl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+uo.transform(t)+", "+uo.transform(e)+", "+uo.transform(i)+", "+Ki(zi.transform(n))+")"};function ip(t){let e="",i="",n="",s="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),n=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),n=t.substring(3,4),s=t.substring(4,5),e+=e,i+=i,n+=n,s+=s),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:s?parseInt(s,16)/255:1}}const ho={test:co("#"),parse:ip,transform:zt.transform},Yi=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Yi("deg"),mt=Yi("%"),Y=Yi("px"),np=Yi("vh"),sp=Yi("vw"),wl={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},fi={test:co("hsl","hue"),parse:bl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(Ki(e))+", "+mt.transform(Ki(i))+", "+Ki(zi.transform(n))+")"},Ie={test:t=>zt.test(t)||ho.test(t)||fi.test(t),parse:t=>zt.test(t)?zt.parse(t):fi.test(t)?fi.parse(t):ho.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):fi.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},op=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function rp(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(lo))==null?void 0:e.length)||0)+(((i=t.match(op))==null?void 0:i.length)||0)>0}const Sl="number",Cl="color",ap="var",lp="var(",Tl="${}",cp=/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 Xi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(cp,l=>(Ie.test(l)?(n.color.push(o),s.push(Cl),i.push(Ie.parse(l))):l.startsWith(lp)?(n.var.push(o),s.push(ap),i.push(l)):(n.number.push(o),s.push(Sl),i.push(parseFloat(l))),++o,Tl)).split(Tl);return{values:i,split:a,indexes:n,types:s}}function El(t){return Xi(t).values}function kl(t){const{split:e,types:i}=Xi(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===Sl?o+=Ki(s[r]):a===Cl?o+=Ie.transform(s[r]):o+=s[r]}return o}}const dp=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function up(t){const e=El(t);return kl(t)(e.map(dp))}const Ft={test:rp,parse:El,createTransformer:kl,getAnimatableNone:up};function fo(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function hp({hue:t,saturation:e,lightness:i,alpha:n}){t/=360,e/=100,i/=100;let s=0,o=0,r=0;if(!e)s=o=r=i;else{const a=i<.5?i*(1+e):i+e-i*e,l=2*i-a;s=fo(l,a,t+1/3),o=fo(l,a,t),r=fo(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Un(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,po=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},fp=[ho,zt,fi],pp=t=>fp.find(e=>e.test(t));function Il(t){const e=pp(t);if(!e)return!1;let i=e.parse(t);return e===fi&&(i=hp(i)),i}const Rl=(t,e)=>{const i=Il(t),n=Il(e);if(!i||!n)return Un(t,e);const s={...i};return o=>(s.red=po(i.red,n.red,o),s.green=po(i.green,n.green,o),s.blue=po(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},go=new Set(["none","hidden"]);function gp(t,e){return go.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function mp(t,e){return i=>Ce(t,e,i)}function mo(t){return typeof t=="number"?mp:typeof t=="string"?ao(t)?Un:Ie.test(t)?Rl:yp:Array.isArray(t)?Al:typeof t=="object"?Ie.test(t)?Rl:vp:Un}function Al(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>mo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function vp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=mo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function _p(t,e){const i=[],n={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][n[o]],a=t.values[r]??0;i[s]=a,n[o]++}return i}const yp=(t,e)=>{const i=Ft.createTransformer(e),n=Xi(t),s=Xi(e);return n.indexes.var.length===s.indexes.var.length&&n.indexes.color.length===s.indexes.color.length&&n.indexes.number.length>=s.indexes.number.length?go.has(t)&&!s.values.length||go.has(e)&&!n.values.length?gp(t,e):Wi(Al(_p(n,s),s.values),i):Un(t,e)};function xl(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):mo(t)(t,e)}const bp=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:qe.now()}},Ll=(t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let o=0;o<s;o++)n+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${n.substring(0,n.length-2)})`},$n=2e4;function vo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<$n;)e+=i,n=t.next(e);return e>=$n?1/0:e}function wp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(vo(n),$n);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const Sp=5;function Dl(t,e,i){const n=Math.max(e-Sp,0);return ol(i-t(n),e-n)}const Te={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},_o=.001;function Cp({duration:t=Te.duration,bounce:e=Te.bounce,velocity:i=Te.velocity,mass:n=Te.mass}){let s,o,r=1-e;r=It(Te.minDamping,Te.maxDamping,r),t=It(Te.minDuration,Te.maxDuration,gt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,p=yo(c,r),_=Math.exp(-d);return _o-h/p*_},o=c=>{const d=c*r*t,h=d*i+i,p=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-d),v=yo(Math.pow(c,2),r);return(-s(c)+_o>0?-1:1)*((h-p)*_)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-_o+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Ep(s,o,a);if(t=pt(t),isNaN(l))return{stiffness:Te.stiffness,damping:Te.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const Tp=12;function Ep(t,e,i){let n=i;for(let s=1;s<Tp;s++)n=n-t(n)/e(n);return n}function yo(t,e){return t*Math.sqrt(1-e*e)}const kp=["duration","bounce"],Ip=["stiffness","damping","mass"];function Ol(t,e){return e.some(i=>t[i]!==void 0)}function Rp(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!Ol(t,Ip)&&Ol(t,kp))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*It(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Te.mass,stiffness:s,damping:o}}else{const i=Cp(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function jn(t=Te.visualDuration,e=Te.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:p}=Rp({...i,velocity:-gt(i.velocity||0)}),_=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,w=gt(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Te.restSpeed.granular:Te.restSpeed.default),s||(s=C?Te.restDelta.granular:Te.restDelta.default);let k;if(v<1){const R=yo(w,v);k=O=>{const T=Math.exp(-v*w*O);return r-T*((_+v*w*b)/R*Math.sin(R*O)+b*Math.cos(R*O))}}else if(v===1)k=R=>r-Math.exp(-w*R)*(b+(_+w*b)*R);else{const R=w*Math.sqrt(v*v-1);k=O=>{const T=Math.exp(-v*w*O),E=Math.min(R*O,300);return r-T*((_+v*w*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const L={calculatedDuration:p&&d||null,next:R=>{const O=k(R);if(p)a.done=R>=d;else{let T=R===0?_:0;v<1&&(T=R===0?pt(_):Dl(k,R,O));const E=Math.abs(T)<=n,g=Math.abs(r-O)<=s;a.done=E&&g}return a.value=a.done?r:O,a},toString:()=>{const R=Math.min(vo(L),$n),O=Ll(T=>L.next(R*T).value,R,30);return R+"ms "+O},toTransition:()=>{}};return L}jn.applyToOptions=t=>{const e=wp(t,100,jn);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function bo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=E=>a!==void 0&&E<a||l!==void 0&&E>l,_=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let v=i*e;const b=d+v,w=r===void 0?b:r(b);w!==b&&(v=w-d);const C=E=>-v*Math.exp(-E/n),k=E=>w+C(E),L=E=>{const g=C(E),m=k(E);h.done=Math.abs(g)<=c,h.value=h.done?w:m};let R,O;const T=E=>{p(h.value)&&(R=E,O=jn({keyframes:[h.value,_(h.value)],velocity:Dl(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let g=!1;return!O&&R===void 0&&(g=!0,L(E),T(E)),R!==void 0&&E>=R?O.next(E-R):(!g&&L(E),h)}}}function Ap(t,e,i){const n=[],s=i||Rt.mix||xl,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]||et:e;a=Wi(l,a)}n.push(a)}return n}function xp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(eo(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=Ap(e,n,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=Gi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Lp(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Gi(0,e,n);t.push(Ce(i,1,s))}}function Dp(t){const e=[0];return Lp(e,t.length-1),e}function Op(t,e){return t.map(i=>i*e)}function Mp(t,e){return t.map(()=>e||pl).splice(0,t.length-1)}function Ji({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Gf(n)?n.map(ml):ml(n),o={done:!1,value:e[0]},r=Op(i&&i.length===e.length?i:Dp(e),t),a=xp(r,e,{ease:Array.isArray(s)?s:Mp(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Pp=t=>t!==null;function wo(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Pp),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Np={decay:bo,inertia:bo,tween:Ji,keyframes:Ji,spring:jn};function Ml(t){typeof t.type=="string"&&(t.type=Np[t.type])}class So{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const Fp=t=>t/100;class Co extends So{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==qe.now()&&this.tick(qe.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(n=this.options).onStop)==null||s.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Ml(e);const{type:i=Ji,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Ji;l!==Ji&&typeof a[0]!="number"&&(this.mixKeyframes=Wi(Fp,xl(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=vo(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:p,type:_,onUpdate:v,finalKeyframe:b}=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)),i?this.currentTime=e:this.updateTime(e);const w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,L=n;if(d){const E=Math.min(this.currentTime,s)/a;let g=Math.floor(E),m=E%1;!m&&E>=1&&(m=1),m===1&&g--,g=Math.min(g,d+1),!!(g%2)&&(h==="reverse"?(m=1-m,p&&(m-=p/a)):h==="mirror"&&(L=r)),k=It(0,1,m)*a}const R=C?{done:!1,value:u[0]}:L.next(k);o&&(R.value=o(R.value));let{done:O}=R;!C&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return T&&_!==bo&&(R.value=wo(u,this.options,b,this.speed)),v&&v(R.value),T&&this.finish(),R}then(e,i){return this.finished.then(e,i)}get duration(){return gt(this.calculatedDuration)}get time(){return gt(this.currentTime)}set time(e){var i;e=pt(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),(i=this.driver)==null||i.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(qe.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=gt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=bp,startTime:i}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=i??n),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(qe.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.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 i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function Bp(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,To=t=>{const e=Kt(Math.atan2(t[1],t[0]));return Eo(e)},Vp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:To,rotateZ:To,skewX:t=>Kt(Math.atan(t[1])),skewY:t=>Kt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Eo=t=>(t=t%360,t<0&&(t+=360),t),Pl=To,Nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Fl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Up={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Nl,scaleY:Fl,scale:t=>(Nl(t)+Fl(t))/2,rotateX:t=>Eo(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>Eo(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Pl,rotate:Pl,skewX:t=>Kt(Math.atan(t[4])),skewY:t=>Kt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ko(t){return t.includes("scale")?1:0}function Io(t,e){if(!t||t==="none")return ko(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Up,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Vp,s=a}if(!s)return ko(e);const o=n[e],r=s[1].split(",").map(jp);return typeof o=="function"?o(r):r[o]}const $p=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Io(i,e)};function jp(t){return parseFloat(t.trim())}const pi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],gi=new Set(pi),Bl=t=>t===hi||t===Y,Hp=new Set(["x","y","z"]),Wp=pi.filter(t=>!Hp.has(t));function Gp(t){const e=[];return Wp.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Yt={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),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})=>Io(e,"x"),y:(t,{transform:e})=>Io(e,"y")};Yt.translateX=Yt.x,Yt.translateY=Yt.y;const Xt=new Set;let Ro=!1,Ao=!1,xo=!1;function Vl(){if(Ao){const t=Array.from(Xt).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=Gp(n);s.length&&(i.set(n,s),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const s=i.get(n);s&&s.forEach(([o,r])=>{var a;(a=n.getValue(o))==null||a.set(r)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}Ao=!1,Ro=!1,Xt.forEach(t=>t.complete(xo)),Xt.clear()}function Ul(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ao=!0)})}function qp(){xo=!0,Ul(),Vl(),xo=!1}class Lo{constructor(e,i,n,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=n,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Xt.add(this),Ro||(Ro=!0,we.read(Ul),we.resolveKeyframes(Vl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:n,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(n&&i){const a=n.readValue(i,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Bp(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Xt.delete(this)}cancel(){this.state==="scheduled"&&(Xt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const zp=t=>t.startsWith("--");function Kp(t,e,i){zp(e)?t.style.setProperty(e,i):t.style[e]=i}const Yp=to(()=>window.ScrollTimeline!==void 0),Xp={};function Jp(t,e){const i=to(t);return()=>Xp[e]??i()}const $l=Jp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zi=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,jl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zi([0,.65,.55,1]),circOut:Zi([.55,0,1,.45]),backIn:Zi([.31,.01,.66,-.59]),backOut:Zi([.33,1.53,.69,.99])};function Hl(t,e){if(t)return typeof t=="function"?$l()?Ll(t,e):"ease-out":gl(t)?Zi(t):Array.isArray(t)?t.map(i=>Hl(i,e)||jl.easeOut):jl[t]}function Zp(t,e,i,{delay:n=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:i};l&&(u.offset=l);const d=Hl(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function Wl(t){return typeof t=="function"&&"applyToOptions"in t}function Qp({type:t,...e}){return Wl(t)&&$l()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class eg extends So{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,eo(typeof e.type!="string");const c=Qp(e);this.animation=Zp(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=wo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Kp(i,n,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.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,i;this.isPseudoElement||(i=(e=this.animation).commitStyles)==null||i.call(e)}get duration(){var i,n;const e=((n=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:n.call(i).duration)||0;return gt(Number(e))}get time(){return gt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=pt(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:i}){var n;return this.allowFlatten&&((n=this.animation.effect)==null||n.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Yp()?(this.animation.timeline=e,et):i(this)}}const Gl={anticipate:ul,backInOut:dl,circInOut:fl};function tg(t){return t in Gl}function ig(t){typeof t.ease=="string"&&tg(t.ease)&&(t.ease=Gl[t.ease])}const ql=10;class ng extends eg{constructor(e){ig(e),Ml(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:n,onComplete:s,element:o,...r}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const a=new Co({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-ql).value,a.sample(l).value,ql),a.stop()}}const zl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function sg(t){const e=t[0];if(t.length===1)return!0;for(let i=0;i<t.length;i++)if(t[i]!==e)return!0}function og(t,e,i,n){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=zl(s,e),a=zl(o,e);return!r||!a?!1:sg(t)||(i==="spring"||Wl(i))&&n}function Do(t){return nl(t)&&"offsetHeight"in t}const rg=new Set(["opacity","clipPath","filter","transform"]),ag=to(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function lg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Do((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return ag()&&i&&rg.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const cg=40;class dg extends So{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var _;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=qe.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},p=(u==null?void 0:u.KeyframeResolver)||Lo;this.keyframeResolver=new p(a,(v,b,w)=>this.onKeyframesResolved(v,b,h,!w),l,c,u),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,i,n,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=n;this.resolvedAt=qe.now(),og(e,o,r,a)||((Rt.instantAnimations||!l)&&(u==null||u(wo(e,n,i))),e[0]=e[e.length-1],n.duration=0,n.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>cg?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&lg(h)?new ng({...h,element:h.motionValue.owner.current}):new Co(h);p.finished.then(()=>this.notifyFinished()).catch(et),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),qp()),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 ug=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hg(t){const e=ug.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Kl(t,e,i=1){const[n,s]=hg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return il(r)?parseFloat(r):r}return ao(s)?Kl(s,e,i+1):s}function Oo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Yl=new Set(["width","height","top","left","right","bottom",...pi]),fg={test:t=>t==="auto",parse:t=>t},Xl=t=>e=>e.test(t),Jl=[hi,Y,mt,Nt,sp,np,fg],Zl=t=>Jl.find(Xl(t));function pg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||sl(t):!0}const gg=new Set(["brightness","contrast","saturate","opacity"]);function mg(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(lo)||[];if(!n)return t;const s=i.replace(n,"");let o=gg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const vg=/\b([a-z-]*)\(.*?\)/gu,Mo={...Ft,getAnimatableNone:t=>{const e=t.match(vg);return e?e.map(mg).join(" "):t}},Ql={...hi,transform:Math.round},Po={borderWidth:Y,borderTopWidth:Y,borderRightWidth:Y,borderBottomWidth:Y,borderLeftWidth:Y,borderRadius:Y,radius:Y,borderTopLeftRadius:Y,borderTopRightRadius:Y,borderBottomRightRadius:Y,borderBottomLeftRadius:Y,width:Y,maxWidth:Y,height:Y,maxHeight:Y,top:Y,right:Y,bottom:Y,left:Y,padding:Y,paddingTop:Y,paddingRight:Y,paddingBottom:Y,paddingLeft:Y,margin:Y,marginTop:Y,marginRight:Y,marginBottom:Y,marginLeft:Y,backgroundPositionX:Y,backgroundPositionY:Y,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Vn,scaleX:Vn,scaleY:Vn,scaleZ:Vn,skew:Nt,skewX:Nt,skewY:Nt,distance:Y,translateX:Y,translateY:Y,translateZ:Y,x:Y,y:Y,z:Y,perspective:Y,transformPerspective:Y,opacity:zi,originX:wl,originY:wl,originZ:Y},zIndex:Ql,fillOpacity:zi,strokeOpacity:zi,numOctaves:Ql},_g={...Po,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:Mo,WebkitFilter:Mo},ec=t=>_g[t];function tc(t,e){let i=ec(t);return i!==Mo&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const yg=new Set(["auto","none","0"]);function bg(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!yg.has(o)&&Xi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=tc(i,s)}class wg extends Lo{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),ao(c))){const u=Kl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Yl.has(n)||e.length!==2)return;const[s,o]=e,r=Zl(s),a=Zl(o);if(r!==a)if(Bl(r)&&Bl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Yt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||pg(e[s]))&&n.push(s);n.length&&bg(e,n,i)}measureInitialState(){const{element:e,unresolvedKeyframes:i,name:n}=this;if(!e||!e.current)return;n==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Yt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i[0]=this.measuredOrigin;const s=i[i.length-1];s!==void 0&&e.getValue(n,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:i,unresolvedKeyframes:n}=this;if(!e||!e.current)return;const s=e.getValue(i);s&&s.jump(this.measuredOrigin,!1);const o=n.length-1,r=n[o];n[o]=Yt[i](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 Sg(t,e,i){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let n=document;const s=(i==null?void 0:i[t])??n.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const ic=(t,e)=>e&&typeof t=="number"?e.transform(t):t,nc=30,Cg=t=>!isNaN(parseFloat(t));class Tg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=qe.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),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=i.owner}setCurrent(e){this.current=e,this.updatedAt=qe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Cg(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new io);const n=this.events[e].add(i);return e==="change"?()=>{n(),we.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e,i=!0){!i||!this.passiveEffect?this.updateAndNotify(e,i):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,i,n){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&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=qe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>nc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,nc);return ol(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),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,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function mi(t,e){return new Tg(t,e)}const{schedule:No}=_l(queueMicrotask,!1),lt={x:!1,y:!1};function sc(){return lt.x||lt.y}function Eg(t){return t==="x"||t==="y"?lt[t]?null:(lt[t]=!0,()=>{lt[t]=!1}):lt.x||lt.y?null:(lt.x=lt.y=!0,()=>{lt.x=lt.y=!1})}function oc(t,e){const i=Sg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function rc(t){return!(t.pointerType==="touch"||sc())}function kg(t,e,i={}){const[n,s,o]=oc(t,i),r=a=>{if(!rc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{rc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const ac=(t,e)=>e?t===e?!0:ac(t,e.parentElement):!1,Fo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ig=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Rg(t){return Ig.has(t.tagName)||t.tabIndex!==-1}const Hn=new WeakSet;function lc(t){return e=>{e.key==="Enter"&&t(e)}}function Bo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Ag=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=lc(()=>{if(Hn.has(i))return;Bo(i,"down");const s=lc(()=>{Bo(i,"up")}),o=()=>Bo(i,"cancel");i.addEventListener("keyup",s,e),i.addEventListener("blur",o,e)});i.addEventListener("keydown",n,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),e)};function cc(t){return Fo(t)&&!sc()}function xg(t,e,i={}){const[n,s,o]=oc(t,i),r=a=>{const l=a.currentTarget;if(!cc(a))return;Hn.add(l);const c=e(l,a),u=(p,_)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Hn.has(l)&&Hn.delete(l),cc(p)&&typeof c=="function"&&c(p,{success:_})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||ac(l,p.target))},h=p=>{u(p,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Do(a)&&(a.addEventListener("focus",c=>Ag(c,s)),!Rg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function dc(t){return nl(t)&&"ownerSVGElement"in t}function Lg(t){return dc(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),Dg=[...Jl,Ie,Ft],Og=t=>Dg.find(Xl(t)),Qi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Mg extends at{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Do(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=i.offsetHeight||0,o.width=i.offsetWidth||0,o.top=i.offsetTop,o.left=i.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Pg({children:t,isPresent:e,anchorX:i,root:n}){const s=Bs(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(Qi);return Na(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const p=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=n??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,115 +6,115 @@ var _w=Object.defineProperty;var yw=(ot,z,Gt)=>z in ot?_w(ot,z,{enumerable:!0,co
6
6
  ${p}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),D(Pg,{isPresent:e,childRef:o,sizeRef:r,children:Nf(t,{ref:o})})}const Fg=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Pn(Vg),u=Vs();let d=!0,h=Ze(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:p=>{c.set(p,!0);for(const _ of c.values())if(!_)return;n&&n()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[i,c,n]);return o&&d&&(h={...h}),Ze(()=>{c.forEach((p,_)=>c.set(_,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Ng,{isPresent:i,anchorX:a,root:l,children:t})),D(Nn.Provider,{value:h,children:t})};function Vg(){return new Map}function lc(t=!0){const e=De(Nn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Vs();xe(()=>{if(t)return s(o)},[t]);const r=He(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Hn=t=>t.key||"";function cc(t){const e=[];return Ef.forEach(t,i=>{za(i)&&e.push(i)}),e}const Bg=({children:t,custom:e,initial:i=!0,onExitComplete:n,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=lc(r),d=Ze(()=>cc(t),[t]),h=r&&!c?[]:d.map(Hn),p=ue(!0),_=ue(d),v=Pn(()=>new Map),[b,w]=Ae(d),[C,k]=Ae(d);Za(()=>{p.current=!1,_.current=d;for(let O=0;O<C.length;O++){const T=Hn(C[O]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const L=[];if(d!==b){let O=[...d];for(let T=0;T<C.length;T++){const E=C[T],g=Hn(E);h.includes(g)||(O.splice(T,0,E),L.push(E))}return o==="wait"&&L.length&&(O=L),k(cc(O)),w(d),null}const{forceRender:R}=De(Xs);return D(ut,{children:C.map(O=>{const T=Hn(O),E=r&&!c?!1:d===C||h.includes(T),g=()=>{if(v.has(T))v.set(T,!0);else return;let m=!0;v.forEach(f=>{f||(m=!1)}),m&&(R==null||R(),k(_.current),r&&(u==null||u()),n&&n())};return D(Fg,{isPresent:E,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:g,anchorX:a,children:O},T)})})},dc=kt({strict:!1}),uc={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"]},vi={};for(const t in uc)vi[t]={isEnabled:e=>uc[t].some(i=>!!e[i])};function Ug(t){for(const e in t)vi[e]={...vi[e],...t[e]}}const $g=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 Gn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||$g.has(t)}let hc=t=>!Gn(t);function fc(t){typeof t=="function"&&(hc=e=>e.startsWith("on")?!Gn(e):t(e))}try{fc(require("@emotion/is-prop-valid").default)}catch{}function jg(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(hc(s)||i===!0&&Gn(s)||!e&&!Gn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Wg({children:t,isValidProp:e,...i}){e&&fc(e),i={...De(Qi),...i},i.isStatic=Pn(()=>i.isStatic);const n=Ze(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Qi.Provider,{value:n,children:t})}function Hg(t){if(typeof Proxy>"u")return t;const e=new Map,i=(...n)=>t(...n);return new Proxy(i,{get:(n,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const qn=kt({});function zn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function en(t){return typeof t=="string"||Array.isArray(t)}const Bo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Uo=["initial",...Bo];function Kn(t){return zn(t.animate)||Uo.some(e=>en(t[e]))}function pc(t){return!!(Kn(t)||t.variants)}function Gg(t,e){if(Kn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||en(i)?i:void 0,animate:en(n)?n:void 0}}return t.inherit!==!1?e:{}}function qg(t){const{initial:e,animate:i}=Gg(t,De(qn));return Ze(()=>({initial:e,animate:i}),[gc(e),gc(i)])}function gc(t){return Array.isArray(t)?t.join(" "):t}const zg=Symbol.for("motionComponentSymbol");function _i(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Kg(t,e,i){return He(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):_i(i)&&(i.current=n))},[e])}const $o=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),mc="data-"+$o("framerAppearId"),vc=kt({});function Yg(t,e,i,n,s){var v,b;const{visualElement:o}=De(qn),r=De(dc),a=De(Nn),l=De(Qi).reducedMotion,c=ue(null);n=n||r.renderer,!c.current&&n&&(c.current=n(t,{visualState:e,parent:o,props:i,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=De(vc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Xg(c.current,i,s,d);const h=ue(!1);Oa(()=>{u&&h.current&&u.update(i,a)});const p=i[mc],_=ue(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return Za(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),No.render(u.render),_.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!_.current&&u.animationState&&u.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),_.current=!1))}),u}function Xg(t,e,i,n){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new i(t.latestValues,e["data-framer-portal-id"]?void 0:_c(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&_i(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function _c(t){if(t)return t.options.allowProjection!==!1?t.projection:_c(t.parent)}function Jg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Ug(t);function o(a,l){let c;const u={...De(Qi),...a,layoutId:Zg(a)},{isStatic:d}=u,h=qg(a),p=n(a,d);if(!d&&Js){Qg();const _=em(u);c=_.MeasureLayout,h.visualElement=Yg(s,p,u,e,_.ProjectionNode)}return D(qn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,Kg(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Tf(o);return r[zg]=s,r}function Zg({layoutId:t}){const e=De(Xs).id;return e&&t!==void 0?e+"-"+t:t}function Qg(t,e){De(dc).strict}function em(t){const{drag:e,layout:i}=vi;if(!e&&!i)return{};const n={...e,...i};return{MeasureLayout:e!=null&&e.isEnabled(t)||i!=null&&i.isEnabled(t)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}const tn={};function tm(t){for(const e in t)tn[e]=t[e],ro(e)&&(tn[e].isCSSVariable=!0)}function yc(t,{layout:e,layoutId:i}){return gi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!tn[t]||t==="opacity")}const im={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},nm=pi.length;function sm(t,e,i){let n="",s=!0;for(let o=0;o<nm;o++){const r=pi[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||i){const c=Ql(a,Po[r]);if(!l){s=!1;const u=im[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function jo(t,e,i){const{style:n,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(gi.has(l)){r=!0;continue}else if(ro(l)){s[l]=c;continue}else{const u=Ql(c,Po[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=sm(e,t.transform,i):n.transform&&(n.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;n.transformOrigin=`${l} ${c} ${u}`}}const Wo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function bc(t,e,i){for(const n in e)!Be(e[n])&&!yc(n,i)&&(t[n]=e[n])}function om({transformTemplate:t},e){return Ze(()=>{const i=Wo();return jo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function rm(t,e){const i=t.style||{},n={};return bc(n,i,t),Object.assign(n,om(t,e)),n}function am(t,e){const i={},n=rm(t,e);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=n,i}const lm={offset:"stroke-dashoffset",array:"stroke-dasharray"},cm={offset:"strokeDashoffset",array:"strokeDasharray"};function dm(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?lm:cm;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function wc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(jo(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),i!==void 0&&(d.y=i),n!==void 0&&(d.scale=n),s!==void 0&&dm(d,s,o,r,!1)}const Sc=()=>({...Wo(),attrs:{}}),Cc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function um(t,e,i,n){const s=Ze(()=>{const o=Sc();return wc(o,e,Cc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};bc(o,t.style,t),s.style={...o,...s.style}}return s}const hm=["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 Ho(t){return typeof t!="string"||t.includes("-")?!1:!!(hm.indexOf(t)>-1||/[A-Z]/u.test(t))}function fm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(Ho(i)?um:am)(n,o,r,i),c=jg(n,typeof i=="string",t),u=i!==ut?{...c,...l,ref:s}:{},{children:d}=n,h=Ze(()=>Be(d)?d.get():d,[d]);return Je(i,{...u,children:h})}}function Tc(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function Go(t,e,i,n){if(typeof e=="function"){const[s,o]=Tc(n);e=e(i!==void 0?i:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=Tc(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Yn(t){return Be(t)?t.get():t}function pm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:gm(i,n,s,t),renderState:e()}}const Ec=t=>(e,i)=>{const n=De(qn),s=De(Nn),o=()=>pm(t,e,n,s);return i?o():Pn(o)};function gm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Yn(o[h]);let{initial:r,animate:a}=t;const l=Kn(t),c=pc(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=i?i.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!zn(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const _=Go(t,h[p]);if(_){const{transitionEnd:v,transition:b,...w}=_;for(const C in w){let k=w[C];if(Array.isArray(k)){const L=u?k.length-1:0;k=k[L]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function qo(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Be(n[r])||e.style&&Be(e.style[r])||yc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const mm={useVisualState:Ec({scrapeMotionValuesFromProps:qo,createRenderState:Wo})};function kc(t,e,i){const n=qo(t,e,i);for(const s in t)if(Be(t[s])||Be(e[s])){const o=pi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const vm={useVisualState:Ec({scrapeMotionValuesFromProps:kc,createRenderState:Sc})};function _m(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Ho(n)?vm:mm,preloadedFeatures:t,useRender:fm(s),createVisualElement:e,Component:n};return Jg(r)}}function nn(t,e,i){const n=t.getProps();return Go(n,e,i!==void 0?i:n.custom,t)}const zo=t=>Array.isArray(t);function ym(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,mi(i))}function bm(t){return zo(t)?t[t.length-1]||0:t}function wm(t,e){const i=nn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=bm(o[r]);ym(t,r,a)}}function Sm(t){return!!(Be(t)&&t.add)}function Ko(t,e){const i=t.getValue("willChange");if(Sm(i))return i.add(e);if(!i&&Rt.WillChange){const n=new Rt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function Ic(t){return t.props[mc]}const Cm=t=>t!==null;function Tm(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Cm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Em={type:"spring",stiffness:500,damping:25,restSpeed:10},km=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Im={type:"keyframes",duration:.8},Rm={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Am=(t,{keyframes:e})=>e.length>2?Im:gi.has(t)?t.startsWith("scale")?km(e[1]):Em:Rm;function xm({when:t,delay:e,delayChildren:i,staggerChildren:n,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Yo=(t,e,i,n={},s,o)=>r=>{const a=Oo(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-ft(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};xm(a)||Object.assign(u,Am(t,u)),u.duration&&(u.duration=ft(u.duration)),u.repeatDelay&&(u.repeatDelay=ft(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(Rt.instantAnimations||Rt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=Tm(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Co(u):new ug(u)};function Lm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Rc(t,e,{delay:i=0,transitionOverride:n,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;n&&(o=n);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&Lm(c,u))continue;const p={delay:i,...Oo(o||{},u)},_=d.get();if(_!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===_&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=Ic(t);if(w){const C=window.MotionHandoffAnimation(w,u,we);C!==null&&(p.startTime=C,v=!0)}}Ko(t,u),d.start(Yo(u,d,h,t.shouldReduceMotion&&ql.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&wm(t,r)})}),l}function Xo(t,e,i={}){var l;const n=nn(t,e,i.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=n||{};i.transitionOverride&&(s=i.transitionOverride);const o=n?()=>Promise.all(Rc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Dm(t,e,c,u,d,h,i)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(i.delay)])}function Dm(t,e,i=0,n=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof n=="function",d=u?h=>n(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(Om).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(Xo(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Om(t,e){return t.sortNodePosition(e)}function Mm(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>Xo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=Xo(t,e,i);else{const s=typeof e=="function"?nn(t,e,i.custom):e;n=Promise.all(Rc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Ac(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(e[n]!==t[n])return!1;return!0}const Pm=Uo.length;function xc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?xc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Pm;i++){const n=Uo[i],s=t.props[n];(en(s)||s===!1)&&(e[n]=s)}return e}const Nm=[...Bo].reverse(),Fm=Bo.length;function Vm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Mm(t,i,n)))}function Bm(t){let e=Vm(t),i=Lc(),n=!0;const s=l=>(c,u)=>{var h;const d=nn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:_,...v}=d;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=xc(t.parent)||{},d=[],h=new Set;let p={},_=1/0;for(let b=0;b<Fm;b++){const w=Nm[b],C=i[w],k=c[w]!==void 0?c[w]:u[w],L=en(k),R=w===l?C.isActive:null;R===!1&&(_=b);let O=k===u[w]&&k!==c[w]&&L;if(O&&n&&t.manuallyAnimateOnMount&&(O=!1),C.protectedKeys={...p},!C.isActive&&R===null||!k&&!C.prevProp||zn(k)||typeof k=="boolean")continue;const T=Um(C.prevProp,k);let E=T||w===l&&C.isActive&&!O&&L||b>_&&L,g=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(w),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},A=M=>{E=!0,h.has(M)&&(g=!0,h.delete(M)),C.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in I){const F=f[M],H=S[M];if(p.hasOwnProperty(M))continue;let $=!1;zo(F)&&zo(H)?$=!Ac(F,H):$=F!==H,$?F!=null?A(M):h.add(M):F!==void 0&&h.has(M)?A(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(p={...p,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(O&&T)||g)&&d.push(...m.map(M=>({animation:M,options:{type:w}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const w=nn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(b.transition=w.transition)}h.forEach(w=>{const C=t.getBaseTarget(w),k=t.getValue(w);k&&(k.liveStyle=!0),b[w]=C??null}),d.push({animation:b})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var p;return(p=h.animationState)==null?void 0:p.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=Lc(),n=!0}}}function Um(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Ac(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Vt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class $m extends Vt{constructor(e){super(e),e.animationState||(e.animationState=Bm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();zn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let jm=0;class Wm extends Vt{constructor(){super(...arguments),this.id=jm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const s=this.node.animationState.setActive("exit",!e);i&&!e&&s.then(()=>{i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Hm={animation:{Feature:$m},exit:{Feature:Wm}};function sn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function on(t){return{point:{x:t.pageX,y:t.pageY}}}const Gm=t=>e=>Fo(e)&&t(e,on(e));function rn(t,e,i,n){return sn(t,e,Gm(i),n)}function Dc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function qm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function zm(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}const Oc=1e-4,Km=1-Oc,Ym=1+Oc,Mc=.01,Xm=0-Mc,Jm=0+Mc;function $e(t){return t.max-t.min}function Zm(t,e,i){return Math.abs(t-e)<=i}function Pc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=$e(i)/$e(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Km&&t.scale<=Ym||isNaN(t.scale))&&(t.scale=1),(t.translate>=Xm&&t.translate<=Jm||isNaN(t.translate))&&(t.translate=0)}function an(t,e,i,n){Pc(t.x,e.x,i.x,n?n.originX:void 0),Pc(t.y,e.y,i.y,n?n.originY:void 0)}function Nc(t,e,i){t.min=i.min+e.min,t.max=t.min+$e(e)}function Qm(t,e,i){Nc(t.x,e.x,i.x),Nc(t.y,e.y,i.y)}function Fc(t,e,i){t.min=e.min-i.min,t.max=t.min+$e(e)}function ln(t,e,i){Fc(t.x,e.x,i.x),Fc(t.y,e.y,i.y)}const Vc=()=>({translate:0,scale:1,origin:0,originPoint:0}),yi=()=>({x:Vc(),y:Vc()}),Bc=()=>({min:0,max:0}),ke=()=>({x:Bc(),y:Bc()});function et(t){return[t("x"),t("y")]}function Jo(t){return t===void 0||t===1}function Zo({scale:t,scaleX:e,scaleY:i}){return!Jo(t)||!Jo(e)||!Jo(i)}function Zt(t){return Zo(t)||Uc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Uc(t){return $c(t.x)||$c(t.y)}function $c(t){return t&&t!=="0%"}function Xn(t,e,i){const n=t-i,s=e*n;return i+s}function jc(t,e,i,n,s){return s!==void 0&&(t=Xn(t,s,n)),Xn(t,i,n)+e}function Qo(t,e=0,i=1,n,s){t.min=jc(t.min,e,i,n,s),t.max=jc(t.max,e,i,n,s)}function Wc(t,{x:e,y:i}){Qo(t.x,e.translate,e.scale,e.originPoint),Qo(t.y,i.translate,i.scale,i.originPoint)}const Hc=.999999999999,Gc=1.0000000000001;function ev(t,e,i,n=!1){const s=i.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=i[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(n&&o.options.layoutScroll&&o.scroll&&o!==o.root&&wi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Wc(t,r)),n&&Zt(o.latestValues)&&wi(t,o.latestValues))}e.x<Gc&&e.x>Hc&&(e.x=1),e.y<Gc&&e.y>Hc&&(e.y=1)}function bi(t,e){t.min=t.min+e,t.max=t.max+e}function qc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);Qo(t,e,i,o,n)}function wi(t,e){qc(t.x,e.x,e.scaleX,e.scale,e.originX),qc(t.y,e.y,e.scaleY,e.scale,e.originY)}function zc(t,e){return Dc(zm(t.getBoundingClientRect(),e))}function tv(t,e,i){const n=zc(t,i),{scroll:s}=e;return s&&(bi(n.x,s.offset.x),bi(n.y,s.offset.y)),n}const Kc=({current:t})=>t?t.ownerDocument.defaultView:null,Yc=(t,e)=>Math.abs(t-e);function iv(t,e){const i=Yc(t.x,e.x),n=Yc(t.y,e.y);return Math.sqrt(i**2+n**2)}class Xc{constructor(e,i,{transformPagePoint:n,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=tr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,_=iv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!_)return;const{point:v}=h,{timestamp:b}=Pe;this.history.push({...v,timestamp:b});const{onStart:w,onMove:C}=this.handlers;p||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=er(p,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=tr(h.type==="pointercancel"?this.lastMoveEventInfo:er(p,this.transformPagePoint),this.history);this.startEvent&&_&&_(h,w),v&&v(h,w)},!Fo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=on(e),l=er(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,tr(l,this.history)),this.removeListeners=Hi(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function er(t,e){return e?{point:e(t.point)}:t}function Jc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function tr({point:t},e){return{point:t,delta:Jc(t,Zc(e)),offset:Jc(t,nv(e)),velocity:sv(e,.1)}}function nv(t){return t[0]}function Zc(t){return t[t.length-1]}function sv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Zc(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>ft(e)));)i--;if(!n)return{x:0,y:0};const o=pt(s.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-n.x)/o,y:(s.y-n.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function ov(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Ce(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Ce(i,t,n.max):Math.min(t,i)),t}function Qc(t,e,i){return{min:e!==void 0?t.min+e:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function rv(t,{top:e,left:i,bottom:n,right:s}){return{x:Qc(t.x,i,s),y:Qc(t.y,e,n)}}function ed(t,e){let i=e.min-t.min,n=e.max-t.max;return e.max-e.min<t.max-t.min&&([i,n]=[n,i]),{min:i,max:n}}function av(t,e){return{x:ed(t.x,e.x),y:ed(t.y,e.y)}}function lv(t,e){let i=.5;const n=$e(t),s=$e(e);return s>n?i=Gi(e.min,e.max-n,t.min):n>s&&(i=Gi(t.min,t.max-s,e.min)),It(0,1,i)}function cv(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const ir=.35;function dv(t=ir){return t===!1?t=0:t===!0&&(t=ir),{x:td(t,"left","right"),y:td(t,"top","bottom")}}function td(t,e,i){return{min:id(t,e),max:id(t,i)}}function id(t,e){return typeof t=="number"?t:t[e]||0}const uv=new WeakMap;class hv{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=ke(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:n}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),i&&this.snapToCursor(on(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:_,onDragStart:v}=this.getProps();if(p&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kg(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),et(w=>{let C=this.getAxisMotionValue(w).get()||0;if(gt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const L=k.layout.layoutBox[w];L&&(C=$e(L)*(parseFloat(C)/100))}}this.originPoint[w]=C}),v&&we.postRender(()=>v(d,h)),Ko(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:_,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=h;if(_&&this.currentDirection===null){this.currentDirection=fv(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),this.visualElement.render(),b&&b(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>et(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Xc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Kc(this.visualElement)})}stop(e,i){const n=e||this.latestPointerEvent,s=i||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!n)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&we.postRender(()=>a(n,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}updateAxis(e,i,n){const{drag:s}=this.getProps();if(!n||!Jn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=ov(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:i}=this.getProps(),n=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&&_i(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=rv(n.layoutBox,e):this.constraints=!1,this.elastic=dv(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&et(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=cv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!_i(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=tv(n,s.root,this.visualElement.getTransformPagePoint());let r=av(s.layout.layoutBox,o);if(i){const a=i(qm(r));this.hasMutatedConstraints=!!a,a&&(r=Dc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=et(u=>{if(!Jn(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,p=s?40:1e7,_={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return Ko(this.visualElement,e),n.start(Yo(e,n,0,i,this.visualElement,!1))}stopAnimation(){et(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){et(e=>{var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.pause()})}getAnimationState(e){var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.state}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),s=n[i];return s||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){et(i=>{const{drag:n}=this.getProps();if(!Jn(i,n,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(i);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[i];o.set(e[i]-Ce(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!_i(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};et(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=lv({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),et(r=>{if(!Jn(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Ce(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;uv.set(this.visualElement,this);const e=this.visualElement.current,i=rn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();_i(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",n);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),we.read(n);const r=sn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(et(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=ir,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Jn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function fv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class pv extends Vt{constructor(e){super(e),this.removeGroupControls=Qe,this.removeListeners=Qe,this.controls=new hv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Qe}unmount(){this.removeGroupControls(),this.removeListeners()}}const nd=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class gv extends Vt{constructor(){super(...arguments),this.removePointerDownListener=Qe}onPointerDown(e){this.session=new Xc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Kc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:nd(e),onStart:nd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=rn(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 Zn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function sd(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const cn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=sd(t,e.target.x),n=sd(t,e.target.y);return`${i}% ${n}%`}},mv={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Ft.parse(t);if(s.length>5)return n;const o=Ft.createTransformer(t),r=typeof s[0]!="number"?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=Ce(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 od=!1;class vv extends rt{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;tm(_v),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),od&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Zn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,od=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||we.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),No.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(s),n&&n.deregister&&n.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function rd(t){const[e,i]=lc(),n=De(Xs);return D(vv,{...t,layoutGroup:n,switchLayoutGroup:De(vc),isPresent:e,safeToRemove:i})}const _v={borderRadius:{...cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:cn,borderTopRightRadius:cn,borderBottomLeftRadius:cn,borderBottomRightRadius:cn,boxShadow:mv};function yv(t,e,i){const n=Be(t)?t:mi(t);return n.start(Yo("",n,e,i)),n.animation}const bv=(t,e)=>t.depth-e.depth;class wv{constructor(){this.children=[],this.isDirty=!1}add(e){Zs(this.children,e),this.isDirty=!0}remove(e){Qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(bv),this.isDirty=!1,this.children.forEach(e)}}function Sv(t,e){const i=Ge.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const ad=["TopLeft","TopRight","BottomLeft","BottomRight"],Cv=ad.length,ld=t=>typeof t=="string"?parseFloat(t):t,cd=t=>typeof t=="number"||K.test(t);function Tv(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,Ev(n)),t.opacityExit=Ce(e.opacity??1,0,kv(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<Cv;r++){const a=`border${ad[r]}Radius`;let l=dd(e,a),c=dd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||cd(l)===cd(c)?(t[a]=Math.max(Ce(ld(l),ld(c),n),0),(gt.test(c)||gt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Ce(e.rotate||0,i.rotate||0,n))}function dd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Ev=ud(0,.5,cl),kv=ud(.5,.95,Qe);function ud(t,e,i){return n=>n<t?0:n>e?1:i(Gi(t,e,n))}function hd(t,e){t.min=e.min,t.max=e.max}function tt(t,e){hd(t.x,e.x),hd(t.y,e.y)}function fd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function pd(t,e,i,n,s){return t-=e,t=Xn(t,1/i,n),s!==void 0&&(t=Xn(t,1/s,n)),t}function Iv(t,e=0,i=1,n=.5,s,o=t,r=t){if(gt.test(e)&&(e=parseFloat(e),e=Ce(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Ce(o.min,o.max,n);t===o&&(a-=e),t.min=pd(t.min,e,i,a,s),t.max=pd(t.max,e,i,a,s)}function gd(t,e,[i,n,s],o,r){Iv(t,e[i],e[n],e[s],e.scale,o,r)}const Rv=["x","scaleX","originX"],Av=["y","scaleY","originY"];function md(t,e,i,n){gd(t.x,e,Rv,i?i.x:void 0,n?n.x:void 0),gd(t.y,e,Av,i?i.y:void 0,n?n.y:void 0)}function vd(t){return t.translate===0&&t.scale===1}function _d(t){return vd(t.x)&&vd(t.y)}function yd(t,e){return t.min===e.min&&t.max===e.max}function xv(t,e){return yd(t.x,e.x)&&yd(t.y,e.y)}function bd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function wd(t,e){return bd(t.x,e.x)&&bd(t.y,e.y)}function Sd(t){return $e(t.x)/$e(t.y)}function Cd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Lv{constructor(){this.members=[]}add(e){Zs(this.members,e),e.scheduleRender()}remove(e){if(Qs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){const i=this.members.findIndex(s=>e===s);if(i===0)return!1;let n;for(let s=i;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){n=o;break}}return n?(this.promote(n),!0):!1}promote(e,i){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,i&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:i,resumingFrom:n}=e;i.onExitComplete&&i.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Dv(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:p,skewY:_}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),p&&(n+=`skewX(${p}deg) `),_&&(n+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(n+=`scale(${a}, ${l})`),n||"none"}const nr=["","X","Y","Z"],Ov=1e3;let Mv=0;function sr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Td(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=Ic(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",we,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&Td(n)}function Ed({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Mv++,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(Fv),this.nodes.forEach($v),this.nodes.forEach(jv),this.nodes.forEach(Vv)},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 wv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new io),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=ac(r)&&!Dg(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 u,d=0;const h=()=>this.root.updateBlockedByResize=!1;we.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=Sv(h,250),Zn.hasAnimatedSinceResize&&(Zn.hasAnimatedSinceResize=!1,this.nodes.forEach(Rd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||zv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),w=!this.targetLayout||!wd(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Oo(_,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,C)}else d||Rd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),Pt(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(Wv),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&&Td(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(kd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Id);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Uv),this.nodes.forEach(Pv),this.nodes.forEach(Nv)):this.nodes.forEach(Id),this.clearAllSnapshots();const a=Ge.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,oo.update.process(Pe),oo.preRender.process(Pe),oo.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,No.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Bv),this.sharedNodes.forEach(Hv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,we.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){we.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!$e(this.snapshot.measuredBox.x)&&!$e(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=ke(),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=n(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:i(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&&!_d(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Zt(this.latestValues)||u)&&(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)),Kv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Yv))){const{scroll:u}=this.root;u&&(bi(a.x,u.offset.x),bi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(tt(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&tt(a,r),bi(a.x,d.offset.x),bi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();tt(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&wi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&wi(l,u.latestValues)}return Zt(this.latestValues)&&wi(l,this.latestValues),l}removeTransform(r){const a=ke();tt(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;Zo(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();tt(u,d),md(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&md(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!==Pe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Pe.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),tt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Qm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):tt(this.target,this.layout.layoutBox),Wc(this.target,this.targetDelta)):tt(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.target,p.target),tt(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Zo(this.parent.latestValues)||Uc(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===Pe.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;tt(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;ev(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=ke());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(fd(this.prevProjectionDelta.x,this.projectionDelta.x),fd(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Cd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Cd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}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=yi(),this.projectionDelta=yi(),this.projectionDeltaWithTransform=yi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),p=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=p!==_,b=this.getStack(),w=!b||b.members.length<=1,C=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(qv));this.animationProgress=0;let k;this.mixTargetDelta=L=>{const R=L/1e3;Ad(d.x,r.x,R),Ad(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ln(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Gv(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&xv(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),tt(k,this.relativeTarget)),v&&(this.animationValues=u,Tv(u,c,this.latestValues,R,C,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},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&&(Pt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=we.update(()=>{Zn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=mi(0)),this.currentAnimation=yv(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},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(Ov),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&Md(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=$e(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=$e(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}tt(a,l),wi(a,u),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Lv),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&sr("z",r,c,this.animationValues);for(let u=0;u<nr.length;u++)sr(`rotate${nr[u]}`,r,c,this.animationValues),sr(`skew${nr[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);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=Yn(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=Yn(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Dv(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:p}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const _ in tn){if(u[_]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:w}=tn[_],C=d==="none"?u[_]:v(u[_],c);if(b){const k=b.length;for(let L=0;L<k;L++)r[b[L]]=C}else w?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Yn(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(kd),this.root.sharedNodes.clear()}}}function Pv(t){t.updateLayout()}function Nv(t){var i;const e=((i=t.resumeFrom)==null?void 0:i.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?et(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=$e(h);h.min=n[d].min,h.max=h.min+p}):Md(o,e.layoutBox,n)&&et(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=$e(n[d]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+p)});const a=yi();an(a,n,e.layoutBox);const l=yi();r?an(l,t.applyTransform(s,!0),e.measuredBox):an(l,n,e.layoutBox);const c=!_d(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:p}=d;if(h&&p){const _=ke();ln(_,e.layoutBox,h.layoutBox);const v=ke();ln(v,n,p.layoutBox),wd(_,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Fv(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 Vv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Bv(t){t.clearSnapshot()}function kd(t){t.clearMeasurements()}function Id(t){t.isLayoutDirty=!1}function Uv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Rd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function $v(t){t.resolveTargetDelta()}function jv(t){t.calcProjection()}function Wv(t){t.resetSkewAndRotation()}function Hv(t){t.removeLeadSnapshot()}function Ad(t,e,i){t.translate=Ce(e.translate,0,i),t.scale=Ce(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function xd(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function Gv(t,e,i,n){xd(t.x,e.x,i.x,n),xd(t.y,e.y,i.y,n)}function qv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const zv={duration:.45,ease:[.4,0,.1,1]},Ld=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Dd=Ld("applewebkit/")&&!Ld("chrome/")?Math.round:Qe;function Od(t){t.min=Dd(t.min),t.max=Dd(t.max)}function Kv(t){Od(t.x),Od(t.y)}function Md(t,e,i){return t==="position"||t==="preserve-aspect"&&!Zm(Sd(e),Sd(i),.2)}function Yv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Xv=Ed({attachResizeListener:(t,e)=>sn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),or={current:void 0},Pd=Ed({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!or.current){const t=new Xv({});t.mount(window),t.setOptions({layoutScroll:!0}),or.current=t}return or.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Jv={pan:{Feature:gv},drag:{Feature:pv,ProjectionNode:Pd,MeasureLayout:rd}};function Nd(t,e,i){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",i==="Start");const s="onHover"+i,o=n[s];o&&we.postRender(()=>o(e,on(e)))}class Zv extends Vt{mount(){const{current:e}=this.node;e&&(this.unmount=Ig(e,(i,n)=>(Nd(this.node,n,"Start"),s=>Nd(this.node,s,"End"))))}unmount(){}}class Qv extends Vt{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=Hi(sn(this.node.current,"focus",()=>this.onFocus()),sn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Fd(t,e,i){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",i==="Start");const s="onTap"+(i==="End"?"":i),o=n[s];o&&we.postRender(()=>o(e,on(e)))}class e_ extends Vt{mount(){const{current:e}=this.node;e&&(this.unmount=Lg(e,(i,n)=>(Fd(this.node,n,"Start"),(s,{success:o})=>Fd(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const rr=new WeakMap,ar=new WeakMap,t_=t=>{const e=rr.get(t.target);e&&e(t)},i_=t=>{t.forEach(t_)};function n_({root:t,...e}){const i=t||document;ar.has(i)||ar.set(i,{});const n=ar.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(i_,{root:t,...e})),n[s]}function s_(t,e,i){const n=n_(e);return rr.set(t,i),n.observe(t),()=>{rr.delete(t),n.unobserve(t)}}const o_={some:0,all:1};class r_ extends Vt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:i,margin:n,amount:s="some",once:o}=e,r={root:i?i.current:void 0,rootMargin:n,threshold:typeof s=="number"?s:o_[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:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return s_(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(a_(e,i))&&this.startObserver()}unmount(){}}function a_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const l_={inView:{Feature:r_},tap:{Feature:e_},focus:{Feature:Qv},hover:{Feature:Zv}},c_={layout:{ProjectionNode:Pd,MeasureLayout:rd}},lr={current:null},Vd={current:!1};function d_(){if(Vd.current=!0,!!Js)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>lr.current=t.matches;t.addEventListener("change",e),e()}else lr.current=!1}const u_=new WeakMap;function h_(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Be(s))t.addValue(n,s);else if(Be(o))t.addValue(n,mi(s,{owner:t}));else if(o!==s)if(t.hasValue(n)){const r=t.getValue(n);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(n);t.addValue(n,mi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const Bd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class f_{scrapeMotionValuesFromProps(e,i,n){return{}}constructor({parent:e,props:i,presenceContext:n,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=Lo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=Ge.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,we.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=i.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=i,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Kn(i),this.isVariantNode=pc(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const p=d[h];l[h]!==void 0&&Be(p)&&p.set(l[h],!1)}}mount(e){this.current=e,u_.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((i,n)=>this.bindToMotionValue(n,i)),Vd.current||d_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Pt(this.notifyUpdate),Pt(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 i=this.features[e];i&&(i.unmount(),i.isMounted=!1)}this.current=null}bindToMotionValue(e,i){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=gi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&we.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),o=i.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),i.owner&&i.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 vi){const i=vi[e];if(!i)continue;const{isEnabled:n,Feature:s}=i;if(!this.features[e]&&s&&n(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):ke()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let n=0;n<Bd.length;n++){const s=Bd[n];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=h_(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 i=this.getClosestVariantNode();if(i)return i.variantChildren&&i.variantChildren.add(e),()=>i.variantChildren.delete(e)}addValue(e,i){const n=this.values.get(e);i!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&i!==void 0&&(n=mi(i===null?void 0:i,{owner:this}),this.addValue(e,n)),n}readValue(e,i){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(Qa(n)||tl(n))?n=parseFloat(n):!Mg(n)&&Ft.test(i)&&(n=Zl(e,i)),this.setBaseTarget(e,Be(n)?n.get():n)),Be(n)?n.get():n}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var o;const{initial:i}=this.props;let n;if(typeof i=="string"||typeof i=="object"){const r=Go(this.props,i,(o=this.presenceContext)==null?void 0:o.custom);r&&(n=r[e])}if(i&&n!==void 0)return n;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Be(s)?s:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new io),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Ud extends f_{constructor(){super(...arguments),this.KeyframeResolver=Sg}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){return e.style?e.style[i]:void 0}removeValueFromRenderState(e,{vars:i,style:n}){delete i[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Be(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function $d(t,{style:e,vars:i},n,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,n);for(r in i)o.setProperty(r,i[r])}function p_(t){return window.getComputedStyle(t)}class g_ extends Ud{constructor(){super(...arguments),this.type="html",this.renderInstance=$d}readValueFromInstance(e,i){var n;if(gi.has(i))return(n=this.projection)!=null&&n.isProjecting?ko(i):jp(e,i);{const s=p_(e),o=(ro(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return zc(e,i)}build(e,i,n){jo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return qo(e,i,n)}}const jd=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 m_(t,e,i,n){$d(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(jd.has(s)?s:$o(s),e.attrs[s])}class v_ extends Ud{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(gi.has(i)){const n=Jl(i);return n&&n.default||0}return i=jd.has(i)?i:$o(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return kc(e,i,n)}build(e,i,n){wc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){m_(e,i,n,s)}mount(e){this.isSVGTag=Cc(e.tagName),super.mount(e)}}const __=(t,e)=>Ho(t)?new v_(e):new g_(e,{allowProjection:t!==ut}),y_=_m({...Hm,...l_,...Jv,...c_},__),Si=Hg(y_),b_=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region","skip-last-voice-sdk-id"],dn="widget-layout-id";function Wd(t){var e,i,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=Wd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function At(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=Wd(t))&&(n&&(n+=" "),n+=e);return n}const w_=Dn("listening"),cr=()=>Ja(w_);function S_(t){var i;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((i=e.params)==null?void 0:i.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Qn={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},Hd=Dn(Qn),C_=()=>{const t=Mn(Hd);return He(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Qn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Qn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Qn.speak_to_interrupt_text),i}),[t])},Qt=()=>Ys(Hd),Gd=({size:t="large",className:e})=>{const i=Qt(),[n]=cr();return D("h1",{className:At({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},qd=({stream:t,chatMode:e})=>{const i=ue(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),D(Mg,{isPresent:e,childRef:o,sizeRef:r,children:Pf(t,{ref:o})})}const Ng=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Pn(Fg),u=Bs();let d=!0,h=Qe(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:p=>{c.set(p,!0);for(const _ of c.values())if(!_)return;n&&n()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[i,c,n]);return o&&d&&(h={...h}),Qe(()=>{c.forEach((p,_)=>c.set(_,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Pg,{isPresent:i,anchorX:a,root:l,children:t})),D(Nn.Provider,{value:h,children:t})};function Fg(){return new Map}function uc(t=!0){const e=De(Nn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Bs();xe(()=>{if(t)return s(o)},[t]);const r=Ge(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Wn=t=>t.key||"";function hc(t){const e=[];return Tf.forEach(t,i=>{Xa(i)&&e.push(i)}),e}const Bg=({children:t,custom:e,initial:i=!0,onExitComplete:n,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=uc(r),d=Qe(()=>hc(t),[t]),h=r&&!c?[]:d.map(Wn),p=ue(!0),_=ue(d),v=Pn(()=>new Map),[b,w]=Ae(d),[C,k]=Ae(d);tl(()=>{p.current=!1,_.current=d;for(let O=0;O<C.length;O++){const T=Wn(C[O]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const L=[];if(d!==b){let O=[...d];for(let T=0;T<C.length;T++){const E=C[T],g=Wn(E);h.includes(g)||(O.splice(T,0,E),L.push(E))}return o==="wait"&&L.length&&(O=L),k(hc(O)),w(d),null}const{forceRender:R}=De(Xs);return D(ht,{children:C.map(O=>{const T=Wn(O),E=r&&!c?!1:d===C||h.includes(T),g=()=>{if(v.has(T))v.set(T,!0);else return;let m=!0;v.forEach(f=>{f||(m=!1)}),m&&(R==null||R(),k(_.current),r&&(u==null||u()),n&&n())};return D(Ng,{isPresent:E,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:g,anchorX:a,children:O},T)})})},fc=kt({strict:!1}),pc={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"]},vi={};for(const t in pc)vi[t]={isEnabled:e=>pc[t].some(i=>!!e[i])};function Vg(t){for(const e in t)vi[e]={...vi[e],...t[e]}}const Ug=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 Gn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Ug.has(t)}let gc=t=>!Gn(t);function mc(t){typeof t=="function"&&(gc=e=>e.startsWith("on")?!Gn(e):t(e))}try{mc(require("@emotion/is-prop-valid").default)}catch{}function $g(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(gc(s)||i===!0&&Gn(s)||!e&&!Gn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function jg({children:t,isValidProp:e,...i}){e&&mc(e),i={...De(Qi),...i},i.isStatic=Pn(()=>i.isStatic);const n=Qe(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Qi.Provider,{value:n,children:t})}function Hg(t){if(typeof Proxy>"u")return t;const e=new Map,i=(...n)=>t(...n);return new Proxy(i,{get:(n,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const qn=kt({});function zn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function en(t){return typeof t=="string"||Array.isArray(t)}const Vo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Uo=["initial",...Vo];function Kn(t){return zn(t.animate)||Uo.some(e=>en(t[e]))}function vc(t){return!!(Kn(t)||t.variants)}function Wg(t,e){if(Kn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||en(i)?i:void 0,animate:en(n)?n:void 0}}return t.inherit!==!1?e:{}}function Gg(t){const{initial:e,animate:i}=Wg(t,De(qn));return Qe(()=>({initial:e,animate:i}),[_c(e),_c(i)])}function _c(t){return Array.isArray(t)?t.join(" "):t}const qg=Symbol.for("motionComponentSymbol");function _i(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function zg(t,e,i){return Ge(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):_i(i)&&(i.current=n))},[e])}const $o=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),yc="data-"+$o("framerAppearId"),bc=kt({});function Kg(t,e,i,n,s){var v,b;const{visualElement:o}=De(qn),r=De(fc),a=De(Nn),l=De(Qi).reducedMotion,c=ue(null);n=n||r.renderer,!c.current&&n&&(c.current=n(t,{visualState:e,parent:o,props:i,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=De(bc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Yg(c.current,i,s,d);const h=ue(!1);Na(()=>{u&&h.current&&u.update(i,a)});const p=i[yc],_=ue(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return tl(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),No.render(u.render),_.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!_.current&&u.animationState&&u.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),_.current=!1))}),u}function Yg(t,e,i,n){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new i(t.latestValues,e["data-framer-portal-id"]?void 0:wc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&_i(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function wc(t){if(t)return t.options.allowProjection!==!1?t.projection:wc(t.parent)}function Xg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Vg(t);function o(a,l){let c;const u={...De(Qi),...a,layoutId:Jg(a)},{isStatic:d}=u,h=Gg(a),p=n(a,d);if(!d&&Js){Zg();const _=Qg(u);c=_.MeasureLayout,h.visualElement=Kg(s,p,u,e,_.ProjectionNode)}return D(qn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,zg(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Cf(o);return r[qg]=s,r}function Jg({layoutId:t}){const e=De(Xs).id;return e&&t!==void 0?e+"-"+t:t}function Zg(t,e){De(fc).strict}function Qg(t){const{drag:e,layout:i}=vi;if(!e&&!i)return{};const n={...e,...i};return{MeasureLayout:e!=null&&e.isEnabled(t)||i!=null&&i.isEnabled(t)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}const tn={};function em(t){for(const e in t)tn[e]=t[e],ro(e)&&(tn[e].isCSSVariable=!0)}function Sc(t,{layout:e,layoutId:i}){return gi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!tn[t]||t==="opacity")}const tm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},im=pi.length;function nm(t,e,i){let n="",s=!0;for(let o=0;o<im;o++){const r=pi[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||i){const c=ic(a,Po[r]);if(!l){s=!1;const u=tm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function jo(t,e,i){const{style:n,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(gi.has(l)){r=!0;continue}else if(ro(l)){s[l]=c;continue}else{const u=ic(c,Po[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=nm(e,t.transform,i):n.transform&&(n.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;n.transformOrigin=`${l} ${c} ${u}`}}const Ho=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Cc(t,e,i){for(const n in e)!Ve(e[n])&&!Sc(n,i)&&(t[n]=e[n])}function sm({transformTemplate:t},e){return Qe(()=>{const i=Ho();return jo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function om(t,e){const i=t.style||{},n={};return Cc(n,i,t),Object.assign(n,sm(t,e)),n}function rm(t,e){const i={},n=om(t,e);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=n,i}const am={offset:"stroke-dashoffset",array:"stroke-dasharray"},lm={offset:"strokeDashoffset",array:"strokeDasharray"};function cm(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?am:lm;t[o.offset]=Y.transform(-n);const r=Y.transform(e),a=Y.transform(i);t[o.array]=`${r} ${a}`}function Tc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(jo(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),i!==void 0&&(d.y=i),n!==void 0&&(d.scale=n),s!==void 0&&cm(d,s,o,r,!1)}const Ec=()=>({...Ho(),attrs:{}}),kc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function dm(t,e,i,n){const s=Qe(()=>{const o=Ec();return Tc(o,e,kc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Cc(o,t.style,t),s.style={...o,...s.style}}return s}const um=["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 Wo(t){return typeof t!="string"||t.includes("-")?!1:!!(um.indexOf(t)>-1||/[A-Z]/u.test(t))}function hm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(Wo(i)?dm:rm)(n,o,r,i),c=$g(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Qe(()=>Ve(d)?d.get():d,[d]);return Ze(i,{...u,children:h})}}function Ic(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function Go(t,e,i,n){if(typeof e=="function"){const[s,o]=Ic(n);e=e(i!==void 0?i:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=Ic(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Yn(t){return Ve(t)?t.get():t}function fm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:pm(i,n,s,t),renderState:e()}}const Rc=t=>(e,i)=>{const n=De(qn),s=De(Nn),o=()=>fm(t,e,n,s);return i?o():Pn(o)};function pm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Yn(o[h]);let{initial:r,animate:a}=t;const l=Kn(t),c=vc(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=i?i.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!zn(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const _=Go(t,h[p]);if(_){const{transitionEnd:v,transition:b,...w}=_;for(const C in w){let k=w[C];if(Array.isArray(k)){const L=u?k.length-1:0;k=k[L]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function qo(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||Sc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const gm={useVisualState:Rc({scrapeMotionValuesFromProps:qo,createRenderState:Ho})};function Ac(t,e,i){const n=qo(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=pi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const mm={useVisualState:Rc({scrapeMotionValuesFromProps:Ac,createRenderState:Ec})};function vm(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Wo(n)?mm:gm,preloadedFeatures:t,useRender:hm(s),createVisualElement:e,Component:n};return Xg(r)}}function nn(t,e,i){const n=t.getProps();return Go(n,e,i!==void 0?i:n.custom,t)}const zo=t=>Array.isArray(t);function _m(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,mi(i))}function ym(t){return zo(t)?t[t.length-1]||0:t}function bm(t,e){const i=nn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=ym(o[r]);_m(t,r,a)}}function wm(t){return!!(Ve(t)&&t.add)}function Ko(t,e){const i=t.getValue("willChange");if(wm(i))return i.add(e);if(!i&&Rt.WillChange){const n=new Rt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function xc(t){return t.props[yc]}const Sm=t=>t!==null;function Cm(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Sm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Tm={type:"spring",stiffness:500,damping:25,restSpeed:10},Em=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),km={type:"keyframes",duration:.8},Im={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Rm=(t,{keyframes:e})=>e.length>2?km:gi.has(t)?t.startsWith("scale")?Em(e[1]):Tm:Im;function Am({when:t,delay:e,delayChildren:i,staggerChildren:n,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Yo=(t,e,i,n={},s,o)=>r=>{const a=Oo(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-pt(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Am(a)||Object.assign(u,Rm(t,u)),u.duration&&(u.duration=pt(u.duration)),u.repeatDelay&&(u.repeatDelay=pt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(Rt.instantAnimations||Rt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=Cm(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Co(u):new dg(u)};function xm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Lc(t,e,{delay:i=0,transitionOverride:n,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;n&&(o=n);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&xm(c,u))continue;const p={delay:i,...Oo(o||{},u)},_=d.get();if(_!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===_&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=xc(t);if(w){const C=window.MotionHandoffAnimation(w,u,we);C!==null&&(p.startTime=C,v=!0)}}Ko(t,u),d.start(Yo(u,d,h,t.shouldReduceMotion&&Yl.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&bm(t,r)})}),l}function Xo(t,e,i={}){var l;const n=nn(t,e,i.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=n||{};i.transitionOverride&&(s=i.transitionOverride);const o=n?()=>Promise.all(Lc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Lm(t,e,c,u,d,h,i)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(i.delay)])}function Lm(t,e,i=0,n=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof n=="function",d=u?h=>n(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(Dm).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(Xo(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Dm(t,e){return t.sortNodePosition(e)}function Om(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>Xo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=Xo(t,e,i);else{const s=typeof e=="function"?nn(t,e,i.custom):e;n=Promise.all(Lc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Dc(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(e[n]!==t[n])return!1;return!0}const Mm=Uo.length;function Oc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?Oc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Mm;i++){const n=Uo[i],s=t.props[n];(en(s)||s===!1)&&(e[n]=s)}return e}const Pm=[...Vo].reverse(),Nm=Vo.length;function Fm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Om(t,i,n)))}function Bm(t){let e=Fm(t),i=Mc(),n=!0;const s=l=>(c,u)=>{var h;const d=nn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:_,...v}=d;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=Oc(t.parent)||{},d=[],h=new Set;let p={},_=1/0;for(let b=0;b<Nm;b++){const w=Pm[b],C=i[w],k=c[w]!==void 0?c[w]:u[w],L=en(k),R=w===l?C.isActive:null;R===!1&&(_=b);let O=k===u[w]&&k!==c[w]&&L;if(O&&n&&t.manuallyAnimateOnMount&&(O=!1),C.protectedKeys={...p},!C.isActive&&R===null||!k&&!C.prevProp||zn(k)||typeof k=="boolean")continue;const T=Vm(C.prevProp,k);let E=T||w===l&&C.isActive&&!O&&L||b>_&&L,g=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(w),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},A=M=>{E=!0,h.has(M)&&(g=!0,h.delete(M)),C.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in I){const F=f[M],G=S[M];if(p.hasOwnProperty(M))continue;let U=!1;zo(F)&&zo(G)?U=!Dc(F,G):U=F!==G,U?F!=null?A(M):h.add(M):F!==void 0&&h.has(M)?A(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(p={...p,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(O&&T)||g)&&d.push(...m.map(M=>({animation:M,options:{type:w}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const w=nn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(b.transition=w.transition)}h.forEach(w=>{const C=t.getBaseTarget(w),k=t.getValue(w);k&&(k.liveStyle=!0),b[w]=C??null}),d.push({animation:b})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var p;return(p=h.animationState)==null?void 0:p.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=Mc(),n=!0}}}function Vm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Dc(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Mc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Bt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Um extends Bt{constructor(e){super(e),e.animationState||(e.animationState=Bm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();zn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let $m=0;class jm extends Bt{constructor(){super(...arguments),this.id=$m++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const s=this.node.animationState.setActive("exit",!e);i&&!e&&s.then(()=>{i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Hm={animation:{Feature:Um},exit:{Feature:jm}};function sn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function on(t){return{point:{x:t.pageX,y:t.pageY}}}const Wm=t=>e=>Fo(e)&&t(e,on(e));function rn(t,e,i,n){return sn(t,e,Wm(i),n)}function Pc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Gm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function qm(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}const Nc=1e-4,zm=1-Nc,Km=1+Nc,Fc=.01,Ym=0-Fc,Xm=0+Fc;function je(t){return t.max-t.min}function Jm(t,e,i){return Math.abs(t-e)<=i}function Bc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=je(i)/je(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=zm&&t.scale<=Km||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ym&&t.translate<=Xm||isNaN(t.translate))&&(t.translate=0)}function an(t,e,i,n){Bc(t.x,e.x,i.x,n?n.originX:void 0),Bc(t.y,e.y,i.y,n?n.originY:void 0)}function Vc(t,e,i){t.min=i.min+e.min,t.max=t.min+je(e)}function Zm(t,e,i){Vc(t.x,e.x,i.x),Vc(t.y,e.y,i.y)}function Uc(t,e,i){t.min=e.min-i.min,t.max=t.min+je(e)}function ln(t,e,i){Uc(t.x,e.x,i.x),Uc(t.y,e.y,i.y)}const $c=()=>({translate:0,scale:1,origin:0,originPoint:0}),yi=()=>({x:$c(),y:$c()}),jc=()=>({min:0,max:0}),ke=()=>({x:jc(),y:jc()});function tt(t){return[t("x"),t("y")]}function Jo(t){return t===void 0||t===1}function Zo({scale:t,scaleX:e,scaleY:i}){return!Jo(t)||!Jo(e)||!Jo(i)}function Zt(t){return Zo(t)||Hc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Hc(t){return Wc(t.x)||Wc(t.y)}function Wc(t){return t&&t!=="0%"}function Xn(t,e,i){const n=t-i,s=e*n;return i+s}function Gc(t,e,i,n,s){return s!==void 0&&(t=Xn(t,s,n)),Xn(t,i,n)+e}function Qo(t,e=0,i=1,n,s){t.min=Gc(t.min,e,i,n,s),t.max=Gc(t.max,e,i,n,s)}function qc(t,{x:e,y:i}){Qo(t.x,e.translate,e.scale,e.originPoint),Qo(t.y,i.translate,i.scale,i.originPoint)}const zc=.999999999999,Kc=1.0000000000001;function Qm(t,e,i,n=!1){const s=i.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=i[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(n&&o.options.layoutScroll&&o.scroll&&o!==o.root&&wi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,qc(t,r)),n&&Zt(o.latestValues)&&wi(t,o.latestValues))}e.x<Kc&&e.x>zc&&(e.x=1),e.y<Kc&&e.y>zc&&(e.y=1)}function bi(t,e){t.min=t.min+e,t.max=t.max+e}function Yc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);Qo(t,e,i,o,n)}function wi(t,e){Yc(t.x,e.x,e.scaleX,e.scale,e.originX),Yc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Xc(t,e){return Pc(qm(t.getBoundingClientRect(),e))}function ev(t,e,i){const n=Xc(t,i),{scroll:s}=e;return s&&(bi(n.x,s.offset.x),bi(n.y,s.offset.y)),n}const Jc=({current:t})=>t?t.ownerDocument.defaultView:null,Zc=(t,e)=>Math.abs(t-e);function tv(t,e){const i=Zc(t.x,e.x),n=Zc(t.y,e.y);return Math.sqrt(i**2+n**2)}class Qc{constructor(e,i,{transformPagePoint:n,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=tr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,_=tv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!_)return;const{point:v}=h,{timestamp:b}=Pe;this.history.push({...v,timestamp:b});const{onStart:w,onMove:C}=this.handlers;p||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=er(p,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=tr(h.type==="pointercancel"?this.lastMoveEventInfo:er(p,this.transformPagePoint),this.history);this.startEvent&&_&&_(h,w),v&&v(h,w)},!Fo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=on(e),l=er(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,tr(l,this.history)),this.removeListeners=Wi(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function er(t,e){return e?{point:e(t.point)}:t}function ed(t,e){return{x:t.x-e.x,y:t.y-e.y}}function tr({point:t},e){return{point:t,delta:ed(t,td(e)),offset:ed(t,iv(e)),velocity:nv(e,.1)}}function iv(t){return t[0]}function td(t){return t[t.length-1]}function nv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=td(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>pt(e)));)i--;if(!n)return{x:0,y:0};const o=gt(s.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-n.x)/o,y:(s.y-n.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function sv(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Ce(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Ce(i,t,n.max):Math.min(t,i)),t}function id(t,e,i){return{min:e!==void 0?t.min+e:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function ov(t,{top:e,left:i,bottom:n,right:s}){return{x:id(t.x,i,s),y:id(t.y,e,n)}}function nd(t,e){let i=e.min-t.min,n=e.max-t.max;return e.max-e.min<t.max-t.min&&([i,n]=[n,i]),{min:i,max:n}}function rv(t,e){return{x:nd(t.x,e.x),y:nd(t.y,e.y)}}function av(t,e){let i=.5;const n=je(t),s=je(e);return s>n?i=Gi(e.min,e.max-n,t.min):n>s&&(i=Gi(t.min,t.max-s,e.min)),It(0,1,i)}function lv(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const ir=.35;function cv(t=ir){return t===!1?t=0:t===!0&&(t=ir),{x:sd(t,"left","right"),y:sd(t,"top","bottom")}}function sd(t,e,i){return{min:od(t,e),max:od(t,i)}}function od(t,e){return typeof t=="number"?t:t[e]||0}const dv=new WeakMap;class uv{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=ke(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:n}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),i&&this.snapToCursor(on(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:_,onDragStart:v}=this.getProps();if(p&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Eg(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),tt(w=>{let C=this.getAxisMotionValue(w).get()||0;if(mt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const L=k.layout.layoutBox[w];L&&(C=je(L)*(parseFloat(C)/100))}}this.originPoint[w]=C}),v&&we.postRender(()=>v(d,h)),Ko(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:_,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=h;if(_&&this.currentDirection===null){this.currentDirection=hv(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),this.visualElement.render(),b&&b(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>tt(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Qc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Jc(this.visualElement)})}stop(e,i){const n=e||this.latestPointerEvent,s=i||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!n)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&we.postRender(()=>a(n,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}updateAxis(e,i,n){const{drag:s}=this.getProps();if(!n||!Jn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=sv(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:i}=this.getProps(),n=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&&_i(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=ov(n.layoutBox,e):this.constraints=!1,this.elastic=cv(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&tt(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=lv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!_i(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=ev(n,s.root,this.visualElement.getTransformPagePoint());let r=rv(s.layout.layoutBox,o);if(i){const a=i(Gm(r));this.hasMutatedConstraints=!!a,a&&(r=Pc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=tt(u=>{if(!Jn(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,p=s?40:1e7,_={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return Ko(this.visualElement,e),n.start(Yo(e,n,0,i,this.visualElement,!1))}stopAnimation(){tt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){tt(e=>{var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.pause()})}getAnimationState(e){var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.state}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),s=n[i];return s||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){tt(i=>{const{drag:n}=this.getProps();if(!Jn(i,n,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(i);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[i];o.set(e[i]-Ce(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!_i(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};tt(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=av({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),tt(r=>{if(!Jn(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Ce(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;dv.set(this.visualElement,this);const e=this.visualElement.current,i=rn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();_i(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",n);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),we.read(n);const r=sn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(tt(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=ir,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Jn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function hv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class fv extends Bt{constructor(e){super(e),this.removeGroupControls=et,this.removeListeners=et,this.controls=new uv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||et}unmount(){this.removeGroupControls(),this.removeListeners()}}const rd=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class pv extends Bt{constructor(){super(...arguments),this.removePointerDownListener=et}onPointerDown(e){this.session=new Qc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Jc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:rd(e),onStart:rd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=rn(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 Zn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ad(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const cn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(Y.test(t))t=parseFloat(t);else return t;const i=ad(t,e.target.x),n=ad(t,e.target.y);return`${i}% ${n}%`}},gv={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Ft.parse(t);if(s.length>5)return n;const o=Ft.createTransformer(t),r=typeof s[0]!="number"?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=Ce(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 ld=!1;class mv extends at{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;em(vv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),ld&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Zn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,ld=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||we.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),No.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(s),n&&n.deregister&&n.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function cd(t){const[e,i]=uc(),n=De(Xs);return D(mv,{...t,layoutGroup:n,switchLayoutGroup:De(bc),isPresent:e,safeToRemove:i})}const vv={borderRadius:{...cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:cn,borderTopRightRadius:cn,borderBottomLeftRadius:cn,borderBottomRightRadius:cn,boxShadow:gv};function _v(t,e,i){const n=Ve(t)?t:mi(t);return n.start(Yo("",n,e,i)),n.animation}const yv=(t,e)=>t.depth-e.depth;class bv{constructor(){this.children=[],this.isDirty=!1}add(e){Zs(this.children,e),this.isDirty=!0}remove(e){Qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(yv),this.isDirty=!1,this.children.forEach(e)}}function wv(t,e){const i=qe.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const dd=["TopLeft","TopRight","BottomLeft","BottomRight"],Sv=dd.length,ud=t=>typeof t=="string"?parseFloat(t):t,hd=t=>typeof t=="number"||Y.test(t);function Cv(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,Tv(n)),t.opacityExit=Ce(e.opacity??1,0,Ev(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<Sv;r++){const a=`border${dd[r]}Radius`;let l=fd(e,a),c=fd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||hd(l)===hd(c)?(t[a]=Math.max(Ce(ud(l),ud(c),n),0),(mt.test(c)||mt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Ce(e.rotate||0,i.rotate||0,n))}function fd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Tv=pd(0,.5,hl),Ev=pd(.5,.95,et);function pd(t,e,i){return n=>n<t?0:n>e?1:i(Gi(t,e,n))}function gd(t,e){t.min=e.min,t.max=e.max}function it(t,e){gd(t.x,e.x),gd(t.y,e.y)}function md(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function vd(t,e,i,n,s){return t-=e,t=Xn(t,1/i,n),s!==void 0&&(t=Xn(t,1/s,n)),t}function kv(t,e=0,i=1,n=.5,s,o=t,r=t){if(mt.test(e)&&(e=parseFloat(e),e=Ce(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Ce(o.min,o.max,n);t===o&&(a-=e),t.min=vd(t.min,e,i,a,s),t.max=vd(t.max,e,i,a,s)}function _d(t,e,[i,n,s],o,r){kv(t,e[i],e[n],e[s],e.scale,o,r)}const Iv=["x","scaleX","originX"],Rv=["y","scaleY","originY"];function yd(t,e,i,n){_d(t.x,e,Iv,i?i.x:void 0,n?n.x:void 0),_d(t.y,e,Rv,i?i.y:void 0,n?n.y:void 0)}function bd(t){return t.translate===0&&t.scale===1}function wd(t){return bd(t.x)&&bd(t.y)}function Sd(t,e){return t.min===e.min&&t.max===e.max}function Av(t,e){return Sd(t.x,e.x)&&Sd(t.y,e.y)}function Cd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Td(t,e){return Cd(t.x,e.x)&&Cd(t.y,e.y)}function Ed(t){return je(t.x)/je(t.y)}function kd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class xv{constructor(){this.members=[]}add(e){Zs(this.members,e),e.scheduleRender()}remove(e){if(Qs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){const i=this.members.findIndex(s=>e===s);if(i===0)return!1;let n;for(let s=i;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){n=o;break}}return n?(this.promote(n),!0):!1}promote(e,i){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,i&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:i,resumingFrom:n}=e;i.onExitComplete&&i.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Lv(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:p,skewY:_}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),p&&(n+=`skewX(${p}deg) `),_&&(n+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(n+=`scale(${a}, ${l})`),n||"none"}const nr=["","X","Y","Z"],Dv=1e3;let Ov=0;function sr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Id(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=xc(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",we,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&Id(n)}function Rd({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Ov++,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(Nv),this.nodes.forEach(Uv),this.nodes.forEach($v),this.nodes.forEach(Fv)},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 bv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new io),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=dc(r)&&!Lg(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 u,d=0;const h=()=>this.root.updateBlockedByResize=!1;we.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=wv(h,250),Zn.hasAnimatedSinceResize&&(Zn.hasAnimatedSinceResize=!1,this.nodes.forEach(Ld)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||qv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),w=!this.targetLayout||!Td(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Oo(_,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,C)}else d||Ld(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),Pt(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(jv),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&&Id(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Ad);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(xd);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Vv),this.nodes.forEach(Mv),this.nodes.forEach(Pv)):this.nodes.forEach(xd),this.clearAllSnapshots();const a=qe.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,oo.update.process(Pe),oo.preRender.process(Pe),oo.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,No.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Bv),this.sharedNodes.forEach(Hv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,we.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){we.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!je(this.snapshot.measuredBox.x)&&!je(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=ke(),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=n(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:i(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&&!wd(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Zt(this.latestValues)||u)&&(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)),zv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Kv))){const{scroll:u}=this.root;u&&(bi(a.x,u.offset.x),bi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(it(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&it(a,r),bi(a.x,d.offset.x),bi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();it(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&wi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&wi(l,u.latestValues)}return Zt(this.latestValues)&&wi(l,this.latestValues),l}removeTransform(r){const a=ke();it(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;Zo(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();it(u,d),yd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&yd(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!==Pe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Pe.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Zm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):it(this.target,this.layout.layoutBox),qc(this.target,this.targetDelta)):it(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.target,p.target),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Zo(this.parent.latestValues)||Hc(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===Pe.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;it(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Qm(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=ke());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(md(this.prevProjectionDelta.x,this.projectionDelta.x),md(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!kd(this.projectionDelta.x,this.prevProjectionDelta.x)||!kd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}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=yi(),this.projectionDelta=yi(),this.projectionDeltaWithTransform=yi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),p=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=p!==_,b=this.getStack(),w=!b||b.members.length<=1,C=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(Gv));this.animationProgress=0;let k;this.mixTargetDelta=L=>{const R=L/1e3;Dd(d.x,r.x,R),Dd(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ln(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Wv(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&Av(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),it(k,this.relativeTarget)),v&&(this.animationValues=u,Cv(u,c,this.latestValues,R,C,w)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},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&&(Pt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=we.update(()=>{Zn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=mi(0)),this.currentAnimation=_v(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},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(Dv),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&Fd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=je(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=je(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}it(a,l),wi(a,u),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new xv),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&sr("z",r,c,this.animationValues);for(let u=0;u<nr.length;u++)sr(`rotate${nr[u]}`,r,c,this.animationValues),sr(`skew${nr[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);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=Yn(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=Yn(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Lv(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:p}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const _ in tn){if(u[_]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:w}=tn[_],C=d==="none"?u[_]:v(u[_],c);if(b){const k=b.length;for(let L=0;L<k;L++)r[b[L]]=C}else w?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Yn(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(Ad),this.root.sharedNodes.clear()}}}function Mv(t){t.updateLayout()}function Pv(t){var i;const e=((i=t.resumeFrom)==null?void 0:i.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=je(h);h.min=n[d].min,h.max=h.min+p}):Fd(o,e.layoutBox,n)&&tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=je(n[d]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+p)});const a=yi();an(a,n,e.layoutBox);const l=yi();r?an(l,t.applyTransform(s,!0),e.measuredBox):an(l,n,e.layoutBox);const c=!wd(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:p}=d;if(h&&p){const _=ke();ln(_,e.layoutBox,h.layoutBox);const v=ke();ln(v,n,p.layoutBox),Td(_,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Nv(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 Fv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Bv(t){t.clearSnapshot()}function Ad(t){t.clearMeasurements()}function xd(t){t.isLayoutDirty=!1}function Vv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Ld(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Uv(t){t.resolveTargetDelta()}function $v(t){t.calcProjection()}function jv(t){t.resetSkewAndRotation()}function Hv(t){t.removeLeadSnapshot()}function Dd(t,e,i){t.translate=Ce(e.translate,0,i),t.scale=Ce(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function Od(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function Wv(t,e,i,n){Od(t.x,e.x,i.x,n),Od(t.y,e.y,i.y,n)}function Gv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const qv={duration:.45,ease:[.4,0,.1,1]},Md=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Pd=Md("applewebkit/")&&!Md("chrome/")?Math.round:et;function Nd(t){t.min=Pd(t.min),t.max=Pd(t.max)}function zv(t){Nd(t.x),Nd(t.y)}function Fd(t,e,i){return t==="position"||t==="preserve-aspect"&&!Jm(Ed(e),Ed(i),.2)}function Kv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Yv=Rd({attachResizeListener:(t,e)=>sn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),or={current:void 0},Bd=Rd({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!or.current){const t=new Yv({});t.mount(window),t.setOptions({layoutScroll:!0}),or.current=t}return or.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Xv={pan:{Feature:pv},drag:{Feature:fv,ProjectionNode:Bd,MeasureLayout:cd}};function Vd(t,e,i){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",i==="Start");const s="onHover"+i,o=n[s];o&&we.postRender(()=>o(e,on(e)))}class Jv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=kg(e,(i,n)=>(Vd(this.node,n,"Start"),s=>Vd(this.node,s,"End"))))}unmount(){}}class Zv extends Bt{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=Wi(sn(this.node.current,"focus",()=>this.onFocus()),sn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ud(t,e,i){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",i==="Start");const s="onTap"+(i==="End"?"":i),o=n[s];o&&we.postRender(()=>o(e,on(e)))}class Qv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=xg(e,(i,n)=>(Ud(this.node,n,"Start"),(s,{success:o})=>Ud(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const rr=new WeakMap,ar=new WeakMap,e_=t=>{const e=rr.get(t.target);e&&e(t)},t_=t=>{t.forEach(e_)};function i_({root:t,...e}){const i=t||document;ar.has(i)||ar.set(i,{});const n=ar.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(t_,{root:t,...e})),n[s]}function n_(t,e,i){const n=i_(e);return rr.set(t,i),n.observe(t),()=>{rr.delete(t),n.unobserve(t)}}const s_={some:0,all:1};class o_ extends Bt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:i,margin:n,amount:s="some",once:o}=e,r={root:i?i.current:void 0,rootMargin:n,threshold:typeof s=="number"?s:s_[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:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return n_(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(r_(e,i))&&this.startObserver()}unmount(){}}function r_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const a_={inView:{Feature:o_},tap:{Feature:Qv},focus:{Feature:Zv},hover:{Feature:Jv}},l_={layout:{ProjectionNode:Bd,MeasureLayout:cd}},lr={current:null},$d={current:!1};function c_(){if($d.current=!0,!!Js)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>lr.current=t.matches;t.addEventListener("change",e),e()}else lr.current=!1}const d_=new WeakMap;function u_(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ve(s))t.addValue(n,s);else if(Ve(o))t.addValue(n,mi(s,{owner:t}));else if(o!==s)if(t.hasValue(n)){const r=t.getValue(n);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(n);t.addValue(n,mi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const jd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class h_{scrapeMotionValuesFromProps(e,i,n){return{}}constructor({parent:e,props:i,presenceContext:n,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=Lo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=qe.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,we.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=i.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=i,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Kn(i),this.isVariantNode=vc(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const p=d[h];l[h]!==void 0&&Ve(p)&&p.set(l[h],!1)}}mount(e){this.current=e,d_.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((i,n)=>this.bindToMotionValue(n,i)),$d.current||c_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Pt(this.notifyUpdate),Pt(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 i=this.features[e];i&&(i.unmount(),i.isMounted=!1)}this.current=null}bindToMotionValue(e,i){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=gi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&we.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),o=i.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),i.owner&&i.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 vi){const i=vi[e];if(!i)continue;const{isEnabled:n,Feature:s}=i;if(!this.features[e]&&s&&n(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):ke()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let n=0;n<jd.length;n++){const s=jd[n];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=u_(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 i=this.getClosestVariantNode();if(i)return i.variantChildren&&i.variantChildren.add(e),()=>i.variantChildren.delete(e)}addValue(e,i){const n=this.values.get(e);i!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&i!==void 0&&(n=mi(i===null?void 0:i,{owner:this}),this.addValue(e,n)),n}readValue(e,i){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(il(n)||sl(n))?n=parseFloat(n):!Og(n)&&Ft.test(i)&&(n=tc(e,i)),this.setBaseTarget(e,Ve(n)?n.get():n)),Ve(n)?n.get():n}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var o;const{initial:i}=this.props;let n;if(typeof i=="string"||typeof i=="object"){const r=Go(this.props,i,(o=this.presenceContext)==null?void 0:o.custom);r&&(n=r[e])}if(i&&n!==void 0)return n;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ve(s)?s:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new io),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Hd extends h_{constructor(){super(...arguments),this.KeyframeResolver=wg}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){return e.style?e.style[i]:void 0}removeValueFromRenderState(e,{vars:i,style:n}){delete i[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ve(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function Wd(t,{style:e,vars:i},n,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,n);for(r in i)o.setProperty(r,i[r])}function f_(t){return window.getComputedStyle(t)}class p_ extends Hd{constructor(){super(...arguments),this.type="html",this.renderInstance=Wd}readValueFromInstance(e,i){var n;if(gi.has(i))return(n=this.projection)!=null&&n.isProjecting?ko(i):$p(e,i);{const s=f_(e),o=(ro(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Xc(e,i)}build(e,i,n){jo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return qo(e,i,n)}}const Gd=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 g_(t,e,i,n){Wd(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(Gd.has(s)?s:$o(s),e.attrs[s])}class m_ extends Hd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(gi.has(i)){const n=ec(i);return n&&n.default||0}return i=Gd.has(i)?i:$o(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return Ac(e,i,n)}build(e,i,n){Tc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){g_(e,i,n,s)}mount(e){this.isSVGTag=kc(e.tagName),super.mount(e)}}const v_=(t,e)=>Wo(t)?new m_(e):new p_(e,{allowProjection:t!==ht}),__=vm({...Hm,...a_,...Xv,...l_},v_),Si=Hg(__),y_=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region","skip-last-voice-sdk-id"],dn="widget-layout-id";function qd(t){var e,i,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=qd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function At(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=qd(t))&&(n&&(n+=" "),n+=e);return n}const b_=Dn("listening"),cr=()=>el(b_);function w_(t){var i;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((i=e.params)==null?void 0:i.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Qn={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},zd=Dn(Qn),S_=()=>{const t=Mn(zd);return Ge(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Qn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Qn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Qn.speak_to_interrupt_text),i}),[t])},Qt=()=>Ys(zd),Kd=({size:t="large",className:e})=>{const i=Qt(),[n]=cr();return D("h1",{className:At({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Yd=({stream:t,chatMode:e})=>{const i=ue(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:i,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 T_="4.5.1",dr=Math.PI,Ci=2*dr,ur=dr/2,zd=8.17579892,Kd="dual-combined",es="dual-horizontal",xt="single",mt="dual-vertical",Yd="bar-index",Xd="bar-level",ts="gradient",Jd=60,Zd="click",E_="fullscreenchange",Qd="resize",k_="#111",eu="",tu="A",iu="B",nu="C",su="D",ou="468",is="sans-serif",I_="#0f0",R_="#7f7f7f22",Ti=10,ru="create",au="fschange",A_="lores",x_=Qd,hr="user",L_="#000c",lu="#fff",D_="#4f4",cu="#888",O_="#555",fr="bark",un="linear",Ei="log",pr="mel",du=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],uu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:du}],["rainbow",{dir:"h",colorStops:["#817",...du,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],hn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:ts,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ei,gradient:uu[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:eu,width:void 0},M_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],P_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],N_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],gr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],F_=["ERR_INVALID_MODE","Invalid mode"],V_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],B_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],U_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],$_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],j_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class it extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const hu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),fu=t=>{for(const e in t)return!1;return!0},ns=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],W_=(t,e,i,n,s)=>e+(n-e)*(s-t)/(i-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 H_{constructor(e,i={}){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||(fu(i)&&!fu(e)&&(i=e),e=null),this._ownCanvas=!(i.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):i.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[d,h]of uu)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(i.source&&(s=i.source.context))){if(!(s=i.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new it(M_)}}if(!s.createGain)throw new it(P_);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(),i.source&&this.connectInput(i.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),i.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=i.fsElement||n;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(x_),this._fsTimeout=0)},Jd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Qd,l,{signal:c}),n.addEventListener(E_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(au),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Jd)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Zd,u))};window.addEventListener(Zd,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(i,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(ru)}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=ns(e,[xt,es,mt,Kd]),this._input.disconnect(),this._input.connect(this._chLayout!=xt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=xt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=ns(e,[ts,Yd,Xd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const i=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(i),new Float32Array(i)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=ns(e,[Ei,fr,pr,un]),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||hn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(hr)}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(A_)}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 i of[0,1])this._analyzer[i].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 it(gr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const i of[0,1])this._analyzer[i].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new it(gr);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 i=e|0;if(i>=0&&i<=10&&i!=9)this._mode=i,this._calcBars(),this._makeGrad();else throw new it(F_,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||hn.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 it(V_);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const i of[0,1])this._analyzer[i].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-ur),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return hu("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){hu("stereo","channelLayout"),this.channelLayout=e?mt:xt}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=ns(e,[eu,tu,iu,nu,su,ou],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(hr)}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 T_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new it(B_);const n=i?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const i of[0,1])this._analyzer[i].connect(this._chLayout==xt&&!i?this._output:this._merger,0,i)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:i,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&i.remove(),this._calcBars()}disconnectInput(e,i){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(i&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(i=>i!==e):[],this._outNodes.length==0))for(const i of[0,1])this._analyzer[i].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,i){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,i]=a[e]}const n=this._freqToBin(e),s=i?this._freqToBin(i):n,o=this._chLayout==xt?1:2;let r=0;for(let a=0;a<o;a++)for(let l=n;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let i={};for(const n of Object.keys(hn))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(i.gradientLeft=this.gradientLeft,i.gradientRight=this.gradientRight):n!="start"&&(i[n]=this[n]));return i}registerGradient(e,i){if(typeof e!="string"||e.trim().length==0)throw new it(U_);if(typeof i!="object")throw new it($_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new it(j_);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?n[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(n[a].level=1-a/s)}),n.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:i.bgColor||k_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(hr)}setFreqRange(e,i){if(e<1||i<1)throw new it(gr);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,p=s.width>>1,_=s.height>>1,v=o==mt&&!u,b=o==es,w=c%10!=0,C=w&&this._frequencyScale==Ei,k=this._showLeds&&w&&!u,L=this._lumiBars&&w&&!u,R=this._alphaBars&&!L&&c!=Ti,O=this._outlineBars&&w&&!L&&!k,T=this._roundBars&&w&&!L&&!k,E=o!=mt||h>0&&!L,g=s.height-(v&&!k?.5:0)>>v,m=g*(L||u?1:1-h)|0,f=s.width-p*(b||l!=0),S=v?s.height-g*2:0,I=p*(l==-1&&!b&&!u);let A=Math.min(s.width,s.height)*.375*(o==mt?1:this._radius)|0,x=Math.min(p,_);d&&o!=mt&&([A,x]=[x,A]);const P=J=>e.push({...J,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=J=>{const te=this._freqToBin(J,"floor"),ie=this._binToFreq(te),ne=this._binToFreq(te+1),me=Math.log2(J/ie)/Math.log2(ne/ie);return[te,me]};let F,H,$;if(C){const J=(oe,ge,fe)=>+oe.toPrecision(fe?Math.max(ge,1+Math.log10(oe)|0):ge),te=oe=>{const ge=[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],fe=Math.log10(oe)|0,St=oe/10**fe;let lt=1;for(;lt<ge.length&&St>ge[lt];)lt++;return St-ge[lt-1]<ge[lt]-St&&lt--,(ge[lt]*10**(fe+5)|0)/1e5},ie=[0,24,12,8,6,4,3,2,1][c],ne=i?10**(3/(ie*10)):2**(1/ie),me=ne**.5;let Le=i?7.94328235/(ie%2?1:me):zd;do{let oe=Le;const ge=J(oe/me,4,!0),fe=J(oe*me,4,!0),[St,lt]=M(ge),[wn,Ct]=M(fe);i?oe=ie<4?te(oe):J(oe,oe.toString()[0]<5?3:2):oe=J(oe,4,!0),oe>=a&&P({posX:0,freq:oe,freqLo:ge,freqHi:fe,binLo:St,binHi:wn,ratioLo:lt,ratioHi:Ct}),Le*=ne}while(Le<=r);F=f/e.length,e.forEach((oe,ge)=>oe.posX=I+ge*F);const ye=e[0],he=e[e.length-1];H=this._freqScaling(ye.freqLo),$=f/(this._freqScaling(he.freqHi)-H),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=M(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=M(r))}else if(w){const J=[0,24,12,8,6,4,3,2,1][c]*10,te=ie=>{switch(this._frequencyScale){case fr:return 1960/(26.81/(ie+.53)-1);case pr:return 700*(2**ie-1);case un:return ie}};F=f/J,H=this._freqScaling(a),$=f/(this._freqScaling(r)-H);for(let ie=0,ne=0;ie<J;ie++,ne+=F){const me=te(H+ne/$),Le=te(H+(ne+F/2)/$),ye=te(H+(ne+F)/$),[he,oe]=M(me),[ge,fe]=M(ye);P({posX:I+ne,freq:Le,freqLo:me,freqHi:ye,binLo:he,binHi:ge,ratioLo:oe,ratioHi:fe})}}else{F=1,H=this._freqScaling(a),$=f/(this._freqScaling(r)-H);const J=this._freqToBin(a,"floor"),te=this._freqToBin(r);let ie=-999;for(let ne=J;ne<=te;ne++){const me=this._binToFreq(ne),Le=I+Math.round($*(this._freqScaling(me)-H));if(Le>ie)P({posX:Le,freq:me,freqLo:me,freqHi:me,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),ie=Le;else if(e.length){const ye=e[e.length-1];ye.binHi=ne,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let Z=0,Y=0;if(k){const J=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),te=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],ie=this._ledParams,[ne,me,Le]=ie||te[c];let ye,he=m;if(ie){const oe=2*J;let ge;ye=ne+1;do ye--,ge=he/ye/(1+me),Y=ge*me;while((ge<oe||Y<oe)&&ye>1)}else{const oe=540/me;Y=Math.min(me*J,Math.max(2,he/oe+.1|0))}E&&(he+=Y),ie||(ye=Math.min(ne,he/(Y*2)|0)),Z=Le>=1?Le:F*Le,this._leds=[ye,Z,Y,he/ye-Y]}const W=Math.min(F-1,n*(n>0&&n<1?F:1));w&&(F-=Math.max(k?Z:0,W)),e.forEach((J,te)=>{let ie=J.posX,ne=F;w&&(n==0&&!k?(ie|=0,ne|=0,te>0&&ie>e[te-1].posX+e[te-1].width&&(ie--,ne++)):ie+=Math.max(k?Z:0,W)/2,J.posX=ie),J.barCenter=ie+(F==1?0:ne/2),J.width=ne});const ce=[];for(const J of[0,1]){const te=o==mt?(g+S)*J:0,ie=te+g,ne=te+m-(!k||E?0:Y);ce.push({channelTop:te,channelBottom:ie,analyzerBottom:ne})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:p,centerY:_,channelCoords:ce,channelHeight:g,channelGap:S,initialX:I,innerRadius:A,outerRadius:x,scaleMin:H,unitWidth:$},this._flg={isAlpha:R,isBands:w,isLeds:k,isLumi:L,isOctaves:C,isOutline:O,isRound:T,noLedGap:E},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,_=h.canvas,v=[],b=this._chLayout==es,w=this._chLayout==mt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],L=C/34|0,R=p.height>>1,O=L>>1,T=R*(c?.7:1.5),E=O*(c?1:2),g=2**(1/12);if(!c&&(this._ansiBands||a!=Ei))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==un?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=zd;for(let P=-1;P<11;P++)for(let M=0;M<12;M++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[M],H=F=="C";(F&&c&&!l&&!b||H)&&v.push(c?[x,F+(H?P:"")]:x)}x*=g}}_.width=_.height=Math.max(C*.15,(n<<1)+w*L);const m=_.width>>1,f=m-L*.7,S=(x,P)=>{const M=Ci*(x/r.width),F=M-ur,H=f*Math.cos(F),$=f*Math.sin(F);h.save(),h.translate(m+H,m+$),h.rotate(M),h.fillText(P,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=L_,d.fillRect(0,0,p.width,p.height),h.arc(m,m,m-L/2,0,Ci),h.lineWidth=L,h.stroke(),d.fillStyle=h.fillStyle=lu,d.font=`${R}px ${is}`,h.font=`${O}px ${is}`,d.textAlign=h.textAlign="center";let I=-T/4,A=-E;for(const x of v){const[P,M]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(P)-s),H=p.height*.75,$=M[0]=="C",Z=R*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?D_:lu,c){const Y=a==Ei,W=a==un;let ce=["C"];if((Y||P>2e3||!W&&P>250||(!u||w)&&(!W&&P>125||P>1e3))&&ce.push("G"),(Y||P>4e3||!W&&P>500||(!u||w)&&(!W&&P>250||P>2e3))&&ce.push("E"),(W&&P>4e3||(!u||w)&&(Y||P>2e3||!W&&P>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(M,b&&l==-1?e-F:i+F,H,Z),(b||l&&(F>T||l==1))&&d.fillText(M,b&&l!=1?e+F:(i||r.width)-F,H,Z),I=F+Math.min(Z,d.measureText(M).width)/2),F>=A+E&&F<e-E&&(S(b&&l==1?e-F:F,M),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,M),A=F)}}_draw(e){this._runId=requestAnimationFrame(U=>this._draw(U));const i=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,i>=1e3&&(this._fps=this._frames/i*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:p,centerX:_,centerY:v,channelCoords:b,channelHeight:w,channelGap:C,initialX:k,innerRadius:L,outerRadius:R}=this._aux,{_bars:O,canvas:T,_canvasGradients:E,_chLayout:g,_colorMode:m,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:A,_fps:x,_linearAmplitude:P,_lineWidth:M,maxDecibels:F,minDecibels:H,_mirror:$,_mode:Z,overlay:Y,_radial:W,showBgColor:ce,showPeaks:J,useCanvas:te,_weightingFilter:ie}=this,ne=this._scaleX.canvas,me=this._scaleR.canvas,Le=x*this._peakFadeTime/1e3,ye=x**2,he=this._gravity*1e3,oe=x*this._peakHoldTime/1e3,ge=g==Kd,fe=g==es,St=g==mt,lt=g==xt,wn=a&&this._trueLeds&&m==ts,Ct=W?T.width:this._aux.analyzerWidth,Ur=k+Ct,Sn=J&&this._peakLine&&Z==Ti,$t=W?R-L:p,hw=$t/this._pixelRatio,[fw,Cw,Cn,$r]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ci/60/x);const pw=U=>{if(this._reflexRatio>0&&!l&&!W){let de,Tt;this.reflexFit||St?(de=St&&U==0?w+C:0,Tt=w-p):(de=T.height-p*2,Tt=p),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,b[U].channelTop,T.width,p,0,de,T.width,Tt),f.restore()}},gw=()=>{this.showScaleX&&(W?(f.save(),f.translate(_,v),this._spinSpeed&&f.rotate(this._spinAngle+ur),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ne,0,T.height-ne.height))},mw=U=>{const de=U**2,Tt=424.36,Ve=11599.29,Ts=25122.25,jt=544496.41,Ot=148693636,oi=ri=>20*Math.log10(ri);switch(ie){case tu:const ri=Ot*de**2/((de+Tt)*Math.sqrt((de+Ve)*(de+jt))*(de+Ot));return 2+oi(ri);case iu:const ai=Ot*de*U/((de+Tt)*Math.sqrt(de+Ts)*(de+Ot));return .17+oi(ai);case nu:const Hr=Ot*de/((de+Tt)*(de+Ot));return .06+oi(Hr);case su:const Es=((103791848e-2-de)**2+108076816e-2*de)/((9837328-de)**2+11723776*de),Gr=U/68966888496476e-18*Math.sqrt(Es/((de+79919.29)*(de+1345600)));return oi(Gr);case ou:const ks=-4737338981378384e-39*U**6+2043828333606125e-30*U**4-1363894795463638e-22*de+1,li=1306612257412824e-34*U**5-2118150887518656e-26*U**3+.0005559488023498642*U,Xe=.0001246332637532143*U/Math.hypot(ks,li);return 18.2+oi(Xe)}return 0},jr=(U,de,Tt)=>{f.beginPath(),f.moveTo(U,de),f.lineTo(U,Tt),f.stroke()},Wr=U=>{if(U&&M){const de=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=de}},si=U=>Math.max(0,(U*fw|0)*($r+Cn)-Cn),vw=U=>{S.val=U,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*he/ye/T.height*this._pixelRatio)),U>=S.peak&&(S.peak=U,S.hold=oe)};Y&&f.clearRect(0,0,T.width,T.height);let Gh=0;const qh=O.length,zh=lt?1:2;for(let U=0;U<zh;U++){const{channelTop:de,channelBottom:Tt,analyzerBottom:Ve}=b[U],Ts=this._gradients[this._selectedGrads[U]],jt=Ts.colorStops,Ot=jt.length,oi=!ce||a&&!Y?"#000":Ts.bgColor,ri=St&&W&&U?-1:1,ai=!U&&$==-1||U&&$==1,Hr=!fe||U&&$!=1?0:Ct>>(U||!ai),Es=fe&&ai?-1:1,Gr=()=>{const q=ne.height,X=q>>1,ee=P?100:F,be=P?0:H,Re=P?20:5,ze=p/(ee-be),Et=$!=-1&&(!fe||U==0||$==1),Wt=$!=1&&(!fe||U!=$);f.save(),f.fillStyle=cu,f.font=`${X}px ${is}`,f.textAlign="right",f.lineWidth=1;for(let Ht=ee;Ht>be;Ht-=Re){const Ni=de+(ee-Ht)*ze,Me=Ht%2==0|0;if(Me){const We=Ni+X*(Ni==de?.8:.35);Et&&f.fillText(Ht,q*.85,We),Wt&&f.fillText(Ht,(fe?Ct:T.width)-q*.1,We),f.strokeStyle=cu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=O_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+q*Me*Et,~~Ni+.5),f.lineTo(Ur-q*Me*Wt,~~Ni+.5),f.stroke()}f.restore()},ks=(q,X)=>{const ee=ct[q]+(q<ct.length-1?(ct[q+1]-ct[q])*X:0);return isNaN(ee)?-1/0:ee},li=(q,X=Es)=>X*Ci*((q+Hr)/T.width)+this._spinAngle,Xe=(q,X,ee)=>{const be=L+X*ri,Re=li(q,ee);return[_+be*Math.cos(Re),v+be*Math.sin(Re)]},qr=(q,X,ee,be,Re)=>{f.beginPath();for(const ze of $&&!fe?[1,-1]:[Es]){const[Et,Wt]=d?[li(q,ze),li(q+ee,ze)]:[];f.moveTo(...Xe(q,X,ze)),f.lineTo(...Xe(q,X+be,ze)),d?f.arc(_,v,L+(X+be)*ri,Et,Wt,ze!=1):f.lineTo(...Xe(q+ee,X+be,ze)),f.lineTo(...Xe(q+ee,X,ze)),d&&!Re&&f.arc(_,v,L+X*ri,Wt,Et,ze==1)}Wr(Re),f.fill()},zr=(q=0,X=0)=>{let ee;if(m==ts&&!wn||Z==Ti)ee=E[U];else{const be=m==Yd?X%Ot:jt.findLastIndex(Re=>a?si(q)<=si(Re.level):q<=Re.level);ee=jt[be].color}f.fillStyle=f.strokeStyle=ee};if(te){if(fe&&!W){const q=Ct*(U+ai),X=ai?-1:1;f.setTransform(X,0,0,1,q,0)}if((!Y||ce)&&(Y&&(f.globalAlpha=this.bgAlpha),f.fillStyle=oi,(U==0||!W&&!ge)&&f.fillRect(k,de-C,Ct,(Y&&this.reflexAlpha==1?p:w)+C),f.globalAlpha=1),this.showScaleY&&!l&&!W&&(U==0||!ge)&&Gr(),a?(f.setLineDash([$r,Cn]),f.lineWidth=O[0].width):f.lineWidth=u?Math.min(M,O[0].width/2):M,f.save(),!W){const q=new Path2D;q.rect(0,de,T.width,p),f.clip(q)}}let ct=this._fftData[U];this._analyzer[U].getFloatFrequencyData(ct),ie&&(ct=ct.map((q,X)=>q+mw(this._binToFreq(X)))),f.beginPath();let Tn=[];for(let q=0;q<qh;q++){const X=O[q],{posX:ee,barCenter:be,width:Re,freq:ze,binLo:Et,binHi:Wt,ratioLo:Ht,ratioHi:Ni}=X;let Me=Math.max(ks(Et,Ht),ks(Wt,Ni));for(let ve=Et+1;ve<Wt;ve++)ct[ve]>Me&&(Me=ct[ve]);if(Me=this._normalizedB(Me),X.value[U]=Me,Gh+=Me,X.peak[U]>0&&X.alpha[U]>0&&(X.hold[U]--,X.hold[U]<0)){if(I&&!Sn){const ve=!o||u&&M>0?1:o?X.peak[U]:A;X.alpha[U]=ve*(1+X.hold[U]/Le)}else X.peak[U]+=X.hold[U]*he/ye/hw;X.alpha[U]<=0&&(X.peak[U]=0)}if(Me>=X.peak[U]&&(X.peak[U]=Me,X.hold[U]=oe,X.alpha[U]=!o||u&&M>0?1:o?Me:A),!te)continue;f.globalAlpha=l||o?Me:u?A:1,zr(Me,q);const We=l?$t:a?si(Me):Me*$t|0;if(Z==Ti){const ve=q?0:(this._normalizedB(ct[O[1].binLo])*$t+We)/2;if(W){if(q==0&&(fe&&f.moveTo(...Xe(0,0)),f.lineTo(...Xe(0,ee<0?ve:We))),ee>=0){const st=[ee,We];f.lineTo(...Xe(...st)),Tn.push(st)}}else{if(q==0)if($==-1&&!fe)f.moveTo(k,Ve-(ee<k?ve:We));else{const st=Et?this._normalizedB(ct[Et-1])*$t:We;f.moveTo(k-M,Ve-st)}(fe||$!=-1||ee>=k)&&f.lineTo(ee,Ve-We)}}else if(a){if(ce&&!Y&&(U==0||!ge)){const ve=f.globalAlpha;f.strokeStyle=R_,f.globalAlpha=1,jr(be,de,Ve),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(wn){const ve=l?0:jt.findLastIndex(ci=>si(Me)<=si(ci.level));let st=Ve;for(let ci=Ot-1;ci>=ve;ci--){f.strokeStyle=jt[ci].color;let Yh=Ve-(ci==ve?We:si(jt[ci].level));jr(be,st,Yh),st=Yh-Cn}}else jr(be,Ve,Ve-We)}else if(ee>=k)if(W)qr(ee,0,Re,We,u);else if(d){const ve=Re/2,st=Ve+ve;f.beginPath(),f.moveTo(ee,st),f.lineTo(ee,st-We),f.arc(be,st-We,ve,dr,Ci),f.lineTo(ee+Re,st),Wr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(ee,Ve+ve,Re,-We-ve),Wr(u),f.fill()}const Fi=X.peak[U],Kh=X.alpha[U];if(Fi>0&&Kh>0&&J&&!Sn&&!l&&ee>=k&&ee<Ur){if(I?f.globalAlpha=Kh:u&&M>0?f.globalAlpha=1:o&&(f.globalAlpha=Fi),(m==Xd||wn)&&zr(Fi),a){const ve=si(Fi);ve>=Cn&&f.fillRect(ee,Ve-ve,Re,$r)}else if(!W)f.fillRect(ee,Ve-Fi*$t,Re,2);else if(Z!=Ti){const ve=Fi*$t;qr(ee,ve,Re,!this._radialInvert||St||ve+L>=2?-2:2)}}}if(te){if(f.globalAlpha=1,Z==Ti){if(zr(),W&&!fe){if($){let q;for(;q=Tn.pop();)f.lineTo(...Xe(...q,-1))}f.closePath()}if(M>0&&f.stroke(),A>0){if(W){const q=fe?li(Ct>>1):0,X=fe?li(Ct):Ci;f.moveTo(...Xe(fe?Ct>>1:0,0)),f.arc(_,v,L,q,X,fe?!ai:!0)}else f.lineTo(Ur,Ve),f.lineTo(k,Ve);f.globalAlpha=A,f.fill(),f.globalAlpha=1}if((Sn||W&&J)&&(Tn=[],f.beginPath(),O.forEach((q,X)=>{let ee=q.posX,be=q.peak[U],Re=X?"lineTo":"moveTo";if(W&&ee<0){const ze=O[X+1];be=W_(ee,be,ze.posX,ze.peak[U],0),ee=0}be*=$t,Sn?(f[Re](...W?Xe(ee,be):[ee,Ve-be]),W&&$&&!fe&&Tn.push([ee,be])):be>0&&qr(ee,be,1,-2)}),Sn)){let q;for(;q=Tn.pop();)f.lineTo(...Xe(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),fe&&!W&&f.setTransform(1,0,0,1,0,0),(!fe&&!ge||U)&&pw(U)}}if(vw(Gh/(qh<<zh-1)),te&&($&&!W&&!fe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,_,T.height,0,0,_,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),gw()),this.showFPS){const U=ne.height;f.font=`bold ${U}px ${is}`,f.fillStyle=I_,f.textAlign="right",f.fillText(Math.round(x),T.width-U,U*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case Ei:return Math.log2(e);case fr:return 26.81*e/(1960+e)-.53;case pr:return Math.log2(1+e/700);case un:return e}}_freqToBin(e,i="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[i](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:i,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==mt,p=1-s,_=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],w=b.colorStops,C=b.dir=="h";let k;if(n?k=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):k=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),w){const L=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+L;R++){const O=w.length-1;w.forEach((T,E)=>{let g=T.pos;if(L&&(g/=2),h&&!d&&!n&&!C&&(g*=p,!L&&g>.5*p&&(g+=.5*s)),R==1)if(n||d){const m=O-E;T=w[m],g=1-T.pos/2}else E==0&&g>0&&k.addColorStop(.5,T.color),g+=.5;k.addColorStop(g,T.color),h&&E==O&&g<.5&&k.addColorStop(.5,T.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=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==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=ru&&i.width==u&&i.height==d)&&(i.width=u,i.height=d,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,u,d)),n.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=au),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new it(N_,e);[0,1].includes(i)||(this._selectedGrads[1]=e,i=0),this._selectedGrads[i]=e,this._makeGrad()}_setProps(e,i){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(hn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...hn,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const G_={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}]}},pu=({stream:t,className:e,onClick:i})=>{var o;const n=ue(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new H_(n.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",G_[((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]),D("div",{onClick:i,className:At("w-full",e),ref:n})},gu=Dn(null),mu=({className:t,debug:e=!1})=>{const i=Ys(gu);return!e||!i||!(i.region||i.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&D("span",{children:" · "}),i.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
16
+ */const C_="4.5.1",dr=Math.PI,Ci=2*dr,ur=dr/2,Xd=8.17579892,Jd="dual-combined",es="dual-horizontal",xt="single",vt="dual-vertical",Zd="bar-index",Qd="bar-level",ts="gradient",eu=60,tu="click",T_="fullscreenchange",iu="resize",E_="#111",nu="",su="A",ou="B",ru="C",au="D",lu="468",is="sans-serif",k_="#0f0",I_="#7f7f7f22",Ti=10,cu="create",du="fschange",R_="lores",A_=iu,hr="user",x_="#000c",uu="#fff",L_="#4f4",hu="#888",D_="#555",fr="bark",un="linear",Ei="log",pr="mel",fu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],pu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:fu}],["rainbow",{dir:"h",colorStops:["#817",...fu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],hn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:ts,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ei,gradient:pu[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:nu,width:void 0},O_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],M_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],P_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],gr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],N_=["ERR_INVALID_MODE","Invalid mode"],F_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],B_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],V_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],U_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],$_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class nt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const gu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),mu=t=>{for(const e in t)return!1;return!0},ns=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],j_=(t,e,i,n,s)=>e+(n-e)*(s-t)/(i-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 H_{constructor(e,i={}){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||(mu(i)&&!mu(e)&&(i=e),e=null),this._ownCanvas=!(i.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):i.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[d,h]of pu)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(i.source&&(s=i.source.context))){if(!(s=i.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new nt(O_)}}if(!s.createGain)throw new nt(M_);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(),i.source&&this.connectInput(i.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),i.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=i.fsElement||n;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(A_),this._fsTimeout=0)},eu))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(iu,l,{signal:c}),n.addEventListener(T_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(du),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},eu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(tu,u))};window.addEventListener(tu,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(i,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(cu)}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=ns(e,[xt,es,vt,Jd]),this._input.disconnect(),this._input.connect(this._chLayout!=xt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=xt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=ns(e,[ts,Zd,Qd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const i=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(i),new Float32Array(i)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=ns(e,[Ei,fr,pr,un]),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||hn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(hr)}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(R_)}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 i of[0,1])this._analyzer[i].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 nt(gr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const i of[0,1])this._analyzer[i].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new nt(gr);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 i=e|0;if(i>=0&&i<=10&&i!=9)this._mode=i,this._calcBars(),this._makeGrad();else throw new nt(N_,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||hn.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 nt(F_);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 i of[0,1])this._analyzer[i].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-ur),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return gu("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){gu("stereo","channelLayout"),this.channelLayout=e?vt:xt}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=ns(e,[nu,su,ou,ru,au,lu],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(hr)}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 C_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new nt(B_);const n=i?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const i of[0,1])this._analyzer[i].connect(this._chLayout==xt&&!i?this._output:this._merger,0,i)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:i,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&i.remove(),this._calcBars()}disconnectInput(e,i){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(i&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(i=>i!==e):[],this._outNodes.length==0))for(const i of[0,1])this._analyzer[i].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,i){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,i]=a[e]}const n=this._freqToBin(e),s=i?this._freqToBin(i):n,o=this._chLayout==xt?1:2;let r=0;for(let a=0;a<o;a++)for(let l=n;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let i={};for(const n of Object.keys(hn))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(i.gradientLeft=this.gradientLeft,i.gradientRight=this.gradientRight):n!="start"&&(i[n]=this[n]));return i}registerGradient(e,i){if(typeof e!="string"||e.trim().length==0)throw new nt(V_);if(typeof i!="object")throw new nt(U_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new nt($_);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?n[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(n[a].level=1-a/s)}),n.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:i.bgColor||E_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(hr)}setFreqRange(e,i){if(e<1||i<1)throw new nt(gr);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,p=s.width>>1,_=s.height>>1,v=o==vt&&!u,b=o==es,w=c%10!=0,C=w&&this._frequencyScale==Ei,k=this._showLeds&&w&&!u,L=this._lumiBars&&w&&!u,R=this._alphaBars&&!L&&c!=Ti,O=this._outlineBars&&w&&!L&&!k,T=this._roundBars&&w&&!L&&!k,E=o!=vt||h>0&&!L,g=s.height-(v&&!k?.5:0)>>v,m=g*(L||u?1:1-h)|0,f=s.width-p*(b||l!=0),S=v?s.height-g*2:0,I=p*(l==-1&&!b&&!u);let A=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,x=Math.min(p,_);d&&o!=vt&&([A,x]=[x,A]);const N=J=>e.push({...J,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=J=>{const ee=this._freqToBin(J,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),me=Math.log2(J/te)/Math.log2(ie/te);return[ee,me]};let F,G,U;if(C){const J=(se,ge,pe)=>+se.toPrecision(pe?Math.max(ge,1+Math.log10(se)|0):ge),ee=se=>{const ge=[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],pe=Math.log10(se)|0,St=se/10**pe;let ct=1;for(;ct<ge.length&&St>ge[ct];)ct++;return St-ge[ct-1]<ge[ct]-St&&ct--,(ge[ct]*10**(pe+5)|0)/1e5},te=[0,24,12,8,6,4,3,2,1][c],ie=i?10**(3/(te*10)):2**(1/te),me=ie**.5;let Le=i?7.94328235/(te%2?1:me):Xd;do{let se=Le;const ge=J(se/me,4,!0),pe=J(se*me,4,!0),[St,ct]=M(ge),[wn,Ct]=M(pe);i?se=te<4?ee(se):J(se,se.toString()[0]<5?3:2):se=J(se,4,!0),se>=a&&N({posX:0,freq:se,freqLo:ge,freqHi:pe,binLo:St,binHi:wn,ratioLo:ct,ratioHi:Ct}),Le*=ie}while(Le<=r);F=f/e.length,e.forEach((se,ge)=>se.posX=I+ge*F);const ye=e[0],he=e[e.length-1];G=this._freqScaling(ye.freqLo),U=f/(this._freqScaling(he.freqHi)-G),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=M(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=M(r))}else if(w){const J=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case fr:return 1960/(26.81/(te+.53)-1);case pr:return 700*(2**te-1);case un:return te}};F=f/J,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);for(let te=0,ie=0;te<J;te++,ie+=F){const me=ee(G+ie/U),Le=ee(G+(ie+F/2)/U),ye=ee(G+(ie+F)/U),[he,se]=M(me),[ge,pe]=M(ye);N({posX:I+ie,freq:Le,freqLo:me,freqHi:ye,binLo:he,binHi:ge,ratioLo:se,ratioHi:pe})}}else{F=1,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);const J=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=J;ie<=ee;ie++){const me=this._binToFreq(ie),Le=I+Math.round(U*(this._freqScaling(me)-G));if(Le>te)N({posX:Le,freq:me,freqLo:me,freqHi:me,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Le;else if(e.length){const ye=e[e.length-1];ye.binHi=ie,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let ae=0,q=0;if(k){const J=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),ee=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],te=this._ledParams,[ie,me,Le]=te||ee[c];let ye,he=m;if(te){const se=2*J;let ge;ye=ie+1;do ye--,ge=he/ye/(1+me),q=ge*me;while((ge<se||q<se)&&ye>1)}else{const se=540/me;q=Math.min(me*J,Math.max(2,he/se+.1|0))}E&&(he+=q),te||(ye=Math.min(ie,he/(q*2)|0)),ae=Le>=1?Le:F*Le,this._leds=[ye,ae,q,he/ye-q]}const H=Math.min(F-1,n*(n>0&&n<1?F:1));w&&(F-=Math.max(k?ae:0,H)),e.forEach((J,ee)=>{let te=J.posX,ie=F;w&&(n==0&&!k?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(k?ae:0,H)/2,J.posX=te),J.barCenter=te+(F==1?0:ie/2),J.width=ie});const ce=[];for(const J of[0,1]){const ee=o==vt?(g+S)*J:0,te=ee+g,ie=ee+m-(!k||E?0:q);ce.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:p,centerY:_,channelCoords:ce,channelHeight:g,channelGap:S,initialX:I,innerRadius:A,outerRadius:x,scaleMin:G,unitWidth:U},this._flg={isAlpha:R,isBands:w,isLeds:k,isLumi:L,isOctaves:C,isOutline:O,isRound:T,noLedGap:E},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,_=h.canvas,v=[],b=this._chLayout==es,w=this._chLayout==vt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],L=C/34|0,R=p.height>>1,O=L>>1,T=R*(c?.7:1.5),E=O*(c?1:2),g=2**(1/12);if(!c&&(this._ansiBands||a!=Ei))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==un?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=Xd;for(let N=-1;N<11;N++)for(let M=0;M<12;M++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[M],G=F=="C";(F&&c&&!l&&!b||G)&&v.push(c?[x,F+(G?N:"")]:x)}x*=g}}_.width=_.height=Math.max(C*.15,(n<<1)+w*L);const m=_.width>>1,f=m-L*.7,S=(x,N)=>{const M=Ci*(x/r.width),F=M-ur,G=f*Math.cos(F),U=f*Math.sin(F);h.save(),h.translate(m+G,m+U),h.rotate(M),h.fillText(N,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=x_,d.fillRect(0,0,p.width,p.height),h.arc(m,m,m-L/2,0,Ci),h.lineWidth=L,h.stroke(),d.fillStyle=h.fillStyle=uu,d.font=`${R}px ${is}`,h.font=`${O}px ${is}`,d.textAlign=h.textAlign="center";let I=-T/4,A=-E;for(const x of v){const[N,M]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(N)-s),G=p.height*.75,U=M[0]=="C",ae=R*(c&&!l&&!b?U?1.2:.6:3);if(d.fillStyle=h.fillStyle=U&&!l&&!b?L_:uu,c){const q=a==Ei,H=a==un;let ce=["C"];if((q||N>2e3||!H&&N>250||(!u||w)&&(!H&&N>125||N>1e3))&&ce.push("G"),(q||N>4e3||!H&&N>500||(!u||w)&&(!H&&N>250||N>2e3))&&ce.push("E"),(H&&N>4e3||(!u||w)&&(q||N>2e3||!H&&N>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(M,b&&l==-1?e-F:i+F,G,ae),(b||l&&(F>T||l==1))&&d.fillText(M,b&&l!=1?e+F:(i||r.width)-F,G,ae),I=F+Math.min(ae,d.measureText(M).width)/2),F>=A+E&&F<e-E&&(S(b&&l==1?e-F:F,M),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,M),A=F)}}_draw(e){this._runId=requestAnimationFrame($=>this._draw($));const i=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,i>=1e3&&(this._fps=this._frames/i*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:p,centerX:_,centerY:v,channelCoords:b,channelHeight:w,channelGap:C,initialX:k,innerRadius:L,outerRadius:R}=this._aux,{_bars:O,canvas:T,_canvasGradients:E,_chLayout:g,_colorMode:m,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:A,_fps:x,_linearAmplitude:N,_lineWidth:M,maxDecibels:F,minDecibels:G,_mirror:U,_mode:ae,overlay:q,_radial:H,showBgColor:ce,showPeaks:J,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,me=this._scaleR.canvas,Le=x*this._peakFadeTime/1e3,ye=x**2,he=this._gravity*1e3,se=x*this._peakHoldTime/1e3,ge=g==Jd,pe=g==es,St=g==vt,ct=g==xt,wn=a&&this._trueLeds&&m==ts,Ct=H?T.width:this._aux.analyzerWidth,Hr=k+Ct,Sn=J&&this._peakLine&&ae==Ti,$t=H?R-L:p,mw=$t/this._pixelRatio,[vw,Iw,Cn,Wr]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ci/60/x);const _w=$=>{if(this._reflexRatio>0&&!l&&!H){let de,Tt;this.reflexFit||St?(de=St&&$==0?w+C:0,Tt=w-p):(de=T.height-p*2,Tt=p),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,b[$].channelTop,T.width,p,0,de,T.width,Tt),f.restore()}},yw=()=>{this.showScaleX&&(H?(f.save(),f.translate(_,v),this._spinSpeed&&f.rotate(this._spinAngle+ur),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ie,0,T.height-ie.height))},bw=$=>{const de=$**2,Tt=424.36,Be=11599.29,Ts=25122.25,jt=544496.41,Ot=148693636,oi=ri=>20*Math.log10(ri);switch(te){case su:const ri=Ot*de**2/((de+Tt)*Math.sqrt((de+Be)*(de+jt))*(de+Ot));return 2+oi(ri);case ou:const ai=Ot*de*$/((de+Tt)*Math.sqrt(de+Ts)*(de+Ot));return .17+oi(ai);case ru:const zr=Ot*de/((de+Tt)*(de+Ot));return .06+oi(zr);case au:const Es=((103791848e-2-de)**2+108076816e-2*de)/((9837328-de)**2+11723776*de),Kr=$/68966888496476e-18*Math.sqrt(Es/((de+79919.29)*(de+1345600)));return oi(Kr);case lu:const ks=-4737338981378384e-39*$**6+2043828333606125e-30*$**4-1363894795463638e-22*de+1,li=1306612257412824e-34*$**5-2118150887518656e-26*$**3+.0005559488023498642*$,Je=.0001246332637532143*$/Math.hypot(ks,li);return 18.2+oi(Je)}return 0},Gr=($,de,Tt)=>{f.beginPath(),f.moveTo($,de),f.lineTo($,Tt),f.stroke()},qr=$=>{if($&&M){const de=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=de}},si=$=>Math.max(0,($*vw|0)*(Wr+Cn)-Cn),ww=$=>{S.val=$,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*he/ye/T.height*this._pixelRatio)),$>=S.peak&&(S.peak=$,S.hold=se)};q&&f.clearRect(0,0,T.width,T.height);let Wh=0;const Gh=O.length,qh=ct?1:2;for(let $=0;$<qh;$++){const{channelTop:de,channelBottom:Tt,analyzerBottom:Be}=b[$],Ts=this._gradients[this._selectedGrads[$]],jt=Ts.colorStops,Ot=jt.length,oi=!ce||a&&!q?"#000":Ts.bgColor,ri=St&&H&&$?-1:1,ai=!$&&U==-1||$&&U==1,zr=!pe||$&&U!=1?0:Ct>>($||!ai),Es=pe&&ai?-1:1,Kr=()=>{const z=ie.height,X=z>>1,Q=N?100:F,be=N?0:G,Re=N?20:5,Ke=p/(Q-be),Et=U!=-1&&(!pe||$==0||U==1),Ht=U!=1&&(!pe||$!=U);f.save(),f.fillStyle=hu,f.font=`${X}px ${is}`,f.textAlign="right",f.lineWidth=1;for(let Wt=Q;Wt>be;Wt-=Re){const Ni=de+(Q-Wt)*Ke,Me=Wt%2==0|0;if(Me){const We=Ni+X*(Ni==de?.8:.35);Et&&f.fillText(Wt,z*.85,We),Ht&&f.fillText(Wt,(pe?Ct:T.width)-z*.1,We),f.strokeStyle=hu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=D_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+z*Me*Et,~~Ni+.5),f.lineTo(Hr-z*Me*Ht,~~Ni+.5),f.stroke()}f.restore()},ks=(z,X)=>{const Q=dt[z]+(z<dt.length-1?(dt[z+1]-dt[z])*X:0);return isNaN(Q)?-1/0:Q},li=(z,X=Es)=>X*Ci*((z+zr)/T.width)+this._spinAngle,Je=(z,X,Q)=>{const be=L+X*ri,Re=li(z,Q);return[_+be*Math.cos(Re),v+be*Math.sin(Re)]},Yr=(z,X,Q,be,Re)=>{f.beginPath();for(const Ke of U&&!pe?[1,-1]:[Es]){const[Et,Ht]=d?[li(z,Ke),li(z+Q,Ke)]:[];f.moveTo(...Je(z,X,Ke)),f.lineTo(...Je(z,X+be,Ke)),d?f.arc(_,v,L+(X+be)*ri,Et,Ht,Ke!=1):f.lineTo(...Je(z+Q,X+be,Ke)),f.lineTo(...Je(z+Q,X,Ke)),d&&!Re&&f.arc(_,v,L+X*ri,Ht,Et,Ke==1)}qr(Re),f.fill()},Xr=(z=0,X=0)=>{let Q;if(m==ts&&!wn||ae==Ti)Q=E[$];else{const be=m==Zd?X%Ot:jt.findLastIndex(Re=>a?si(z)<=si(Re.level):z<=Re.level);Q=jt[be].color}f.fillStyle=f.strokeStyle=Q};if(ee){if(pe&&!H){const z=Ct*($+ai),X=ai?-1:1;f.setTransform(X,0,0,1,z,0)}if((!q||ce)&&(q&&(f.globalAlpha=this.bgAlpha),f.fillStyle=oi,($==0||!H&&!ge)&&f.fillRect(k,de-C,Ct,(q&&this.reflexAlpha==1?p:w)+C),f.globalAlpha=1),this.showScaleY&&!l&&!H&&($==0||!ge)&&Kr(),a?(f.setLineDash([Wr,Cn]),f.lineWidth=O[0].width):f.lineWidth=u?Math.min(M,O[0].width/2):M,f.save(),!H){const z=new Path2D;z.rect(0,de,T.width,p),f.clip(z)}}let dt=this._fftData[$];this._analyzer[$].getFloatFrequencyData(dt),te&&(dt=dt.map((z,X)=>z+bw(this._binToFreq(X)))),f.beginPath();let Tn=[];for(let z=0;z<Gh;z++){const X=O[z],{posX:Q,barCenter:be,width:Re,freq:Ke,binLo:Et,binHi:Ht,ratioLo:Wt,ratioHi:Ni}=X;let Me=Math.max(ks(Et,Wt),ks(Ht,Ni));for(let ve=Et+1;ve<Ht;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),X.value[$]=Me,Wh+=Me,X.peak[$]>0&&X.alpha[$]>0&&(X.hold[$]--,X.hold[$]<0)){if(I&&!Sn){const ve=!o||u&&M>0?1:o?X.peak[$]:A;X.alpha[$]=ve*(1+X.hold[$]/Le)}else X.peak[$]+=X.hold[$]*he/ye/mw;X.alpha[$]<=0&&(X.peak[$]=0)}if(Me>=X.peak[$]&&(X.peak[$]=Me,X.hold[$]=se,X.alpha[$]=!o||u&&M>0?1:o?Me:A),!ee)continue;f.globalAlpha=l||o?Me:u?A:1,Xr(Me,z);const We=l?$t:a?si(Me):Me*$t|0;if(ae==Ti){const ve=z?0:(this._normalizedB(dt[O[1].binLo])*$t+We)/2;if(H){if(z==0&&(pe&&f.moveTo(...Je(0,0)),f.lineTo(...Je(0,Q<0?ve:We))),Q>=0){const ot=[Q,We];f.lineTo(...Je(...ot)),Tn.push(ot)}}else{if(z==0)if(U==-1&&!pe)f.moveTo(k,Be-(Q<k?ve:We));else{const ot=Et?this._normalizedB(dt[Et-1])*$t:We;f.moveTo(k-M,Be-ot)}(pe||U!=-1||Q>=k)&&f.lineTo(Q,Be-We)}}else if(a){if(ce&&!q&&($==0||!ge)){const ve=f.globalAlpha;f.strokeStyle=I_,f.globalAlpha=1,Gr(be,de,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(wn){const ve=l?0:jt.findLastIndex(ci=>si(Me)<=si(ci.level));let ot=Be;for(let ci=Ot-1;ci>=ve;ci--){f.strokeStyle=jt[ci].color;let Kh=Be-(ci==ve?We:si(jt[ci].level));Gr(be,ot,Kh),ot=Kh-Cn}}else Gr(be,Be,Be-We)}else if(Q>=k)if(H)Yr(Q,0,Re,We,u);else if(d){const ve=Re/2,ot=Be+ve;f.beginPath(),f.moveTo(Q,ot),f.lineTo(Q,ot-We),f.arc(be,ot-We,ve,dr,Ci),f.lineTo(Q+Re,ot),qr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(Q,Be+ve,Re,-We-ve),qr(u),f.fill()}const Fi=X.peak[$],zh=X.alpha[$];if(Fi>0&&zh>0&&J&&!Sn&&!l&&Q>=k&&Q<Hr){if(I?f.globalAlpha=zh:u&&M>0?f.globalAlpha=1:o&&(f.globalAlpha=Fi),(m==Qd||wn)&&Xr(Fi),a){const ve=si(Fi);ve>=Cn&&f.fillRect(Q,Be-ve,Re,Wr)}else if(!H)f.fillRect(Q,Be-Fi*$t,Re,2);else if(ae!=Ti){const ve=Fi*$t;Yr(Q,ve,Re,!this._radialInvert||St||ve+L>=2?-2:2)}}}if(ee){if(f.globalAlpha=1,ae==Ti){if(Xr(),H&&!pe){if(U){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1))}f.closePath()}if(M>0&&f.stroke(),A>0){if(H){const z=pe?li(Ct>>1):0,X=pe?li(Ct):Ci;f.moveTo(...Je(pe?Ct>>1:0,0)),f.arc(_,v,L,z,X,pe?!ai:!0)}else f.lineTo(Hr,Be),f.lineTo(k,Be);f.globalAlpha=A,f.fill(),f.globalAlpha=1}if((Sn||H&&J)&&(Tn=[],f.beginPath(),O.forEach((z,X)=>{let Q=z.posX,be=z.peak[$],Re=X?"lineTo":"moveTo";if(H&&Q<0){const Ke=O[X+1];be=j_(Q,be,Ke.posX,Ke.peak[$],0),Q=0}be*=$t,Sn?(f[Re](...H?Je(Q,be):[Q,Be-be]),H&&U&&!pe&&Tn.push([Q,be])):be>0&&Yr(Q,be,1,-2)}),Sn)){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1));f.lineWidth=1,f.stroke()}}f.restore(),pe&&!H&&f.setTransform(1,0,0,1,0,0),(!pe&&!ge||$)&&_w($)}}if(ww(Wh/(Gh<<qh-1)),ee&&(U&&!H&&!pe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,_,T.height,0,0,_,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),yw()),this.showFPS){const $=ie.height;f.font=`bold ${$}px ${is}`,f.fillStyle=k_,f.textAlign="right",f.fillText(Math.round(x),T.width-$,$*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case Ei:return Math.log2(e);case fr:return 26.81*e/(1960+e)-.53;case pr:return Math.log2(1+e/700);case un:return e}}_freqToBin(e,i="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[i](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:i,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==vt,p=1-s,_=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],w=b.colorStops,C=b.dir=="h";let k;if(n?k=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):k=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),w){const L=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+L;R++){const O=w.length-1;w.forEach((T,E)=>{let g=T.pos;if(L&&(g/=2),h&&!d&&!n&&!C&&(g*=p,!L&&g>.5*p&&(g+=.5*s)),R==1)if(n||d){const m=O-E;T=w[m],g=1-T.pos/2}else E==0&&g>0&&k.addColorStop(.5,T.color),g+=.5;k.addColorStop(g,T.color),h&&E==O&&g<.5&&k.addColorStop(.5,T.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=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==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=cu&&i.width==u&&i.height==d)&&(i.width=u,i.height=d,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,u,d)),n.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=du),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new nt(P_,e);[0,1].includes(i)||(this._selectedGrads[1]=e,i=0),this._selectedGrads[i]=e,this._makeGrad()}_setProps(e,i){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(hn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...hn,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const W_={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}]}},vu=({stream:t,className:e,onClick:i})=>{var o;const n=ue(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new H_(n.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",W_[((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]),D("div",{onClick:i,className:At("w-full",e),ref:n})},_u=Dn(null),yu=({className:t,debug:e=!1})=>{const i=Ys(_u);return!e||!i||!(i.region||i.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&D("span",{children:" · "}),i.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const vu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),q_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),_u=t=>{const e=q_(t);return e.charAt(0).toUpperCase()+e.slice(1)},z_=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
21
+ */const bu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),G_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),wu=t=>{const e=G_(t);return e.charAt(0).toUpperCase()+e.slice(1)},q_=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var K_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
26
+ */var z_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
27
27
  * @license lucide-preact v0.515.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Y_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Je("svg",{...K_,width:String(e),height:e,stroke:t,"stroke-width":n?Number(i)*24/Number(e):i,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Je(l,c)),...ht(s)]);/**
31
+ */const K_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Ze("svg",{...z_,width:String(e),height:e,stroke:t,"stroke-width":n?Number(i)*24/Number(e):i,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Ze(l,c)),...ft(s)]);/**
32
32
  * @license lucide-preact v0.515.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const je=(t,e)=>{const i=({class:n="",children:s,...o})=>Je(Y_,{...o,iconNode:e,class:z_(`lucide-${vu(_u(t))}`,`lucide-${vu(t)}`,n)},s);return i.displayName=_u(t),i};/**
36
+ */const He=(t,e)=>{const i=({class:n="",children:s,...o})=>Ze(K_,{...o,iconNode:e,class:q_(`lucide-${bu(wu(t))}`,`lucide-${bu(t)}`,n)},s);return i.displayName=wu(t),i};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const yu=je("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
41
+ */const Su=He("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const X_=je("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
46
+ */const Y_=He("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const bu=je("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
51
+ */const Cu=He("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
52
52
  * @license lucide-preact v0.515.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const J_=je("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
56
+ */const X_=He("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
57
57
  * @license lucide-preact v0.515.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const Z_=je("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const J_=He("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
62
62
  * @license lucide-preact v0.515.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const Q_=je("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
66
+ */const Z_=He("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
67
67
  * @license lucide-preact v0.515.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const ey=je("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
71
+ */const Q_=He("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
72
72
  * @license lucide-preact v0.515.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const ty=je("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
76
+ */const ey=He("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
77
77
  * @license lucide-preact v0.515.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const iy=je("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
81
+ */const ty=He("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
82
82
  * @license lucide-preact v0.515.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
85
85
  * See the LICENSE file in the root directory of this source tree.
86
- */const ny=je("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
86
+ */const iy=He("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
87
87
  * @license lucide-preact v0.515.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const sy=je("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
91
+ */const ny=He("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
92
92
  * @license lucide-preact v0.515.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const oy=je("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
96
+ */const sy=He("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const ry=je("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
101
+ */const oy=He("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const ay=je("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
106
+ */const ry=He("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
107
107
  * @license lucide-preact v0.515.0 - ISC
108
108
  *
109
109
  * This source code is licensed under the ISC license.
110
110
  * See the LICENSE file in the root directory of this source tree.
111
- */const mr=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),wu=Dn(!1),ly=()=>Ja(wu),Lt=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:At("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Su=({call:t,chatMode:e})=>{const[i,n]=ly(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(Lt,{tooltip:i?"Unmute":"Mute",onClick:s,className:At(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(Q_,{className:"w-5 h-5 text-black dark:text-white"}):D(ey,{className:"w-5 h-5 text-black dark:text-white"})}),D(Lt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(iy,{className:"w-4 h-4 text-black dark:text-white"})})]})},Cu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Si.div,{layoutId:dn,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:[!i&&D(pu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(qd,{stream:t.remoteStream,chatMode:i}),D(Gd,{size:"small"}),D(Su,{call:t,chatMode:i}),D(mu,{debug:n})]});function cy(){const[t,e]=Ae(!1),i=Qt();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(bu,{className:"text-black dark:text-white"})}),t&&D("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:[D(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(bu,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(ry,{className:"w-4 h-4"})]}),i.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(ay,{className:"w-4 h-4"})]}),i.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D(J_,{className:"w-4 h-4"})]})]})]})]})}function dy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ss={exports:{}},uy=ss.exports,Tu;function hy(){return Tu||(Tu=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(uy,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var w=s[b];this[w]=b<v?e:this.methodFactory(w,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=o[b];return w||(w=o[b]=new p(b,r.methodFactory)),w};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(ss)),ss.exports}var fy=hy();const py=dy(fy),gy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),my="[ai-agent-widget]",re=py.getLogger("telnyx-ai-agent-widget"),vy=re.methodFactory;re.methodFactory=(t,e,i)=>{const n=vy(t,e,i);return function(...s){n(gy(),my,...s)}},re.setLevel("info");function _y({onCapture:t,onClose:e}){const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae(null),[a,l]=Ae(!0);xe(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,i.current&&(i.current.srcObject=h,l(!1))}catch(h){re.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,p=h.getContext("2d");if(!p)return;h.width=d.videoWidth,h.height=d.videoHeight,p.drawImage(d,0,0,h.width,h.height);const _=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("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:[D("div",{className:"absolute top-2 right-2 z-10",children:D(Lt,{tooltip:"Close",onClick:u,children:D(mr,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(ut,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:At("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("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:[D(yu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const vr=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],yy=["audio","lang","mark","p","s","sub","w"],Eu=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ku(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function Iu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Ru=vr.filter(t=>!yy.includes(t)),by=ku(vr,"gi"),Au=ku(Ru,"gi"),wy=Iu(vr,"i"),Sy=Iu(Ru,"i"),Cy=new RegExp(`${Au.source}|${Eu.source}`,"i");function Ty(t){const e=Cy.test(t),i=e?by:Au,n=e?wy:Sy;return t.replace(i,"").replace(n,"").replace(Eu,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function Ey({item:t,containerRef:e}){const i=ue(null),n=t.role==="assistant"?Ty(t.content):t.content;return xe(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:At("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:At("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),n&&D("p",{className:At("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const ky=({transcript:t,call:e})=>{const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=cr();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{if(c.length===0)return;const T=t.filter(E=>E.role==="user"&&!E.id.startsWith("optimistic-"));if(T.length>0){const E=T[T.length-1];u(g=>g.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,g)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=g,m.readAsDataURL(T)}),p=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),g=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:E,preview:g};r(f=>[...f,m])}catch(E){re.error("Error processing image:",E)}},_=T=>{r(E=>{const g=E.find(m=>m.id===T);return g&&URL.revokeObjectURL(g.preview),E.filter(m=>m.id!==T)})},v=T=>{const E=T.target,g=E.files;g&&g.length>0&&(Array.from(g).forEach(p),E.value="")},b=T=>{var g;const E=(g=T.clipboardData)==null?void 0:g.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&p(f)}})},w=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const g=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});p(g)}).catch(E=>{re.error("Error processing camera capture:",E)})},L=async()=>{var g;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){const m=((g=i.current)==null?void 0:g.value)||"",f=new Date,S={id:`optimistic-${f.getTime()}`,role:"user",content:m,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),E&&d("processing_image"),e.sendConversationMessage(m,o.map(I=>I.base64)),i.current&&(i.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),L())},O=[...t,...c];return D("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:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((T,E)=>D(Ey,{item:T,containerRef:s},T.id+E))}),o.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>D("div",{className:"relative",children:[D("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>_(T.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:D(mr,{className:"w-3 h-3"})})]},T.id))}),D("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:[D("input",{ref:i,type:"text",onKeyDown:R,onPaste:b,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),D("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),D(Lt,{tooltip:"Attach image",onClick:w,children:D(ty,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Take photo",onClick:C,children:D(yu,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Send",children:D(sy,{onClick:L,className:"text-[#969696] w-4 h-4"})})]}),a&&D(_y,{onCapture:k,onClose:()=>l(!1)})]})};function Iy({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(cy,{}),D(Lt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(mr,{className:"text-black dark:text-white"})})]})}const Ry=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Bg,{children:D(Si.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:[D("div",{className:"p-4 text-center",children:[D(Iy,{onCollapse:e}),!n&&D(pu,{className:"h-[144px]",stream:t.remoteStream}),D(Gd,{size:"large",className:"mb-4"}),D(Su,{call:t,chatMode:n}),D(mu,{className:"mt-2",debug:s})]}),D(qd,{stream:t.remoteStream,chatMode:n}),D(ky,{call:t,transcript:i})]})});function xu(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function B(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var Lu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Ay=new Uint8Array(16);function xy(){if(!Lu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lu(Ay)}for(var Du=[],os=0;os<256;++os)Du[os]=(os+256).toString(16).substr(1);function ki(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||xy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,a){var l=0,c=Du;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 Ly={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},Dy={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:Oy,SDP_CREATE_ANSWER_FAILED:My,SDP_SET_LOCAL_DESCRIPTION_FAILED:Py,SDP_SET_REMOTE_DESCRIPTION_FAILED:Ou,SDP_SEND_FAILED:_r,MEDIA_MICROPHONE_PERMISSION_DENIED:Ny,MEDIA_DEVICE_NOT_FOUND:Fy,MEDIA_GET_USER_MEDIA_FAILED:Mu,HOLD_FAILED:Vy,INVALID_CALL_PARAMETERS:By,BYE_SEND_FAILED:Uy,SUBSCRIBE_FAILED:$y,PEER_CLOSED_DURING_INIT:yr,WEBSOCKET_CONNECTION_FAILED:jy,WEBSOCKET_ERROR:Wy,RECONNECTION_EXHAUSTED:br,GATEWAY_FAILED:Hy,LOGIN_FAILED:Pu,INVALID_CREDENTIALS:Gy,AUTHENTICATION_REQUIRED:qy,ICE_RESTART_FAILED:zy,NETWORK_OFFLINE:Ky,SESSION_NOT_REATTACHED:Nu,UNEXPECTED_ERROR:Fu}=Ly,{HIGH_RTT:Yy,HIGH_JITTER:Xy,HIGH_PACKET_LOSS:Jy,LOW_MOS:Vu,LOW_LOCAL_AUDIO:rs,LOW_INBOUND_AUDIO:Bu,LOW_BYTES_RECEIVED:Uu,LOW_BYTES_SENT:$u,RECORDING_UNAVAILABLE:Zy,RECORDING_BUFFER_OVERFLOW:Qy,ICE_CONNECTIVITY_LOST:e0,ICE_GATHERING_TIMEOUT:t0,ICE_GATHERING_EMPTY:i0,PEER_CONNECTION_FAILED:n0,ONLY_HOST_ICE_CANDIDATES:s0,ANSWER_WHILE_PEER_ACTIVE:o0,ICE_CANDIDATE_PAIR_CHANGED:r0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:a0,MULTIPLE_ACTIVE_CALLS_DETECTED:l0,DUPLICATE_INBOUND_ANSWER:c0,SHARED_REMOTE_ELEMENT_OVERWRITE:d0,TOKEN_EXPIRING_SOON:u0,UNKNOWN_REATTACHED_SESSION:h0,SIGNALING_RECOVERY_REQUIRED:f0,MEDIA_RECOVERY_REQUIRED:p0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:g0}=Dy,m0=/^a=candidate:.+typ (srflx|prflx|relay)/m,ju="wss://rtc.telnyx.com",Wu={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Hu={urls:"stun:stun.l.google.com:19302"},v0={urls:"stun:stun.telnyx.com:3478"},_0={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},y0={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},b0={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},w0=[v0,Hu,_0,y0,b0],S0=[{urls:"stun:stundev.telnyx.com:3478"},Hu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var N;(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.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(N||(N={}));const C0={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},T0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function Ne(t,e){const i=T0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Bt extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,Bt.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}}function Ii(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Ny;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Fy}return Mu}function se(t,e,i,n){const s=C0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Bt({code:t,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:n??s.fatal})}class E0 extends Error{constructor(e,i,n=""){super(`Signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=i,this.method=n}}class wr extends Error{constructor(e,i,n){super(`Stale request cancelled (id=${e}, gen=${i}, current=${n})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=i,this.currentGeneration=n}}var k0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gu(t,e){return t(e={exports:{}},e.exports),e.exports}var I0=Gu(function(t){var e,i;e=k0,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,w){var C=b[w];if(typeof C.bind=="function")return C.bind(b);try{return Function.prototype.bind.call(C,b)}catch{return function(){return Function.prototype.apply.apply(C,[b,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(b,w){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,w)}this.log=this.debug}function u(b,w,C){return function(){typeof console!==s&&(c.call(this,w,C),this[b].apply(this,arguments))}}function d(b,w,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,w,C){var k,L=this;w=w??"WARN";var R="loglevel";function O(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var g=window.document.cookie,m=g.indexOf(encodeURIComponent(R)+"=");m!==-1&&(E=/^([^;]+)/.exec(g.slice(m))[1])}catch{}return L.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=void 0),L.name=b,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=C||d,L.getLevel=function(){return k},L.setLevel=function(E,g){if(typeof E=="string"&&L.levels[E.toUpperCase()]!==void 0&&(E=L.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=L.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,g!==!1&&function(m){var f=(r[m]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=f)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+f+";"}catch{}}}(E),c.call(L,E,b),typeof console===s&&E<L.levels.SILENT)return"No console available for logging"},L.setDefaultLevel=function(E){w=E,O()||L.setLevel(E,!1)},L.resetLevel=function(){L.setLevel(w,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},L.enableAll=function(E){L.setLevel(L.levels.TRACE,E)},L.disableAll=function(E){L.setLevel(L.levels.SILENT,E)};var T=O();T==null&&(T=w),L.setLevel(T,!1)}var p=new h,_={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[b];return w||(w=_[b]=new h(b,p.getLevel(),p.methodFactory)),w};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return _},p.default=p,p},t.exports?t.exports=i():e.log=i()});const qu={debug:0,info:1,warn:2,error:3};class R0{constructor(e={}){var i,n,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(i=e.enabled)!==null&&i!==void 0&&i,level:(n=e.level)!==null&&n!==void 0?n:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,i,n){if(!this.isCapturing||!this.options.enabled||qu[e]<qu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:i},n&&Object.keys(n).length>0?{context:n}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let zu=null;const y=I0.getLogger("telnyx"),as={trace:0,debug:1,info:2,warn:3,error:4};let Ku=as.info;function Yu(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const A0=y.methodFactory;y.methodFactory=(t,e,i)=>{const n=A0(t,e,i);return function(...s){if(as[t]>=Ku){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=zu;if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Yu(a[0]):{args:a.map(Yu)}),o.addEntry(t,l,c)}}},y.setLevel("debug",!1);const ls=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{y.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Xu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ri=t=>t instanceof Function||typeof t=="function",fn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,x0=/^(ws|wss):\/\//,Ju=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Ju(a,r):{result:s}},cs=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),pn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Sr=t=>{var e,i,n,s,o,r;let a="",l="";return!((i=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||i===void 0)&&i.state&&(a=(s=(n=t==null?void 0:t.result)===null||n===void 0?void 0:n.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 Zu({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?L0(n,t):n,i=s}),resolve:e,reject:i}}const L0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Cr="telnyx-voice-sdk-id",ds="telnyx-voice-sdk-session-id",us="telnyx-voice-sdk-session-id-stored-at",Tr="telnyx-voice-sdk-active-calls",D0=9e4;function Qu(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(us));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=D0}function gn(){return sessionStorage.getItem(Cr)}function Er(t,e=Date.now()){sessionStorage.setItem(ds,t),sessionStorage.setItem(us,String(e))}function eh(){sessionStorage.removeItem(Cr),sessionStorage.removeItem(ds),sessionStorage.removeItem(us)}function ei(){(function(t){try{sessionStorage.removeItem(t)}catch(e){y.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Tr)}function th(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return y.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Tr);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return y.debug("Active-calls recovery marker payload was malformed — discarded."),ei(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(y.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),ei(),null):i.calls.length===0?(y.debug("Active-calls recovery marker had no call records — discarded."),ei(),null):i}catch(i){return y.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),ei(),null}}function ih(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void ei();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){y.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Tr,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Fe,vt,Q;(function(t){t.Offer="offer",t.Answer="answer"})(Fe||(Fe={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(vt||(vt={})),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"}(Q||(Q={}));const nt={generic:"event",[Q.Display]:"participantData",[Q.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},O0={invalidCredentialsOptions:"InvalidCredentialsOptions"},nh=24e4,sh=8e6,M0={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!0};var G,kr,Ke,_t,Oe,Ai;(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"})(G||(G={})),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"}(Ke||(Ke={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(_t||(_t={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Oe||(Oe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ai||(Ai={}));const xi="GLOBAL",qe={},mn=(t,e)=>`${t}|${e}`,oh=(t,e=xi)=>mn(t,e)in qe,Ut=(t,e,i=xi)=>{const n=mn(t,i);n in qe||(qe[n]=[]),qe[n].push(e)},rh=(t,e,i=xi)=>{const n=function(s){yt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},yt=(t,e,i=xi)=>{if(!oh(t,i))return!1;const n=mn(t,i);if(Ri(e))for(let s=qe[n].length-1;s>=0;s--){const o=qe[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&qe[n].splice(s,1)}else qe[n]=[];return qe[n].length===0&&delete qe[n],!0},V=(t,e,i=xi,n=!0)=>{const s=n&&i!==xi;if(!oh(t,i))return s&&V(t,e),!1;const o=mn(t,i),r=qe[o].length;if(!r)return s&&V(t,e),!1;for(let a=r-1;a>=0;a--)qe[o][a](e);return s&&V(t,e),!0},Ir=t=>{const e=mn(t,"");Object.keys(qe).filter(i=>i.indexOf(e)===0).forEach(i=>delete qe[i])};let P0=typeof WebSocket<"u"?WebSocket:null;const N0=0,F0=1,V0=2,ah=3;class hs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=ju,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:i,env:n,region:s,useCanaryRtcServer:o}=e.options;y.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":ju),i&&(this._host=(r=>`${x0.test(r)?"":"wss://"}${r}`)(i)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===F0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===N0}get closing(){return!!this._wsClient&&this._wsClient.readyState===V0}get closed(){return!!this._wsClient&&this._wsClient.readyState===ah}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){y.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=gn();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&e.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),y.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const n=this.socketGeneration;this._wsClient=new P0(e.toString()),this.socketGeneration+=1,y.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:n}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(n){y.error("WebSocket connection failed:",n);const s=se(jy,n);V(N.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var i;(i=this._wsClient)===null||i===void 0||i.send(e)}send(e,i){var n;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=p=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),u)return;const{result:_,error:v}=Ju(p);return v?c(v):l(_)};rh(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),i&&i>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),yt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return y.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new wr(s.id,o,this.socketGeneration));c(new E0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return y.debug(`SEND:
111
+ */const mr=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Tu=Dn(!1),ay=()=>el(Tu),Lt=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:At("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Eu=({call:t,chatMode:e})=>{const[i,n]=ay(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(Lt,{tooltip:i?"Unmute":"Mute",onClick:s,className:At(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(Z_,{className:"w-5 h-5 text-black dark:text-white"}):D(Q_,{className:"w-5 h-5 text-black dark:text-white"})}),D(Lt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(ty,{className:"w-4 h-4 text-black dark:text-white"})})]})},ku=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Si.div,{layoutId:dn,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:[!i&&D(vu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Yd,{stream:t.remoteStream,chatMode:i}),D(Kd,{size:"small"}),D(Eu,{call:t,chatMode:i}),D(yu,{debug:n})]});function ly(){const[t,e]=Ae(!1),i=Qt();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Cu,{className:"text-black dark:text-white"})}),t&&D("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:[D(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Cu,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(oy,{className:"w-4 h-4"})]}),i.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(ry,{className:"w-4 h-4"})]}),i.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D(X_,{className:"w-4 h-4"})]})]})]})]})}function cy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ss={exports:{}},dy=ss.exports,Iu;function uy(){return Iu||(Iu=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(dy,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var w=s[b];this[w]=b<v?e:this.methodFactory(w,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=o[b];return w||(w=o[b]=new p(b,r.methodFactory)),w};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(ss)),ss.exports}var hy=uy();const fy=cy(hy),py=()=>new Date().toISOString().replace("T"," ").replace("Z",""),gy="[ai-agent-widget]",oe=fy.getLogger("telnyx-ai-agent-widget"),my=oe.methodFactory;oe.methodFactory=(t,e,i)=>{const n=my(t,e,i);return function(...s){n(py(),gy,...s)}},oe.setLevel("info");function vy({onCapture:t,onClose:e}){const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae(null),[a,l]=Ae(!0);xe(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,i.current&&(i.current.srcObject=h,l(!1))}catch(h){oe.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,p=h.getContext("2d");if(!p)return;h.width=d.videoWidth,h.height=d.videoHeight,p.drawImage(d,0,0,h.width,h.height);const _=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("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:[D("div",{className:"absolute top-2 right-2 z-10",children:D(Lt,{tooltip:"Close",onClick:u,children:D(mr,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(ht,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:At("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("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:[D(Su,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const vr=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],_y=["audio","lang","mark","p","s","sub","w"],Ru=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function Au(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function xu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Lu=vr.filter(t=>!_y.includes(t)),yy=Au(vr,"gi"),Du=Au(Lu,"gi"),by=xu(vr,"i"),wy=xu(Lu,"i"),Sy=new RegExp(`${Du.source}|${Ru.source}`,"i");function Cy(t){const e=Sy.test(t),i=e?yy:Du,n=e?by:wy;return t.replace(i,"").replace(n,"").replace(Ru,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function Ty({item:t,containerRef:e}){const i=ue(null),n=t.role==="assistant"?Cy(t.content):t.content;return xe(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:At("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:At("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),n&&D("p",{className:At("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const Ey=({transcript:t,call:e})=>{const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=cr();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{if(c.length===0)return;const T=t.filter(E=>E.role==="user"&&!E.id.startsWith("optimistic-"));if(T.length>0){const E=T[T.length-1];u(g=>g.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,g)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=g,m.readAsDataURL(T)}),p=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),g=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:E,preview:g};r(f=>[...f,m])}catch(E){oe.error("Error processing image:",E)}},_=T=>{r(E=>{const g=E.find(m=>m.id===T);return g&&URL.revokeObjectURL(g.preview),E.filter(m=>m.id!==T)})},v=T=>{const E=T.target,g=E.files;g&&g.length>0&&(Array.from(g).forEach(p),E.value="")},b=T=>{var g;const E=(g=T.clipboardData)==null?void 0:g.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&p(f)}})},w=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const g=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});p(g)}).catch(E=>{oe.error("Error processing camera capture:",E)})},L=async()=>{var g;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){const m=((g=i.current)==null?void 0:g.value)||"",f=new Date,S={id:`optimistic-${f.getTime()}`,role:"user",content:m,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),E&&d("processing_image"),e.sendConversationMessage(m,o.map(I=>I.base64)),i.current&&(i.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),L())},O=[...t,...c];return D("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:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((T,E)=>D(Ty,{item:T,containerRef:s},T.id+E))}),o.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>D("div",{className:"relative",children:[D("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>_(T.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:D(mr,{className:"w-3 h-3"})})]},T.id))}),D("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:[D("input",{ref:i,type:"text",onKeyDown:R,onPaste:b,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),D("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),D(Lt,{tooltip:"Attach image",onClick:w,children:D(ey,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Take photo",onClick:C,children:D(Su,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Send",children:D(ny,{onClick:L,className:"text-[#969696] w-4 h-4"})})]}),a&&D(vy,{onCapture:k,onClose:()=>l(!1)})]})};function ky({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(ly,{}),D(Lt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(mr,{className:"text-black dark:text-white"})})]})}const Iy=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Bg,{children:D(Si.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:[D("div",{className:"p-4 text-center",children:[D(ky,{onCollapse:e}),!n&&D(vu,{className:"h-[144px]",stream:t.remoteStream}),D(Kd,{size:"large",className:"mb-4"}),D(Eu,{call:t,chatMode:n}),D(yu,{className:"mt-2",debug:s})]}),D(Yd,{stream:t.remoteStream,chatMode:n}),D(Ey,{call:t,transcript:i})]})});function Ou(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function V(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var Mu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Ry=new Uint8Array(16);function Ay(){if(!Mu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mu(Ry)}for(var Pu=[],os=0;os<256;++os)Pu[os]=(os+256).toString(16).substr(1);function ki(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||Ay)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,a){var l=0,c=Pu;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 xy={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},Ly={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:Dy,SDP_CREATE_ANSWER_FAILED:Oy,SDP_SET_LOCAL_DESCRIPTION_FAILED:My,SDP_SET_REMOTE_DESCRIPTION_FAILED:Nu,SDP_SEND_FAILED:_r,MEDIA_MICROPHONE_PERMISSION_DENIED:Py,MEDIA_DEVICE_NOT_FOUND:Ny,MEDIA_GET_USER_MEDIA_FAILED:Fu,HOLD_FAILED:Fy,INVALID_CALL_PARAMETERS:By,BYE_SEND_FAILED:Vy,SUBSCRIBE_FAILED:Uy,PEER_CLOSED_DURING_INIT:yr,WEBSOCKET_CONNECTION_FAILED:$y,WEBSOCKET_ERROR:jy,RECONNECTION_EXHAUSTED:br,GATEWAY_FAILED:Hy,LOGIN_FAILED:Bu,INVALID_CREDENTIALS:Wy,AUTHENTICATION_REQUIRED:Gy,ICE_RESTART_FAILED:qy,NETWORK_OFFLINE:zy,SESSION_NOT_REATTACHED:Vu,UNEXPECTED_ERROR:Uu}=xy,{HIGH_RTT:Ky,HIGH_JITTER:Yy,HIGH_PACKET_LOSS:Xy,LOW_MOS:$u,LOW_LOCAL_AUDIO:rs,LOW_INBOUND_AUDIO:as,LOW_BYTES_RECEIVED:wr,LOW_BYTES_SENT:ju,RECORDING_UNAVAILABLE:Jy,RECORDING_BUFFER_OVERFLOW:Zy,ICE_CONNECTIVITY_LOST:Qy,ICE_GATHERING_TIMEOUT:e0,ICE_GATHERING_EMPTY:t0,PEER_CONNECTION_FAILED:i0,ONLY_HOST_ICE_CANDIDATES:n0,ANSWER_WHILE_PEER_ACTIVE:s0,ICE_CANDIDATE_PAIR_CHANGED:o0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:r0,MULTIPLE_ACTIVE_CALLS_DETECTED:a0,DUPLICATE_INBOUND_ANSWER:l0,SHARED_REMOTE_ELEMENT_OVERWRITE:c0,TOKEN_EXPIRING_SOON:d0,UNKNOWN_REATTACHED_SESSION:u0,SIGNALING_RECOVERY_REQUIRED:h0,MEDIA_RECOVERY_REQUIRED:f0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:p0}=Ly,g0=/^a=candidate:.+typ (srflx|prflx|relay)/m,Hu="wss://rtc.telnyx.com",Wu={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Gu={urls:"stun:stun.l.google.com:19302"},m0={urls:"stun:stun.telnyx.com:3478"},v0={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},_0={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},y0={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},b0={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},w0=[m0,Gu,v0,_0,y0,b0],S0=[{urls:"stun:stundev.telnyx.com:3478"},Gu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var P;(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.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(P||(P={}));const C0={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},T0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function Ne(t,e){const i=T0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Vt extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,Vt.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}}function Ii(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Py;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Ny}return Fu}function ne(t,e,i,n){const s=C0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Vt({code:t,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:n??s.fatal})}class E0 extends Error{constructor(e,i,n=""){super(`Signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=i,this.method=n}}class Sr extends Error{constructor(e,i,n){super(`Stale request cancelled (id=${e}, gen=${i}, current=${n})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=i,this.currentGeneration=n}}var k0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qu(t,e){return t(e={exports:{}},e.exports),e.exports}var I0=qu(function(t){var e,i;e=k0,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,w){var C=b[w];if(typeof C.bind=="function")return C.bind(b);try{return Function.prototype.bind.call(C,b)}catch{return function(){return Function.prototype.apply.apply(C,[b,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(b,w){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,w)}this.log=this.debug}function u(b,w,C){return function(){typeof console!==s&&(c.call(this,w,C),this[b].apply(this,arguments))}}function d(b,w,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,w,C){var k,L=this;w=w??"WARN";var R="loglevel";function O(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var g=window.document.cookie,m=g.indexOf(encodeURIComponent(R)+"=");m!==-1&&(E=/^([^;]+)/.exec(g.slice(m))[1])}catch{}return L.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=void 0),L.name=b,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=C||d,L.getLevel=function(){return k},L.setLevel=function(E,g){if(typeof E=="string"&&L.levels[E.toUpperCase()]!==void 0&&(E=L.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=L.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,g!==!1&&function(m){var f=(r[m]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=f)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+f+";"}catch{}}}(E),c.call(L,E,b),typeof console===s&&E<L.levels.SILENT)return"No console available for logging"},L.setDefaultLevel=function(E){w=E,O()||L.setLevel(E,!1)},L.resetLevel=function(){L.setLevel(w,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},L.enableAll=function(E){L.setLevel(L.levels.TRACE,E)},L.disableAll=function(E){L.setLevel(L.levels.SILENT,E)};var T=O();T==null&&(T=w),L.setLevel(T,!1)}var p=new h,_={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[b];return w||(w=_[b]=new h(b,p.getLevel(),p.methodFactory)),w};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return _},p.default=p,p},t.exports?t.exports=i():e.log=i()});const zu={debug:0,info:1,warn:2,error:3};class R0{constructor(e={}){var i,n,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(i=e.enabled)!==null&&i!==void 0&&i,level:(n=e.level)!==null&&n!==void 0?n:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,i,n){if(!this.isCapturing||!this.options.enabled||zu[e]<zu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:i},n&&Object.keys(n).length>0?{context:n}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Ku=null;const y=I0.getLogger("telnyx"),ls={trace:0,debug:1,info:2,warn:3,error:4};let Yu=ls.info;function Xu(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const A0=y.methodFactory;y.methodFactory=(t,e,i)=>{const n=A0(t,e,i);return function(...s){if(ls[t]>=Yu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Ku;if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Xu(a[0]):{args:a.map(Xu)}),o.addEntry(t,l,c)}}},y.setLevel("debug",!1);const cs=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{y.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Ju=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ri=t=>t instanceof Function||typeof t=="function",fn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,x0=/^(ws|wss):\/\//,Zu=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Zu(a,r):{result:s}},ds=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),pn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Cr=t=>{var e,i,n,s,o,r;let a="",l="";return!((i=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||i===void 0)&&i.state&&(a=(s=(n=t==null?void 0:t.result)===null||n===void 0?void 0:n.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 Qu({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?L0(n,t):n,i=s}),resolve:e,reject:i}}const L0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Tr="telnyx-voice-sdk-id",us="telnyx-voice-sdk-session-id",hs="telnyx-voice-sdk-session-id-stored-at",Er="telnyx-voice-sdk-active-calls",D0=9e4;function eh(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(hs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=D0}function gn(){return sessionStorage.getItem(Tr)}function kr(t,e=Date.now()){sessionStorage.setItem(us,t),sessionStorage.setItem(hs,String(e))}function th(){sessionStorage.removeItem(Tr),sessionStorage.removeItem(us),sessionStorage.removeItem(hs)}function ei(){(function(t){try{sessionStorage.removeItem(t)}catch(e){y.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Er)}function ih(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return y.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Er);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return y.debug("Active-calls recovery marker payload was malformed — discarded."),ei(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(y.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),ei(),null):i.calls.length===0?(y.debug("Active-calls recovery marker had no call records — discarded."),ei(),null):i}catch(i){return y.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),ei(),null}}function nh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void ei();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){y.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Er,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Fe,_t,Z;(function(t){t.Offer="offer",t.Answer="answer"})(Fe||(Fe={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(_t||(_t={})),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"}(Z||(Z={}));const st={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},O0={invalidCredentialsOptions:"InvalidCredentialsOptions"},sh=8e6,M0={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!0};var W,Ir,Ye,yt,Oe,Ai;(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"})(W||(W={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Ir||(Ir={})),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"}(Ye||(Ye={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(yt||(yt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Oe||(Oe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ai||(Ai={}));const xi="GLOBAL",ze={},mn=(t,e)=>`${t}|${e}`,oh=(t,e=xi)=>mn(t,e)in ze,Ut=(t,e,i=xi)=>{const n=mn(t,i);n in ze||(ze[n]=[]),ze[n].push(e)},rh=(t,e,i=xi)=>{const n=function(s){bt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},bt=(t,e,i=xi)=>{if(!oh(t,i))return!1;const n=mn(t,i);if(Ri(e))for(let s=ze[n].length-1;s>=0;s--){const o=ze[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&ze[n].splice(s,1)}else ze[n]=[];return ze[n].length===0&&delete ze[n],!0},B=(t,e,i=xi,n=!0)=>{const s=n&&i!==xi;if(!oh(t,i))return s&&B(t,e),!1;const o=mn(t,i),r=ze[o].length;if(!r)return s&&B(t,e),!1;for(let a=r-1;a>=0;a--)ze[o][a](e);return s&&B(t,e),!0},Rr=t=>{const e=mn(t,"");Object.keys(ze).filter(i=>i.indexOf(e)===0).forEach(i=>delete ze[i])};let P0=typeof WebSocket<"u"?WebSocket:null;const N0=0,F0=1,B0=2,ah=3;class fs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Hu,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:i,env:n,region:s,useCanaryRtcServer:o}=e.options;y.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Hu),i&&(this._host=(r=>`${x0.test(r)?"":"wss://"}${r}`)(i)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===F0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===N0}get closing(){return!!this._wsClient&&this._wsClient.readyState===B0}get closed(){return!!this._wsClient&&this._wsClient.readyState===ah}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){y.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=gn();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&e.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),y.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const n=this.socketGeneration;this._wsClient=new P0(e.toString()),this.socketGeneration+=1,y.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:n}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(n){y.error("WebSocket connection failed:",n);const s=ne($y,n);B(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var i;(i=this._wsClient)===null||i===void 0||i.send(e)}send(e,i){var n;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=p=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),u)return;const{result:_,error:v}=Zu(p);return v?c(v):l(_)};rh(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),i&&i>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),bt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return y.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Sr(s.id,o,this.socketGeneration));c(new E0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return y.debug(`SEND:
112
112
  `,JSON.stringify(s,null,2),`
113
- `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(y.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ri(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const i=this.socketGeneration;e.onopen=n=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),V(N.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.debug("WebSocket onclose",{code:n==null?void 0:n.code,reason:n==null?void 0:n.reason,wasClean:n==null?void 0:n.wasClean,socketGeneration:i,sessionId:this.session.sessionid}),V(N.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=se(Wy);return V(N.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),V(N.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),V(N.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Xu(n.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(Cr,a)),this._unsetTimer(r.id),y.debug(`RECV:
113
+ `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(y.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ri(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const i=this.socketGeneration;e.onopen=n=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),B(P.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.debug("WebSocket onclose",{code:n==null?void 0:n.code,reason:n==null?void 0:n.reason,wasClean:n==null?void 0:n.wasClean,socketGeneration:i,sessionId:this.session.sessionid}),B(P.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ne(jy);return B(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),B(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),B(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Ju(n.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(Tr,a)),this._unsetTimer(r.id),y.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Oe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!V(r.id,r)){const l=Sr(r);V(N.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==ah?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),V(N.SocketClose,{code:Wu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{yt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new wr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_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)),V(N.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}hs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const lh={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 Ue extends Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=xu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in lh)n&&i.hasOwnProperty(n)&&(i[lh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class ch extends Ue{constructor(e){super(),this.method=Q.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class B0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>B(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Sr(i))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const i=new ch(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Zu({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Zu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Rr extends Ue{constructor(e){super(),this.method=Q.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Di.isCriticalMethod(n)?(y.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){y.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=se(Ky);V(N.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return y.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(y.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Rr(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(y.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(f0);V(N.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(p0);V(N.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Q.Modify,Q.Bye,Q.Ping]);var dh="2.27.4",Ar=dh;class U0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Ar,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class $0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class uh extends Ue{toString(){return Q.Invite}}class hh extends Ue{toString(){return Q.Answer}}class fh extends Ue{toString(){return Q.Attach}}class j0 extends Ue{toString(){return Q.Bye}}class W0 extends Ue{toString(){return Q.Candidate}}class H0 extends Ue{toString(){return Q.EndOfCandidates}}class fs extends Ue{toString(){return Q.Modify}}class ph extends Ue{toString(){return Q.Info}}class G0 extends Ue{toString(){return Q.Broadcast}}class q0 extends Ue{toString(){return Q.Subscribe}}class z0 extends Ue{toString(){return Q.Unsubscribe}}class K0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Ar,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class ti{constructor(e){if(this.options=e,this.uuid=ki(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ku=(n=as[i])!==null&&n!==void 0?n:as.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._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new hs(this),this.registerAgent=new B0(this)}get __logger(){return y}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return y.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?hs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>B(this,void 0,void 0,function*(){if(s instanceof wr)throw y.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=se(qy,s,void 0,!0);V(N.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return B(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return cs(this.options)||pn(this.options)}broadcast(e){}disconnect(){return B(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),y.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return yt(e,i,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new hs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=se(Pu,e);V(N.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){eh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(u0);V(N.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return B(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),cs(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=se(Gy,void 0,s);return void V(N.Error,{error:o,type:O0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){return B(this,void 0,void 0,function*(){let s;const o=!!gn(),r=o&&(this.sessionid&&Qu()?this.sessionid:function(l=Date.now()){const c=sessionStorage.getItem(ds);return c?Qu(l)?c:(sessionStorage.removeItem(ds),sessionStorage.removeItem(us),null):null}())||"";s=e==="login"?new U0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,r,this.options.userVariables,o):new K0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:r,userVariables:this.options.userVariables,reconnection:o});const a=yield this.execute(s).catch(l=>{this._handleLoginError(l),n&&n(l)});a&&(this.sessionid=a.sessid,this.sessionid&&Er(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return B(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){y.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(Wu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Ir(this.relayProtocol);for(const l in this.subscriptions)Ir(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Er(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=se(br);return void V(N.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(g0);V(N.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],yt(e,null,i)):(delete this.subscriptions[e],Ir(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(N.SocketOpen,this._onSocketOpen),this.on(N.SocketClose,this.onNetworkClose),this.on(N.SocketError,this.onNetworkClose),this.on(N.SocketMessage,this._onSocketMessage),this.on(N.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(N.SocketOpen,this._onSocketOpen),this.off(N.SocketClose,this.onNetworkClose),this.off(N.SocketError,this.onNetworkClose),this.off(N.SocketMessage,this._onSocketMessage),this.off(N.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),y.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Rr(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([G.Early,G.Active,G.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){y.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return y.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Ut(e,i)}static off(e){yt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const ps=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,gs=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(d0);V(N.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},gh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},mh=(t,e)=>B(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),Y0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(Y0),t=null},ms=t=>B(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield ps(t)}catch(n){if(y.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){y.warn("Device not found or not readable, falling back to default device");try{return yield ps(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===_t.AudioIn||s===_t.AudioOut,video:!s||s===_t.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),vh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],vs=(t,e,i)=>B(void 0,void 0,void 0,function*(){const n=yield yn(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),X0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},xr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,_h=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>xr(a)):[]},Lr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Dr(t);return i.includes(e)||n.includes(e)},Dr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Or=t=>{Oi(t,"audio",!0)},_s=t=>{Oi(t,"audio",!1)};function J0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!ms}}catch(t){return t.message}}var Ee;function yh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function bh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function wh(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"})(Ee||(Ee={}));const Sh=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class Z0 extends Li{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class Q0 extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new R0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,zu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return B(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),y.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return y.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],_=new Date;this._lastIntermediateFlushTime=_;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(_.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:_.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return y.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return B(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return B(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return B(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;y.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),_=(o||r)&&p.length<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,_,v,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((_=(p=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||g>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(le.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return B(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(g=>{switch(g.type){case"outbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(r=g);break;case"inbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(a=g);break;case"media-playout":g.kind==="audio"&&(l=g);break;case"remote-inbound-rtp":g.kind==="audio"&&(c=g);break;case"remote-outbound-rtp":g.kind==="audio"&&(u=g);break;case"candidate-pair":(g.nominated||g.state==="succeeded")&&h.push(g);break;case"transport":p=g}});const _=p==null?void 0:p.selectedCandidatePairId,v=_?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,_):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),w=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:_?h.find(g=>g.id===_)||h[h.length-1]||null:h[h.length-1]||null,r){const g=this._getOutboundAudioLevel(s,r);if(g!==null&&this.intervalAudioLevels.outbound.push(g),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const g=this._getInboundAudioLevel(s,a);if(g!==null&&this.intervalAudioLevels.inbound.push(g),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(r0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void y.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Yy,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Xy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Jy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Vu,O<le.THRESHOLD_MOS)}else this._trackBreach(Vu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const R=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,O=e.audio.inbound.bytesReceived;this._trackBreach(Uu,R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach($u,R!==void 0&&O-R==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(Bu,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(Bu,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,_,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),_?{codec:this._buildCodecSnapshot(_,n.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;y.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void y.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,y.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class bt{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow=!1,this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Zy),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return y.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),y.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,y.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return B(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"];for(const n of i){const s=this._drain(n);if(s.length===0)continue;const o=this._buildEnvelope(s,n,"final",this._startedAt,this._endedAt||new Date);yield this._postRecording(e,o,!0)}})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),B(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+bt.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+bt.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow||(this._overflowWarnedThisWindow=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Qy))}}_flushIntervalMs(){var e;return(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:nh}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:sh}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{y.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return B(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;for(const o of i){const r=this._drain(o);if(r.length===0)continue;const a=this._buildEnvelope(r,o,"intermediate",n,s);yield this._postRecording(e,a,!1)}this._overflowWarnedThisWindow=!1}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return B(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=bt.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=bt.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void y.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=bt.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}bt.RETRY_DELAYS_MS=[500,1e3,2e3],bt.KEEPALIVE_BODY_LIMIT_BYTES=61440,bt.PACKET_OVERHEAD_BYTES=160;class eb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return B(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return B(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){y.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return B(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var ys,Ch=Gu(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(g){return g._maxListeners===void 0?s.defaultMaxListeners:g._maxListeners}function r(g,m,f,S){var I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");P.name="MaxListenersExceededWarning",P.emitter=g,P.type=m,P.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(P)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!1;return S.listener=f,S}function l(g){var m=this._events;if(m){var f=m[g];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(g,m){for(var f=Array(m);m--;)f[m]=g[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||0>g||isNaN(g))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=g,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(g){var m,f,S,I,A,x,P,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(P=this.domain,M){if(m=arguments[1],!P){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=P,m.domainThrown=!1,P.emit("error",m),!1}if(!(f=x[g]))return!1;var H=typeof f=="function";switch(S=arguments.length){case 1:(function($,Z,Y){if(Z)$.call(Y);else for(var W=$.length,ce=c($,W),J=0;J<W;++J)ce[J].call(Y)})(f,H,this);break;case 2:(function($,Z,Y,W){if(Z)$.call(Y,W);else for(var ce=$.length,J=c($,ce),te=0;te<ce;++te)J[te].call(Y,W)})(f,H,this,arguments[1]);break;case 3:(function($,Z,Y,W,ce){if(Z)$.call(Y,W,ce);else for(var J=$.length,te=c($,J),ie=0;ie<J;++ie)te[ie].call(Y,W,ce)})(f,H,this,arguments[1],arguments[2]);break;case 4:(function($,Z,Y,W,ce,J){if(Z)$.call(Y,W,ce,J);else for(var te=$.length,ie=c($,te),ne=0;ne<te;++ne)ie[ne].call(Y,W,ce,J)})(f,H,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function($,Z,Y,W){if(Z)$.apply(Y,W);else for(var ce=$.length,J=c($,ce),te=0;te<ce;++te)J[te].apply(Y,W)})(f,H,this,I)}return!0},s.prototype.addListener=function(g,m){return r(this,g,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,m){return r(this,g,m,!0)},s.prototype.once=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(g,a(this,g,m)),this},s.prototype.prependOnceListener=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(g,a(this,g,m)),this},s.prototype.removeListener=function(g,m){var f,S,I,A,x;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[g]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete S[g],S.removeListener&&this.emit("removeListener",g,f.listener||m));else if(typeof f!="function"){for(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[g]}else(function(P,M){for(var F=M,H=F+1,$=P.length;H<$;F+=1,H+=1)P[F]=P[H];P.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||m)}return this},s.prototype.removeAllListeners=function(g){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[g]&&(--this._eventsCount==0?this._events=new n:delete f[g]),this;if(arguments.length===0){for(var S,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[g])=="function")this.removeListener(g,m);else if(m)do this.removeListener(g,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(g){var m,f,S=this._events;return S?f=(m=S[g])?typeof m=="function"?[m.listener||m]:function(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(m):[]:f=[],f},s.listenerCount=function(g,m){return typeof g.listenerCount=="function"?g.listenerCount(m):l.call(g,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var p=/^(?:[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 b(g){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(_[g[m+0]]+_[g[m+1]]+_[g[m+2]]+_[g[m+3]]+"-"+_[g[m+4]]+_[g[m+5]]+"-"+_[g[m+6]]+_[g[m+7]]+"-"+_[g[m+8]]+_[g[m+9]]+"-"+_[g[m+10]]+_[g[m+11]]+_[g[m+12]]+_[g[m+13]]+_[g[m+14]]+_[g[m+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(g,m){if(!g||!m)return{};const f={...g};if(f.localCandidateId){const S=m.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=m.get(f.remoteCandidateId);f.remote={...S}}return f}function k(g,m,f){return 8*function(S,I,A){const x=S[A],P=I?I[A]:null;return x===null||P===null?null:(x-P)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(g){if(!g.entries)return g;const m={};return g.forEach(function(f,S){m[S]=f}),m}function R(g,m,f={}){if(!g)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let P={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}P=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...P}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const P={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(P.clockRate=M.clockRate,P.mimeType=M.mimeType,P.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...P,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const P=g.get(I.codecId);P&&(x.clockRate=P.clockRate,x.mimeType=P.mimeType,x.payloadType=P.payloadType)}if(!S.connection.id&&I.transportId){const P=g.get(I.transportId);if(P&&P.selectedCandidatePairId){const M=g.get(P.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const P=g.get(I.codecId);P&&(x.clockRate=P.clockRate,x.mimeType=P.mimeType,x.payloadType=P.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let P=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,P,"bytesReceived"),x.packetRate=k(x,P,"packetsReceived")}),I.audio.outbound.map(x=>{let P=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,P,"bytesSent"),x.packetRate=k(x,P,"packetsSent")}),I.video.inbound.map(x=>{let P=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,P,"bytesReceived"),x.packetRate=k(x,P,"packetsReceived")}),I.video.outbound.map(x=>{let P=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,P,"bytesSent"),x.packetRate=k(x,P,"packetsSent")})),I}(S,m),S}let O,T={},E=[];e.WebRTCStats=class extends s{constructor(g){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={...g};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(g,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:g,pc:m})}async addConnection(g){const{pc:m,peerId:f}=g;let{connectionId:S,remote:I}=g;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const P=this.peersToMonitor[f][x];if(P.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);P.pc.connectionState==="closed"&&this.removeConnection({pc:P.pc})}}const A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{connectionId:S}}getTimeline(g){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),g?this.timeline.filter(m=>m.tag===g):this.timeline}get logger(){const g=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&g("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&g("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&g("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&g("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(g){let m,{connectionId:f,pc:S}=g;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let g in this.peersToMonitor)this.removePeer(g)}removePeer(g){if(this.logger.info(`Removing PeerConnection with id ${g}.`),this.peersToMonitor[g]){for(let m in this.peersToMonitor[g]){let f=this.peersToMonitor[g][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[g]}}destroy(){this.removeAllPeers(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=A}else this.peersToMonitor[m]={[f]:A};this.addPeerConnectionEventListeners(m,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(g=>{g.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(g=null){this.logger.info(g?`Getting stats from peer ${g}`:"Getting stats from all peers");let m={};if(g){if(!this.peersToMonitor[g])throw new Error(`Cannot get stats. Peer with id ${g} does not exist`);m[g]=this.peersToMonitor[g]}else m=this.peersToMonitor;let f=[];for(const S in m)for(const I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const P=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,H=this.getTimestamp(),$=L(F),Z={remote:A.options.remote},Y=R(F,A.stats.parsed,Z),W={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:H-P,data:Y};this.rawStats===!0&&(W.rawStats=F),this.statsObject===!0&&(W.statsObject=$),this.filteredStats===!0&&(W.filteredStats=this.filteroutStats($)),f.push(W),A.stats.parsed=Y}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(P){this.logger.error(P)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const g in this.peersToMonitor)for(const m in this.peersToMonitor[g]){const f=this.peersToMonitor[g][m].pc;this.checkIfConnectionIsClosed(g,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(g,m,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:g,connectionId:m,tag:"connection",data:"closed"})}return S}isConnectionClosed(g){return g.connectionState==="closed"||g.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 g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(g({stream:m}),m),m=>(g({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(g={}){const m={...g};for(const S in m){var f=m[S];this.statsToMonitor.includes(f.type)||delete m[S]}return m}get peerConnectionListeners(){return{icecandidate:(g,m,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:g,connectionId:m,data:S.candidate})},track:(g,m,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${g}`,S);const I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${g}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:g,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${g}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${g}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(g,m,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${g}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:g,connectionId:m,error:{errorCode:S.errorCode}})},connectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${g}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.connectionState})},negotiationneeded:(g,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${g}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:g,connectionId:m})},datachannel:(g,m,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${g}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:g,connectionId:m,data:S.channel})}}}addPeerConnectionEventListeners(g,m,f){this.logger.debug(`Adding event listeners for peer ${g} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[m][S]=this.peerConnectionListeners[S].bind(this,g,m,f),f.addEventListener(S,T[m][S],!1)})}parseGetUserMedia(g){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...g}};g.stream&&(m.data.details=this.parseStream(g.stream),g.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(g){const m={audio:[],video:[]};return g.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(g){return{enabled:g.enabled,id:g.id,contentHint:g.contentHint,kind:g.kind,label:g.label,muted:g.muted,readyState:g.readyState,constructorName:g.constructor.name,capabilities:g.getCapabilities?g.getCapabilities():{},constraints:g.getConstraints?g.getConstraints():{},settings:g.getSettings?g.getSettings():{},_track:g}}getStreamDetails(g){return{active:g.active,id:g.id,_stream:g}}getTrackEventObject(g){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:g,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:g,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:g,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:g,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(g,m){T[g.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(S=>{T[g.id][S]=f[S].bind(this),g.addEventListener(S,T[g.id][S])}),T[g.id].readyState=setInterval(()=>{if(g.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});g.dispatchEvent(S)}},1e3)}removeTrackEventListeners(g){if(g.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{g.removeEventListener(f,T[g.id][f])}),clearInterval(T[g.id].readyState),delete T[g.id]}}addToTimeline(g){this.timeline.push(g),this.emit("timeline",g)}emitEvent(g){const m={...g,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(g){if(!Number.isInteger(g))throw new Error(`getStatsInterval should be an integer, got: ${g}`);this._getStatsInterval=g,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(g,m){g in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[g][f],!1)}),delete T[g]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const g=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return g.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return g.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(ys=Ch)&&ys.__esModule&&Object.prototype.hasOwnProperty.call(ys,"default")&&ys.default;var tb=Ch.WebRTCStats;function ib(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),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 nb(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 sb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ob extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class rb extends Li{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function ab(t,e){const i=ki();let n=!1;const s=new tb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&V(N.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=ib({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:nb(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new rb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new sb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();V(N.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new ob(i,e)),s.removeAllPeers(),s.destroy(),n=!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 Th=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:nt.conferenceUpdate,call:t.calls[s],canvasInfo:lb(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ke.LayerInfo},a);V(N.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ke.LayoutInfo},a);V(N.Notification,l,t.uuid);break}}},lb=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Xu(e)},Eh=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],cb={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function ae(t,e){return`telnyx:call:${t}:${e}`}function kh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Mr(t){for(const e of Eh)try{performance.clearMarks(ae(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>B(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return B(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,_=p==null?void 0:p.transport;_&&(d.dtlsState=_.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(d.candidatePairState=_.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(d.dtlsCipher=_.dtlsCipher,d.srtpCipher=_.srtpCipher,d.tlsVersion=_.tlsVersion,_.dtlsState&&(d.dtlsState=_.dtlsState))})}catch(p){y.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Ne(e0);V(N.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(n0);V(N.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(ae(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(ae(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(ae(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(ae(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;y.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},y.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.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=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(y.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.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(ae(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return B(this,void 0,void 0,function*(){performance.mark(ae(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Bt&&V(N.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":V(N.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(ae(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&gs(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(ae(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=kh(ae(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Eh){if(d==="new-call-start")continue;const h=kh(ae(s,d));h!==void 0&&l.push({label:cb[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void y.info(`${l} No timing data collected`);const c=Math.max(...a.map(_=>_.label.length),4)+2,u=(_,v)=>{for(;_.length<v;)_+=" ";return _},d=(_,v)=>{for(;_.length<v;)_=" "+_;return _},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let _=0;_<h.length;_++)p+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Mr(this.options.id)}createPeerConnection(){return B(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer}),performance.mark(ae(this.options.id,"set-remote-description")),!this.instance))throw se(yr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>B(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),V(N.Error,{error:se(Ii(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>B(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw se(yr);if(!this.options.localStream&&!i)throw se(n?Ii(n):Mu,n??void 0);performance.mark(ae(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),_s(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(ae(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Ne(i0);V(N.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(t0);V(N.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return B(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw se(yr);this.isDebugEnabled&&(this.statsReporter=ab(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:i,localStream:n=null,screenShare:s=!1}=this.options;if(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Sh(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(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,n)}),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(n);s===!1&&gs(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Sh(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);y.info("Add transceiver",e,i)}}_createOffer(){return B(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,y.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(ae(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(ae(this.options.id,"set-local-description")),performance.mark(ae(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){throw y.error("Peer _createOffer error:",e),e instanceof Bt?e:se(Oy,e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),se(Ou,i)}})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return y.debug("Skipping negotiation, state:",this.instance.signalingState),y.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:Fe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(ae(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(ae(this.options.id,"set-local-description")),performance.mark(ae(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createAnswer error:",e),e instanceof Bt?e:se(My,e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),se(Py,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(vn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,B(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield vs(s,a,_t.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield vs(r,l,_t.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return ms(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return y.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){Mr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const bs=Ar;class Ih{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=G[G.New],this.prevState="",this.channels=[],this.role=kr.Participant,this.extension=null,this._state=G.New,this._prevState=G.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:p},ringtoneFile:_,ringbackFile:v}=e;this.options=Object.assign({},M0,{audio:h,video:p,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:_,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),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._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=yh(this.options.ringtoneFile,"_ringtone"),this._ringback=yh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
- `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}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 this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=vt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(ae(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Bt?e:se(Fu,e instanceof Error?e:void 0);return V(N.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r,a,l,c;return B(this,void 0,void 0,function*(){const u=((s=(n=(i=this.session).getActiveCalls)===null||n===void 0?void 0:n.call(i))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&y.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=Ne(o0);return V(N.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(ae(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=vt.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(ae(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Bt?d:se(Fu,d instanceof Error?d:void 0);return V(N.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){bh(this._ringtone)}stopRingtone(){wh(this._ringtone)}playRingback(){bh(this._ringback)}stopRingback(){wh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return B(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),_=c.initiator||"app:call.hangup",v=this._state<G.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],y.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:_,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(G.Recovering),void this._finalize();if(this.setState(G.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new j0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let w;try{yield Promise.race([this._execute(b),new Promise(C=>{w=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){y.error("telnyx_rtc.bye failed!",C);const k=se(Uy,C);V(N.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{w&&clearTimeout(w)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(G.Destroy)})}hold(){const e=new fs({sessid:this.session.sessionid,action:Ai.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new fs({sessid:this.session.sessionid,action:Ai.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new fs({sessid:this.session.sessionid,action:Ai.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new ph({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new ph({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,_s(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Or(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?_s(this.options.localStream):Or(this.options.localStream)}toggleAudioMute(){y.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return B(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void V(N.Warning,{warning:Ne(a0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:xr(l.track),localTracks:_h(this.options.localStream)});try{c=yield ps({audio:{deviceId:{exact:e}}})}catch(h){const p=se(Ii(h),h);return void V(N.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=se(Ii(h),h);return V(N.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(_=>_.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:xr(l.track),localTracks:_h(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Oi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Oi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Oi(e,"video",null)}setVideoDevice(e){return B(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield ps({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;gs(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){_s(this.options.remoteStream)}undeaf(){Or(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Oi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void y.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===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.error("Could not set bandwidth (reason: no "+i+" 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")}_isTerminatingOrTerminated(){return[G.Hangup,G.Destroy,G.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n,s,o,r;switch(this._prevState=this._state,this._state=e,this.state=G[this._state].toLowerCase(),this.prevState=G[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:nt.callUpdate,call:this}),e){case G.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case G.Active:if(performance.mark(ae(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:a,speakerId:l}=this.options;a&&l&&mh(a,l)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const a=(s=this.session.connection)===null||s===void 0?void 0:s.host;a&&this._callRecorder._setHost(a),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const l=(o=this.options.localStream)===null||o===void 0?void 0:o.getAudioTracks()[0],c=(r=this.options.remoteStream)===null||r===void 0?void 0:r.getAudioTracks()[0];this._callRecorder.start(l,c)}this._mediaDeviceCollector=new eb,this._mediaDeviceCollector.logDevicesAtStart();break;case G.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Q.Answer:if(performance.mark(ae(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=G.Active)return;this._state>=G.Early&&this.setState(G.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Q.Media:if(performance.mark(ae(this.id,"telnyx-rtc-media")),this._state>=G.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Q.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===vt.Inbound?vt.Outbound:vt.Inbound,c={type:nt[i],call:this,displayName:o,displayNumber:r,displayDirection:l};V(N.Notification,c,this.id)||V(N.Notification,c,this.session.uuid);break}case Q.Candidate:this._addIceCandidate(n);break;case Q.Info:case Q.Event:{const o=Object.assign(Object.assign({},n),{type:nt.generic,call:this});V(N.Notification,o,this.id)||V(N.Notification,o,this.session.uuid);break}case Q.Ringing:performance.mark(ae(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Q.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return y.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:Ke.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const _ in s)p.push(Object.assign({callId:s[_][0],index:Number(_)},ls(s[_][1])));this._dispatchConferenceUpdate({action:Ke.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ke.Add,callId:o,index:r},ls(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ke.Modify,callId:o,index:r},ls(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ke.Delete,callId:o,index:r},ls(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ke.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return B(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Ke.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Lr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return B(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,Th(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Lr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(G.Active):this.setState(G.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=se(Vy,e);return V(N.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new fs(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ai.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>B(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(y.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,i){var n,s,o;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=se(zy,i);V(N.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return B(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Fe.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(ae(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(G.Early),this.gotAnswer&&this.setState(G.Active)}).catch(n=>B(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=se(Ou,n);V(N.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){y.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ri(this.peer.onSdpReadyTwice)){const e=se(_r,new Error("SDP without candidates for the second time!"));V(N.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void y.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return y.info(`No candidate - retry
117
- `),void this._requestAnotherLocalDescription();if((n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),!m0.test(o)){const c=Ne(s0);y.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),V(N.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(ae(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${bs}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(G.Requesting),a=new uh(l);break;case Fe.Answer:this._isRecovering||this.setState(G.Answering),a=this.options.attach===!0?new fh(l):new hh(l);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ae(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(G.Trying):this.setState(G.Active)}).catch(c=>B(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=se(_r,c);V(N.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return y.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${bs}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(G.Requesting),o=new uh(r);break;case Fe.Answer:this._isRecovering||this.setState(G.Answering),o=this.options.attach===!0?new fh(r):new hh(r);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ae(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(G.Trying):this.setState(G.Active)}).catch(a=>B(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=se(_r,a);V(N.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){y.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i;e.candidate&&e.candidate.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const i=new W0({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return y.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new H0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(ae(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(ae(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n;this.options.trickleIce?this._onTrickleIce(i):!((n=this.peer)===null||n===void 0)&&n.iceDone||this._onIce(i)},e.onicegatheringstatechange=i=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(ae(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&gs(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:nt.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),V(N.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:nt.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&V(N.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:nt.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:nt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(V(N.Notification,e,this.id,!1)||V(N.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=Ne(c0);return V(N.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v}=this.options;var b;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0),h&&(b=h,Object.keys(b).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ut(N.MediaError,this._onMediaError,this.id),Ut(N.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(N.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ri(_)&&Ut(N.Notification,_.bind(this),this.id);const w=this.session.options.enableCallReports!==!1,C=this.session.options.callReportInterval||5e3,k=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,L=this.session.options.debugLogLevel||"debug",R=this.session.options.debugLogMaxEntries||1e3;if(w&&(this._callReportCollector=new le({enabled:!0,interval:C,intermediateReportInterval:k},{enabled:!0,level:L,maxEntries:R}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=O=>{var T,E,g,m;V(N.Warning,{warning:O,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),O.code===Uu?(E=(T=this.session).reportNoRtp)===null||E===void 0||E.call(T,this.id,"inbound"):O.code===$u&&this._hasActiveUnmutedLocalAudioTrack()&&((m=(g=this.session).reportNoRtp)===null||m===void 0||m.call(g,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const O={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:nh,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:sh,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},T={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new bt(O,T);const E=(l=this.session.connection)===null||l===void 0?void 0:l.host;E&&this._callRecorder._setHost(E),this._callRecorder.onWarning=g=>{V(N.Warning,{warning:g,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(G.Recovering):this.setState(G.New),y.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}_finalize(){var e,i,n;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(i=this._callRecorder)===null||i===void 0||i.stop(),Mr(this.id),y.debug(`[${this.id}] Closing peer from _finalize`),(n=this.peer)===null||n===void 0||n.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;_n(s),_n(o),gh(r,s),gh(a,o),yt(N.MediaError,null,this.id),yt(N.PeerConnectionFailureError,null,this.id),yt(N.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,i,n,s,o,r,a,l,c,u,d,h;const p=this.session.options,_=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},_?{anonymousLogin:{targetType:_.target_type,targetId:_.target_id,targetVersionId:_.target_version_id,targetParams:this._sanitizeClientOption(_.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(i=p.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=p.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)===null||c===void 0||c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:i,username:n,credential:s})=>({urls:i,hasUsername:!!n,hasCredential:!!s}))}_sanitizeClientOption(e,i=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(i>=4)return"[truncated]";if(Array.isArray(e))return e.map(n=>this._sanitizeClientOption(n,i+1)).filter(n=>n!==void 0);if(typeof e=="object"){const n=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,i+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(n)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void y.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void y.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===vt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:bs,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,n,s,a,l).catch(u=>{y.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void y.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{y.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return y.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===vt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:bs,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw y.error("Failed to post call report",{error:c}),c}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ih.setStateTelnyx=t=>{if(t){switch(t._state){case G.Recovering:t.state="recovering";break;case G.Requesting:case G.Trying:case G.Early:t.state="connecting";break;case G.Active:t.state="active";break;case G.Held:t.state="held";break;case G.Hangup:case G.Destroy:t.state="done";break;case G.Answering:t.state="ringing";break;case G.New:t.state="new"}return t}};class ni extends Ih{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Z0(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new Q0(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return B(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return B(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>B(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return B(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&mh(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
115
+ `),Oe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!B(r.id,r)){const l=Cr(r);B(P.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==ah?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(P.SocketClose,{code:Wu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Sr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_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)),B(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const lh={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 Ue extends Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Ou(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in lh)n&&i.hasOwnProperty(n)&&(i[lh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class ch extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class V0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Cr(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new ch(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Qu({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Qu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Ar extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Di.isCriticalMethod(n)?(y.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){y.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ne(zy);B(P.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return y.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(y.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Ar(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(y.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(h0);B(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(f0);B(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var dh="2.27.8-beta.0",xr=dh;class U0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:xr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class $0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class uh extends Ue{toString(){return Z.Invite}}class hh extends Ue{toString(){return Z.Answer}}class fh extends Ue{toString(){return Z.Attach}}class j0 extends Ue{toString(){return Z.Bye}}class H0 extends Ue{toString(){return Z.Candidate}}class W0 extends Ue{toString(){return Z.EndOfCandidates}}class ps extends Ue{toString(){return Z.Modify}}class ph extends Ue{toString(){return Z.Info}}class G0 extends Ue{toString(){return Z.Broadcast}}class q0 extends Ue{toString(){return Z.Subscribe}}class z0 extends Ue{toString(){return Z.Unsubscribe}}class K0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:xr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class ti{constructor(e){if(this.options=e,this.uuid=ki(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Yu=(n=ls[i])!==null&&n!==void 0?n:ls.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._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new fs(this),this.registerAgent=new V0(this)}get __logger(){return y}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return V(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return y.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>V(this,void 0,void 0,function*(){if(s instanceof Sr)throw y.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=ne(Gy,s,void 0,!0);B(P.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return V(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||pn(this.options)}broadcast(e){}disconnect(){return V(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),y.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return bt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Bu,e);B(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){th()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(d0);B(P.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return V(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)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=ne(Wy,void 0,s);return void B(P.Error,{error:o,type:O0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return V(this,void 0,void 0,function*(){let a;const l=!!gn(),c=l&&(this.sessionid&&eh()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?eh(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new U0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new K0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&kr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return V(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){y.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(Wu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Rr(this.relayProtocol);for(const l in this.subscriptions)Rr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&kr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(br);return void B(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(p0);B(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],bt(e,null,i)):(delete this.subscriptions[e],Rr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),y.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Ar(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([W.Early,W.Active,W.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){y.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return y.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Ut(e,i)}static off(e){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(c0);B(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},gh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},mh=(t,e)=>V(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),Y0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(Y0),t=null},vs=t=>V(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(t=null,e=!1)=>V(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),vh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield yn(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),X0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Lr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,_h=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Lr(a)):[]},Dr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Or(t);return i.includes(e)||n.includes(e)},Or=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Mr=t=>{Oi(t,"audio",!0)},ys=t=>{Oi(t,"audio",!1)};function J0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!vs}}catch(t){return t.message}}var Ee;function yh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function bh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function wh(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"})(Ee||(Ee={}));const Sh=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class Z0 extends Li{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class Q0 extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._isHeld=!1,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new R0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Ku=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return V(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),y.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return y.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],_=new Date;this._lastIntermediateFlushTime=_;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(_.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:_.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return y.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return V(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return V(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return V(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;y.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),_=(o||r)&&p.length<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,_,v,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((_=(p=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||g>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(as,!1),this._trackBreach(wr,!1))}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(le.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return V(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(g=>{switch(g.type){case"outbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(r=g);break;case"inbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(a=g);break;case"media-playout":g.kind==="audio"&&(l=g);break;case"remote-inbound-rtp":g.kind==="audio"&&(c=g);break;case"remote-outbound-rtp":g.kind==="audio"&&(u=g);break;case"candidate-pair":(g.nominated||g.state==="succeeded")&&h.push(g);break;case"transport":p=g}});const _=p==null?void 0:p.selectedCandidatePairId,v=_?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,_):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),w=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:_?h.find(g=>g.id===_)||h[h.length-1]||null:h[h.length-1]||null,r){const g=this._getOutboundAudioLevel(s,r);if(g!==null&&this.intervalAudioLevels.outbound.push(g),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const g=this._getInboundAudioLevel(s,a);if(g!==null&&this.intervalAudioLevels.inbound.push(g),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(o0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void y.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Ky,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Yy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Xy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(as,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach($u,O<le.THRESHOLD_MOS)}else this._trackBreach($u,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const R=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,O=e.audio.inbound.bytesReceived;this._trackBreach(wr,!this._isHeld&&R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(ju,R!==void 0&&O-R==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(as,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(as,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,_,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),_?{codec:this._buildCodecSnapshot(_,n.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;y.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void y.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,y.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class $e{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow={local:!1,remote:!1},this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Jy),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return y.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),y.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,y.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return V(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),V(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+$e.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+$e.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Zy))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*$e.BYTES_PER_SAMPLE+$e.FRAMES_PER_SECOND*$e.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:sh}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{y.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return V(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{y.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!1}}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return V(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=$e.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void y.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=$e.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}$e.RETRY_DELAYS_MS=[500,1e3,2e3],$e.KEEPALIVE_BODY_LIMIT_BYTES=61440,$e.PACKET_OVERHEAD_BYTES=160,$e.BYTES_PER_SAMPLE=4,$e.FRAMES_PER_SECOND=100;class eb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return V(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return V(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){y.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return V(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Ch=qu(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(g){return g._maxListeners===void 0?s.defaultMaxListeners:g._maxListeners}function r(g,m,f,S){var I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!1;return S.listener=f,S}function l(g){var m=this._events;if(m){var f=m[g];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(g,m){for(var f=Array(m);m--;)f[m]=g[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||0>g||isNaN(g))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=g,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(g){var m,f,S,I,A,x,N,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(N=this.domain,M){if(m=arguments[1],!N){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=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(f=x[g]))return!1;var G=typeof f=="function";switch(S=arguments.length){case 1:(function(U,ae,q){if(ae)U.call(q);else for(var H=U.length,ce=c(U,H),J=0;J<H;++J)ce[J].call(q)})(f,G,this);break;case 2:(function(U,ae,q,H){if(ae)U.call(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].call(q,H)})(f,G,this,arguments[1]);break;case 3:(function(U,ae,q,H,ce){if(ae)U.call(q,H,ce);else for(var J=U.length,ee=c(U,J),te=0;te<J;++te)ee[te].call(q,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(U,ae,q,H,ce,J){if(ae)U.call(q,H,ce,J);else for(var ee=U.length,te=c(U,ee),ie=0;ie<ee;++ie)te[ie].call(q,H,ce,J)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function(U,ae,q,H){if(ae)U.apply(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].apply(q,H)})(f,G,this,I)}return!0},s.prototype.addListener=function(g,m){return r(this,g,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,m){return r(this,g,m,!0)},s.prototype.once=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(g,a(this,g,m)),this},s.prototype.prependOnceListener=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(g,a(this,g,m)),this},s.prototype.removeListener=function(g,m){var f,S,I,A,x;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[g]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete S[g],S.removeListener&&this.emit("removeListener",g,f.listener||m));else if(typeof f!="function"){for(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[g]}else(function(N,M){for(var F=M,G=F+1,U=N.length;G<U;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||m)}return this},s.prototype.removeAllListeners=function(g){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[g]&&(--this._eventsCount==0?this._events=new n:delete f[g]),this;if(arguments.length===0){for(var S,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[g])=="function")this.removeListener(g,m);else if(m)do this.removeListener(g,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(g){var m,f,S=this._events;return S?f=(m=S[g])?typeof m=="function"?[m.listener||m]:function(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(m):[]:f=[],f},s.listenerCount=function(g,m){return typeof g.listenerCount=="function"?g.listenerCount(m):l.call(g,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var p=/^(?:[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 b(g){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(_[g[m+0]]+_[g[m+1]]+_[g[m+2]]+_[g[m+3]]+"-"+_[g[m+4]]+_[g[m+5]]+"-"+_[g[m+6]]+_[g[m+7]]+"-"+_[g[m+8]]+_[g[m+9]]+"-"+_[g[m+10]]+_[g[m+11]]+_[g[m+12]]+_[g[m+13]]+_[g[m+14]]+_[g[m+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(g,m){if(!g||!m)return{};const f={...g};if(f.localCandidateId){const S=m.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=m.get(f.remoteCandidateId);f.remote={...S}}return f}function k(g,m,f){return 8*function(S,I,A){const x=S[A],N=I?I[A]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(g){if(!g.entries)return g;const m={};return g.forEach(function(f,S){m[S]=f}),m}function R(g,m,f={}){if(!g)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}N=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=g.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=g.get(N.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let N=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,m),S}let O,T={},E=[];e.WebRTCStats=class extends s{constructor(g){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={...g};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(g,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:g,pc:m})}async addConnection(g){const{pc:m,peerId:f}=g;let{connectionId:S,remote:I}=g;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{connectionId:S}}getTimeline(g){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),g?this.timeline.filter(m=>m.tag===g):this.timeline}get logger(){const g=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&g("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&g("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&g("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&g("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(g){let m,{connectionId:f,pc:S}=g;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let g in this.peersToMonitor)this.removePeer(g)}removePeer(g){if(this.logger.info(`Removing PeerConnection with id ${g}.`),this.peersToMonitor[g]){for(let m in this.peersToMonitor[g]){let f=this.peersToMonitor[g][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[g]}}destroy(){this.removeAllPeers(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=A}else this.peersToMonitor[m]={[f]:A};this.addPeerConnectionEventListeners(m,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(g=>{g.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(g=null){this.logger.info(g?`Getting stats from peer ${g}`:"Getting stats from all peers");let m={};if(g){if(!this.peersToMonitor[g])throw new Error(`Cannot get stats. Peer with id ${g} does not exist`);m[g]=this.peersToMonitor[g]}else m=this.peersToMonitor;let f=[];for(const S in m)for(const I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,G=this.getTimestamp(),U=L(F),ae={remote:A.options.remote},q=R(F,A.stats.parsed,ae),H={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:G-N,data:q};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=U),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(U)),f.push(H),A.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const g in this.peersToMonitor)for(const m in this.peersToMonitor[g]){const f=this.peersToMonitor[g][m].pc;this.checkIfConnectionIsClosed(g,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(g,m,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:g,connectionId:m,tag:"connection",data:"closed"})}return S}isConnectionClosed(g){return g.connectionState==="closed"||g.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 g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(g({stream:m}),m),m=>(g({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(g={}){const m={...g};for(const S in m){var f=m[S];this.statsToMonitor.includes(f.type)||delete m[S]}return m}get peerConnectionListeners(){return{icecandidate:(g,m,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:g,connectionId:m,data:S.candidate})},track:(g,m,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${g}`,S);const I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${g}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:g,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${g}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${g}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(g,m,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${g}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:g,connectionId:m,error:{errorCode:S.errorCode}})},connectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${g}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.connectionState})},negotiationneeded:(g,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${g}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:g,connectionId:m})},datachannel:(g,m,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${g}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:g,connectionId:m,data:S.channel})}}}addPeerConnectionEventListeners(g,m,f){this.logger.debug(`Adding event listeners for peer ${g} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[m][S]=this.peerConnectionListeners[S].bind(this,g,m,f),f.addEventListener(S,T[m][S],!1)})}parseGetUserMedia(g){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...g}};g.stream&&(m.data.details=this.parseStream(g.stream),g.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(g){const m={audio:[],video:[]};return g.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(g){return{enabled:g.enabled,id:g.id,contentHint:g.contentHint,kind:g.kind,label:g.label,muted:g.muted,readyState:g.readyState,constructorName:g.constructor.name,capabilities:g.getCapabilities?g.getCapabilities():{},constraints:g.getConstraints?g.getConstraints():{},settings:g.getSettings?g.getSettings():{},_track:g}}getStreamDetails(g){return{active:g.active,id:g.id,_stream:g}}getTrackEventObject(g){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:g,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:g,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:g,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:g,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(g,m){T[g.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(S=>{T[g.id][S]=f[S].bind(this),g.addEventListener(S,T[g.id][S])}),T[g.id].readyState=setInterval(()=>{if(g.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});g.dispatchEvent(S)}},1e3)}removeTrackEventListeners(g){if(g.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{g.removeEventListener(f,T[g.id][f])}),clearInterval(T[g.id].readyState),delete T[g.id]}}addToTimeline(g){this.timeline.push(g),this.emit("timeline",g)}emitEvent(g){const m={...g,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(g){if(!Number.isInteger(g))throw new Error(`getStatsInterval should be an integer, got: ${g}`);this._getStatsInterval=g,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(g,m){g in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[g][f],!1)}),delete T[g]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const g=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return g.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return g.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(bs=Ch)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var tb=Ch.WebRTCStats;function ib(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),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 nb(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 sb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ob extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class rb extends Li{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function ab(t,e){const i=ki();let n=!1;const s=new tb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>V(this,void 0,void 0,function*(){r.event==="stats"&&B(P.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=ib({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:nb(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new rb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new sb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>V(this,void 0,void 0,function*(){const a=s.getTimeline();B(P.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new ob(i,e)),s.removeAllPeers(),s.destroy(),n=!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 Th=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:st.conferenceUpdate,call:t.calls[s],canvasInfo:lb(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);B(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);B(P.Notification,l,t.uuid);break}}},lb=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Ju(e)},Eh=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],cb={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function re(t,e){return`telnyx:call:${t}:${e}`}function kh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Pr(t){for(const e of Eh)try{performance.clearMarks(re(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>V(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return V(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,_=p==null?void 0:p.transport;_&&(d.dtlsState=_.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(d.candidatePairState=_.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(d.dtlsCipher=_.dtlsCipher,d.srtpCipher=_.srtpCipher,d.tlsVersion=_.tlsVersion,_.dtlsState&&(d.dtlsState=_.dtlsState))})}catch(p){y.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Ne(Qy);B(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(i0);B(P.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(re(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(re(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(re(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(re(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;y.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},y.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.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=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(y.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.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(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return V(this,void 0,void 0,function*(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Vt&&B(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(re(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(re(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=kh(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Eh){if(d==="new-call-start")continue;const h=kh(re(s,d));h!==void 0&&l.push({label:cb[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void y.info(`${l} No timing data collected`);const c=Math.max(...a.map(_=>_.label.length),4)+2,u=(_,v)=>{for(;_.length<v;)_+=" ";return _},d=(_,v)=>{for(;_.length<v;)_=" "+_;return _},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let _=0;_<h.length;_++)p+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Pr(this.options.id)}createPeerConnection(){return V(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(yr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>V(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),B(P.Error,{error:ne(Ii(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>V(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ne(yr);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Fu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(re(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Ne(t0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(e0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return V(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ne(yr);this.isDebugEnabled&&(this.statsReporter=ab(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:i,localStream:n=null,screenShare:s=!1}=this.options;if(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Sh(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(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,n)}),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(n);s===!1&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Sh(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);y.info("Add transceiver",e,i)}}_createOffer(){return V(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,y.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(re(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){throw y.error("Peer _createOffer error:",e),e instanceof Vt?e:ne(Dy,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),ne(Nu,i)}})}_createAnswer(){return V(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return y.debug("Skipping negotiation, state:",this.instance.signalingState),y.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:Fe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(re(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createAnswer error:",e),e instanceof Vt?e:ne(Oy,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),ne(My,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(vn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,V(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return y.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Pr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=xr;class Ih{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Ir.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:p},ringtoneFile:_,ringbackFile:v}=e;this.options=Object.assign({},M0,{audio:h,video:p,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:_,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),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._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=yh(this.options.ringtoneFile,"_ringtone"),this._ringback=yh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
+ `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}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 this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return V(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=_t.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Vt?e:ne(Uu,e instanceof Error?e:void 0);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r,a,l,c;return V(this,void 0,void 0,function*(){const u=((s=(n=(i=this.session).getActiveCalls)===null||n===void 0?void 0:n.call(i))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&y.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=Ne(s0);return B(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(re(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=_t.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Vt?d:ne(Uu,d instanceof Error?d:void 0);return B(P.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){bh(this._ringtone)}stopRingtone(){wh(this._ringtone)}playRingback(){bh(this._ringback)}stopRingback(){wh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return V(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),_=c.initiator||"app:call.hangup",v=this._state<W.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],y.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:_,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new j0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let w;try{yield Promise.race([this._execute(b),new Promise(C=>{w=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){y.error("telnyx_rtc.bye failed!",C);const k=ne(Vy,C);B(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{w&&clearTimeout(w)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new ps({sessid:this.session.sessionid,action:Ai.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new ph({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new ph({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ys(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Mr(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ys(this.options.localStream):Mr(this.options.localStream)}toggleAudioMute(){y.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return V(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void B(P.Warning,{warning:Ne(r0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Lr(l.track),localTracks:_h(this.options.localStream)});try{c=yield gs({audio:{deviceId:{exact:e}}})}catch(h){const p=ne(Ii(h),h);return void B(P.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=ne(Ii(h),h);return B(P.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(_=>_.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Lr(l.track),localTracks:_h(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Oi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Oi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Oi(e,"video",null)}setVideoDevice(e){return V(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield gs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ms(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){ys(this.options.remoteStream)}undeaf(){Mr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Oi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void y.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===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.error("Could not set bandwidth (reason: no "+i+" 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")}_isTerminatingOrTerminated(){return[W.Hangup,W.Destroy,W.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n,s,o,r,a,l;switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case W.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(re(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(y.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(n=this._callReportCollector)===null||n===void 0||n.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&mh(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new eb,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Z.Answer:if(performance.mark(re(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Z.Media:if(performance.mark(re(this.id,"telnyx-rtc-media")),this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Z.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===_t.Inbound?_t.Outbound:_t.Inbound,c={type:st[i],call:this,displayName:o,displayNumber:r,displayDirection:l};B(P.Notification,c,this.id)||B(P.Notification,c,this.session.uuid);break}case Z.Candidate:this._addIceCandidate(n);break;case Z.Info:case Z.Event:{const o=Object.assign(Object.assign({},n),{type:st.generic,call:this});B(P.Notification,o,this.id)||B(P.Notification,o,this.session.uuid);break}case Z.Ringing:performance.mark(re(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Z.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return V(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return y.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:Ye.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const _ in s)p.push(Object.assign({callId:s[_][0],index:Number(_)},cs(s[_][1])));this._dispatchConferenceUpdate({action:Ye.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ye.Add,callId:o,index:r},cs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ye.Modify,callId:o,index:r},cs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ye.Delete,callId:o,index:r},cs(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ye.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Ye.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Dr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,Th(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Dr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=ne(Fy,e);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new ps(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ai.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>V(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(y.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,i){var n,s,o;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ne(qy,i);B(P.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return V(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Fe.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(re(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>V(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=ne(Nu,n);B(P.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){y.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ri(this.peer.onSdpReadyTwice)){const e=ne(_r,new Error("SDP without candidates for the second time!"));B(P.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void y.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return y.info(`No candidate - retry
117
+ `),void this._requestAnotherLocalDescription();if((n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),!g0.test(o)){const c=Ne(n0);y.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),B(P.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(re(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${ws}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(W.Requesting),a=new uh(l);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new fh(l):new hh(l);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=ne(_r,c);B(P.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return y.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ws}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(W.Requesting),o=new uh(r);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new fh(r):new hh(r);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=ne(_r,a);B(P.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){y.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i;e.candidate&&e.candidate.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const i=new H0({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return y.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new W0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(re(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(re(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n;this.options.trickleIce?this._onTrickleIce(i):!((n=this.peer)===null||n===void 0)&&n.iceDone||this._onIce(i)},e.onicegatheringstatechange=i=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(re(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&ms(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:st.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),B(P.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:st.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&B(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(P.Notification,e,this.id,!1)||B(P.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=Ne(l0);return B(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var w;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(w=h,Object.keys(w).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ut(P.MediaError,this._onMediaError,this.id),Ut(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ri(_)&&Ut(P.Notification,_.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,L=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",O=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new le({enabled:!0,interval:k,intermediateReportInterval:L},{enabled:!0,level:R,maxEntries:O}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,g,m,f;B(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===wr&&this._state!==W.Held?(g=(E=this.session).reportNoRtp)===null||g===void 0||g.call(E,this.id,"inbound"):T.code===ju&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(m=this.session).reportNoRtp)===null||f===void 0||f.call(m,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const T={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:15e3,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:sh,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},E={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new $e(T,E);const g=(l=this.session.connection)===null||l===void 0?void 0:l.host;g&&this._callRecorder._setHost(g),this._callRecorder.onWarning=m=>{B(P.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),y.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}_finalize(){var e,i,n;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(i=this._callRecorder)===null||i===void 0||i.stop(),Pr(this.id),y.debug(`[${this.id}] Closing peer from _finalize`),(n=this.peer)===null||n===void 0||n.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;_n(s),_n(o),gh(r,s),gh(a,o),bt(P.MediaError,null,this.id),bt(P.PeerConnectionFailureError,null,this.id),bt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,i,n,s,o,r,a,l,c,u,d,h;const p=this.session.options,_=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},_?{anonymousLogin:{targetType:_.target_type,targetId:_.target_id,targetVersionId:_.target_version_id,targetParams:this._sanitizeClientOption(_.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(i=p.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=p.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)===null||c===void 0||c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:i,username:n,credential:s})=>({urls:i,hasUsername:!!n,hasCredential:!!s}))}_sanitizeClientOption(e,i=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(i>=4)return"[truncated]";if(Array.isArray(e))return e.map(n=>this._sanitizeClientOption(n,i+1)).filter(n=>n!==void 0);if(typeof e=="object"){const n=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,i+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(n)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void y.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void y.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,n,s,a,l).catch(u=>{y.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return V(this,void 0,void 0,function*(){if(!this._callReportCollector)return void y.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{y.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return y.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw y.error("Failed to post call report",{error:c}),c}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ih.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ni extends Ih{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Z0(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new Q0(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return V(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>V(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return V(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&mh(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>V(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
118
118
  ${r.type}
119
119
  `,Object.keys(r).forEach(a=>{o.includes(a)||(n+=` ${a}: ${r[a]}
120
- `)}))}),y.info(n)}),2e3)}}class ws extends ti{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>ws.ACTIVE_CALL_STATE_NAMES.has(e.state))}_extractSafeCallIdentifiers(e){var i,n;const s={callId:e.id,state:e.state,direction:e.direction};!((i=e.options)===null||i===void 0)&&i.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),!((n=e.options)===null||n===void 0)&&n.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const i=this.getActiveCalls().filter(r=>r.id!==e);if(i.length===0)return;const n=Ne(l0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};V(N.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),y.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${i.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){y.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return B(this,void 0,void 0,function*(){try{const n=yield ms({audio:e,video:i});return _n(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){y.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(G.Purge),y.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){y.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(G.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(rh(N.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return yn().catch(e=>{const i=se(Ii(e),e);return V(N.MediaError,i,this.uuid),[]})}getVideoDevices(){return yn(_t.Video).catch(e=>(V(N.MediaError,e,this.uuid),[]))}getAudioInDevices(){return yn(_t.AudioIn).catch(e=>{const i=se(Ii(e),e);return V(N.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return yn(_t.AudioOut).catch(e=>(y.error("getAudioOutDevices",e),V(N.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return vs(e,i,n)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(i=>B(void 0,void 0,void 0,function*(){const n=[],s=yield ms({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<vh.length;r++){const[a,l]=vh[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return _n(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=xu(e,["micId","micLabel"]);return X0(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield vs(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,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 i=this.options.env==="development";this._iceServers=i?S0:w0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=fn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=fn(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new G0({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return B(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new q0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Dr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return B(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new z0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Dr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ni.setStateTelnyx(e)}}ws.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class Rh{constructor(e,i){this.code=i,this.message=e}}class db{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new $0(e,i);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*(e=2,i=6,Math.floor(Math.random()*(i-e+1)+e));var e,i}handleMessage(e){var i,n,s,o,r,a,l,c,u,d,h;const{session:p}=this;p.setPingReceived();const{id:_,method:v,params:b={},voice_sdk_id:w}=e,C=b==null?void 0:b.callID,k=b==null?void 0:b.eventChannel,L=b==null?void 0:b.eventType,R=p.calls[C],O=(i=R==null?void 0:R.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),T=new Set(Object.keys(p.calls));if(Array.isArray(b==null?void 0:b.reattached_sessions)&&T.size){y.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=b.reattached_sessions.length===0,S=b.reattached_sessions.some(I=>T.has(I));if(f||!S)for(const I of Object.keys(p.calls)){const A=p.calls[I];y.debug(`Session not reattached — terminating active call ${I} `);const x=se(Nu);V(N.Error,{error:x,callId:I,sessionId:p.sessionid},p.uuid),A.hangup({},!1)}}if(Array.isArray(b==null?void 0:b.reattached_sessions)&&p.sessionid){const f=th();if(f&&f.calls.length>0)if(f.sessionId!==p.sessionid)y.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${p.sessionid}) — ignoring all.`),ei();else{const S=new Set(b.reattached_sessions),I=[];for(const A of f.calls)try{if(S.has(A.id)){y.debug(`Recovery marker for call ${A.id} was reattached — keeping for Attach element restore.`),I.push(A);continue}y.info(`Recovery marker for call ${A.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const x=se(Nu);V(N.Error,{error:x,callId:A.id,sessionId:p.sessionid,customHeaders:A.customHeaders},p.uuid)}catch(x){y.debug(`Recovery marker for a saved call failed to process (callId=${A==null?void 0:A.id}) — skipping: ${x instanceof Error?x.message:String(x)}`),I.push(A)}ih(I,f.sessionId,f.storedAt)}}if(L==="channelPvtData")return this._handlePvtEvent(b.pvtData);const E=({recoveredCallId:f,forceRelayCandidateForRecovery:S,mutedMicOnStart:I,remoteElement:A,localElement:x}={})=>{var P,M,F,H,$;const Z={audio:!0,video:p.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Q.Attach,mediaSettings:b.mediaSettings,debug:(P=p.options.debug)!==null&&P!==void 0&&P,debugOutput:(M=p.options.debugOutput)!==null&&M!==void 0?M:"socket",trickleIce:(F=p.options.trickleIce)!==null&&F!==void 0&&F,prefetchIceCandidates:(H=p.options.prefetchIceCandidates)===null||H===void 0||H,forceRelayCandidate:S||p.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:($=p.options.keepConnectionAliveOnSocketClose)!==null&&$!==void 0&&$,mutedMicOnStart:I??p.options.mutedMicOnStart};C&&(Z.id=C),b.telnyx_call_control_id&&(Z.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(Z.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(Z.telnyxLegId=b.telnyx_leg_id),b.client_state&&(Z.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(Z.customHeaders=b.dialogParams.custom_headers),f&&(Z.recoveredCallId=f),A!==void 0&&(Z.remoteElement=A),x!==void 0&&(Z.localElement=x),performance.mark(ae(Z.id,"new-call-start"));const Y=new ni(p,Z);return Y.nodeId=this.nodeId,Y},g=new ch(w),m=new Rr(w);switch(v){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!C||!R)return void y.error(`Received ${v} for non existing call:`,b);R.handleMessage(e),this._ack(_,v);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Q.Punt:p.options.keepConnectionAliveOnSocketClose&&O?(y.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(_,v)):(y.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Q.Invite:{const I=E();I.direction=vt.Inbound,I.playRingtone(),I.setState(G.Ringing),this.session.emitMultipleActiveCallsWarning(I.id),this._ack(_,v);break}case Q.Attach:{const I=R||null;if(Object.keys(p.calls).length===0){let A,x;y.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`);const P=th();if(P&&P.sessionId===p.sessionid){const F=P.calls.find(H=>H.id===C);F&&(A=F.remoteElement,x=F.localElement,(A||x)&&y.info(`[${C}] Attach: restoring per-call media elements from recovery marker (remoteElement=${A??"<none>"}, localElement=${x??"<none>"}).`))}const M=E({recoveredCallId:C,remoteElement:A,localElement:x});M.answer(),this.session.emitMultipleActiveCallsWarning(M.id),this._ack(_,v);break}if(I){const A=I.id,x=(s=(n=I.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(I))!==null&&s!==void 0&&s;x&&y.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),y.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${A}.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const P=E({recoveredCallId:A,forceRelayCandidateForRecovery:x,mutedMicOnStart:I.isAudioMuted,remoteElement:I.options.remoteElement,localElement:I.options.localElement});P.answer(),this.session.emitMultipleActiveCallsWarning(P.id),this._ack(_,v);break}y.warn(`Attach: callID ${C} does not match any active calls. `),V(N.Warning,{warning:Ne(h0),callId:C,params:b,sessionId:p.sessionid},p.uuid),this._ack(_,v);break}case Q.Event:case"webrtc.event":if(!k)return void y.error("Verto received an unknown event:",b);const f=p.relayProtocol,S=k.split(".")[0];p._existsSubscription(f,k)?V(f,b,k):k===p.sessionid?this._handleSessionEvent(b.eventData):p._existsSubscription(f,S)?V(f,b,S):p.calls.hasOwnProperty(k)?p.calls[k].handleMessage(e):V(N.Notification,b,p.uuid);break;case Q.Info:b.type=nt.generic,V(N.Notification,b,p.uuid);break;case Q.ClientReady:this.session.execute(g);break;case"ai_conversation":V(N.AIConversationMessage,{method:"ai_conversation",params:b,voice_sdk_id:w},p.uuid);break;default:{const I=Sr(e);if(I){switch(I){case Oe.REGISTER:case Oe.REGED:if(!this.isDuplicateGatewayState(I,[Oe.REGED,Oe.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,I===Oe.REGED&&this.session.resetReconnectAttempts();const A=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.call_report_id;A&&(p.callReportId=A,y.debug("Captured call_report_id from REGED:",A));const x=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;x&&(p.dc=x);const P=(u=(c=e==null?void 0:e.result)===null||c===void 0?void 0:c.params)===null||u===void 0?void 0:u.region;P&&(p.region=P),y.info(`Connected to Telnyx — region: ${(d=p.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),b.type=nt.vertoClientReady,V(N.Ready,b,p.uuid)}break;case Oe.UNREGED:case Oe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const A=new Rh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),x=se(Pu,A);V(N.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{this.session.execute(g)},this.reconnectDelay());break;case Oe.FAILED:case Oe.FAIL_WAIT:case Oe.TIMEOUT:if(!this.isDuplicateGatewayState(I,[Oe.FAILED,Oe.FAIL_WAIT,Oe.TIMEOUT])){const A=se(Hy,new Error(`Gateway state: ${I}`));if(V(N.Error,{error:A,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,y.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${p.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const x=new Rh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const P=se(br,x);V(N.Error,{error:P,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const x=se(br,new Error("Connection Retry Failed"));V(N.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{if(y.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some(x=>{var P;return((P=x.peer)===null||P===void 0?void 0:P.instance)&&!x.signalingStateClosed}))return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();y.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:y.warn("GatewayState message unknown method:",e)}break}y.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&y.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return B(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const w=h||this._retrieveCallId(b,o);if(w&&i.calls.hasOwnProperty(w)){const C=i.calls[w];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(_).catch(b=>{y.error("liveArray subscription error:",b);const w=se($y,b);V(N.Error,{error:w,sessionId:i.sessionid},i.uuid)});Lr(v,o)&&p();break}case"conference-liveArray-part":{let p=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(p=i.calls[v]||null,v!==null){const b={type:nt.conferenceUpdate,action:Ke.Leave,conferenceName:r,participantId:Number(u),role:d};V(N.Notification,b,v,!1)||V(N.Notification,b,i.uuid),p===null&&yt(N.Notification,null,v)}}const _=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{y.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Th(this.session,e);break;case"logo-info":{const i={type:nt.conferenceUpdate,action:Ke.LogoInfo,logo:e.logoURL};V(N.Notification,i,this.session.uuid);break}}}}class ub extends ws{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new db(this),window.addEventListener("beforeunload",i=>{if(y.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return eh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(y.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));this.calls&&Object.keys(this.calls).forEach(n=>{const s=this.calls[n];s!=null&&s.flushIntermediateCallReport&&(y.debug(`beforeunload: flushing call report for ${n}.`),s.flushIntermediateCallReport({type:"page-unload"}))});try{const n=(this.calls?Object.keys(this.calls):[]).filter(s=>!!this.calls[s]).map(s=>this.calls[s]).map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders};return typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(!this.sessionid||n.length===0)return y.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void ei();y.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),ih(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];y.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${s.join(", ")}]): ${n instanceof Error?n.message:String(n)}`)}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(y.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Er(this.sessionid))})}validateOptions(){return cs(this.options)||pn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw se(By,void 0,"Error: destinationNumber is required");const i=new ni(this,e);return e.id||y.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(ae(i.id,"new-call-start")),i.invite(),i}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!pn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return B(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),cs(this.options)?this.handleLoginOnSocketOpen():pn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class hb extends ub{constructor(e){super(e),y.info(`SDK version: ${dh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return J0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ee.not_supported},{browserName:"Firefox",supported:Ee.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",features:["audio"],supported:Ee.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",features:["audio"],supported:Ee.partial}]}]}}function fb(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const i=e;return i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"&&typeof i.arguments=="string"}function Ah(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var xh={exports:{}},Lh;function pb(){return Lh||(Lh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||l,h),_=i?i+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],p]:l._events[_].push(p):(l._events[_]=p,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,p=new Array(h);d<h;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,p){var _=i?i+l:l;if(!this._events[_])return!1;var v=this._events[_],b=arguments.length,w,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){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,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,p),!0}for(C=1,w=new Array(b-1);C<b;C++)w[C-1]=arguments[C];v.fn.apply(v.context,w)}else{var k=v.length,L;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!w)for(L=1,w=new Array(b-1);L<b;L++)w[L-1]=arguments[L];v[C].fn.apply(v[C].context,w)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var _=0,v=[],b=p.length;_<b;_++)(p[_].fn!==c||d&&!p[_].once||u&&p[_].context!==u)&&v.push(p[_]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=i?i+l:l,this._events[c]&&r(this,c)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(xh)),xh.exports}var gb=pb();const Pr=Ah(gb),Ss=new Pr;var Nr={exports:{}},mb=Nr.exports,Dh;function vb(){return Dh||(Dh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(mb,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var w=s[b];this[w]=b<v?e:this.methodFactory(w,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,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 b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Nr)),Nr.exports}var _b=vb();const yb=Ah(_b),bb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),pe=yb.getLogger("telnyx-ai-agent"),wb=pe.methodFactory;pe.methodFactory=(t,e,i)=>{const n=wb(t,e,i);return function(...s){n(bb(),"-",...s)}},pe.setLevel("info");function Sb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Cb=10,Tb=500,Eb=100,Oh=20;class kb{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",Sb(e=>{pe.debug("AudioStreamMonitor updateAgentState",e),pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Ss.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Cb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Tb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Eb,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,i;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(i=this.remoteAudioContext)==null||i.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,i;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(i=this.localAudioContext)==null||i.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;pe.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 i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let n=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(i);const o=i.reduce((l,c)=>l+c,0)/i.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&pe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(n)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"});n=r};this.remoteIntervalId=window.setInterval(s,Oh)}startLocalMonitor(){if(!this.localStream){pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(pe.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),i=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const n=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&pe.debug("Local audio volume:",n),n>=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(i,Oh)}destroy(){this.stopAudioStreamMonitor()}}function Ib(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Rb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Ab(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Mh(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function xb(t){if(!Mh(t))return null;const e=t.params;return fb(e)?e.item:null}function Lb(t){if(!Mh(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const n of e.client_side_tools)if(n&&typeof n=="object"&&typeof n.name=="string"){const s=n;i.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return i}function Db(t){var i;if(!t||typeof t!="object")return!1;const e=t;return((i=e.params)==null?void 0:i.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const Ob=3e4;function Mb(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function Fr(t){return JSON.stringify({error:t})}class Pb{constructor(e){j(this,"registry",new Map);j(this,"toolTimeouts",new Map);j(this,"inFlight",new Set);j(this,"completed",new Set);j(this,"generation",0);j(this,"getActiveCall");j(this,"timeoutMs");j(this,"events");j(this,"handleEvent",e=>{const i=Lb(e);if(i){this.ingestToolSettings(i);return}const n=xb(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Ob,this.events={onInvoked:i=>this.safeEmit(()=>e.events.onInvoked(i)),onCompleted:i=>this.safeEmit(()=>e.events.onCompleted(i)),onError:i=>this.safeEmit(()=>e.events.onError(i))}}safeEmit(e){try{e()}catch(i){pe.warn(`[client-tools] lifecycle listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}register(e,i){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,i)}registerAll(e){for(const[i,n]of Object.entries(e))this.register(i,n)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:i,timeout_ms:n}of e)typeof n=="number"&&n>0&&this.toolTimeouts.set(i,n)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,i){this.generation===i&&this.completed.add(e)}async execute(e){const{call_id:i,name:n}=e;if(this.inFlight.has(i)||this.completed.has(i)){pe.debug(`[client-tools] duplicate function_call ignored (call_id=${i})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(n);if(!r){pe.warn(`[client-tools] no handler registered for tool "${n}"`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"unknown_tool"}),this.sendOutput(i,n,Fr("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{pe.warn(`[client-tools] invalid JSON arguments for tool "${n}" (call_id=${i})`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"invalid_arguments"}),this.sendOutput(i,n,Fr("invalid_arguments"),!0,s,o);return}this.inFlight.add(i),this.events.onInvoked({callId:i,toolName:n});const l={callId:i,toolName:n,rawArguments:e.arguments},c=this.toolTimeouts.get(n)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n,c);this.sendOutput(i,n,Mb(u),!1,s,o)}catch(u){const d=u instanceof Ph?"timeout":"handler_error";pe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,Fr(d),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Ph(n,i,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){pe.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){pe.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}if(!r||a!==r){pe.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:n}),this.events.onCompleted({callId:e,toolName:i,isError:s})}catch(l){pe.warn(`[client-tools] failed to send output for "${i}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:i,reason:"shutdown"})}}}class Ph extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}function Nb(t){return Rb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Fb(t){if(!Ab(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",i=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((n,s)=>(s.type==="text"&&(n+=s.text),n),""),i=t.params.item.content.reduce((n,s)=>(s.type==="image_url"&&s.image_url.url&&n.push({type:"image",url:s.image_url.url}),n),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:i}}class Vb extends Pr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcript",[]);j(this,"onSocketMessage",i=>{if(Ib(i))switch(i.params.type){case"response.text.delta":{const n=Nb(i);n&&(this.transcript.push(n),this.emit("transcript.item",n),Ss.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(Db(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=Fb(i);if(n){const s=this.transcript.findIndex(o=>o.id===n.id);s!==-1?this.transcript[s]=n:this.transcript.push(n),this.emit("transcript.item",n)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(N.SocketMessage,this.onSocketMessage)}}const Dt=t=>typeof t=="object"&&t!==null,Nh=t=>{const e=Dt(t)&&Dt(t.result)?t.result:t;if(!(!Dt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Bb=t=>Dt(t)&&Dt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Ub=(t,e)=>{if(!e||!Dt(t)||!Dt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Dt(i.params))return;const n=i.params;Dt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class $b extends Pr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcription");j(this,"removeLoginSuccessHook",null);j(this,"authenticated",!1);j(this,"authenticating",!1);j(this,"agentId");j(this,"versionId");j(this,"widgetVersion");j(this,"conversationId");j(this,"debug");j(this,"audioStreamMonitor");j(this,"clientTools");j(this,"activeCall");j(this,"chatMode");j(this,"dc",null);j(this,"region",null);j(this,"callReportId",null);j(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});j(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});j(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset()});j(this,"onSocketMessage",i=>{const n=Nh(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});j(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});j(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});j(this,"onAgentStateChange",i=>{this.emit("conversation.agent.state",i)});this.agentId=i.agentId,this.versionId=i.versionId||"main",this.widgetVersion=i.widgetVersion,this.conversationId=i.conversationId,this.debug=i.debug||!1,this.chatMode=i.chatMode||!1,this.activeCall=null,pe.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId};i.conversationId&&(n.target_params={conversation_id:i.conversationId}),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new hb({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(N.Ready,this.onClientReady),this.telnyxRTC.on(N.Error,this.onClientOrSocketError),this.telnyxRTC.on(N.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(N.SocketClose,this.onSocketClose),this.telnyxRTC.on(N.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(N.Notification,this.onNotification),this.transcription=new Vb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Ss.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new kb(i.vad),this.clientTools=new Pb({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:s=>this.emit("client.tool.invoked",s),onCompleted:s=>this.emit("client.tool.completed",s),onError:s=>this.emit("client.tool.error",s)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(N.AIConversationMessage,this.clientTools.handleEvent)}registerClientTool(i,n){this.clientTools.register(i,n)}unregisterClientTool(i){return this.clientTools.unregister(i)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var i;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(N.AIConversationMessage,this.clientTools.handleEvent),this.clientTools.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(N.Ready,this.onClientReady),this.telnyxRTC.off(N.Error,this.onClientOrSocketError),this.telnyxRTC.off(N.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(N.SocketClose,this.onSocketClose),this.telnyxRTC.off(N.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(N.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Ss.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(i,n)}get transcript(){return this.transcription.transcript}async startConversation(i){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw pe.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw pe.warn(d.message),this.emit("agent.error",d),d}const n=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=i||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[n],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var i;return(i=this.activeCall)==null?void 0:i.hangup()}setRemoteStream(i){this.audioStreamMonitor.setRemoteStream(i)}installLoginSuccessHook(){const i=this.telnyxRTC,n=i.execute,s=i.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=p=>{c===p&&(this.authenticating=!1)},d=function(p){const _=Bb(p),v=c;return _&&Ub(p,a),n.call(this,p).then(b=>{const w=_?Nh(b):void 0;return l&&w!==void 0&&(u(v),r({sessionId:w})),b})},h=function(p){const _=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&i.login===h&&u(_)})};return i.execute=d,i.login=h,()=>{l=!1,i.execute===d&&(i.execute=n),i.login===h&&(i.login=s)}}emitLoginStarted(i){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",i)}emitLoginSuccess(i){const n=this.telnyxRTC,s=n.sessionid||null;i.sessionId&&(n.sessionid=i.sessionId);const o=i.sessionId||n.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}var Fh={exports:{}},bn={},Vh;function jb(){if(Vh)return bn;Vh=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(n,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:n,key:r,ref:s!==void 0?s:null,props:o}}return bn.Fragment=e,bn.jsx=i,bn.jsxs=i,bn}var Bh;function Wb(){return Bh||(Bh=1,Fh.exports=jb()),Fh.exports}Wb(),kt(void 0),kt(null);const Hb=(t,e,i,n,s,o,r,a,l,c)=>new $b({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Cs=10,Uh=5e3,Gb=[46001,46003],qb=["login incorrect","authentication required","authentication failed"];function $h(t){var n;const e=t.code;if(e&&Gb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return qb.some(s=>i.includes(s))}const zb=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[p,_]=Ae(!1),[v,b]=Ae(null),[w,C]=Ae(!1),k=ue(0),L=ue(null),R=ue(null),O=ue(!1),T=ue(!1),E=ue(0),g=ue(0),m=He(()=>{L.current&&(clearTimeout(L.current),L.current=null)},[]),f=He(()=>{m(),k.current=0,T.current=!0,C(!1),b(null)},[m]),S=He(()=>{m(),C(!1)},[m]),I=He(A=>{if(m(),k.current>=Cs){re.error(`Max login retry attempts (${Cs}) exceeded`),C(!1);return}k.current+=1;const x=E.current,P=g.current;re.info(`Scheduling login retry attempt ${k.current}/${Cs} in ${Uh}ms due to: ${A}`),C(!0),L.current=window.setTimeout(()=>{var H;L.current=null;const M=R.current,F=M==null?void 0:M.telnyxRTC;if(E.current!==x||g.current!==P||M!=null&&M.isAuthenticating){re.info("Skipping login retry because a newer socket/login is already in progress"),S();return}if(O.current||T.current||M!=null&&M.isAuthenticated){re.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(re.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(H=F==null?void 0:F.socketDisconnect)==null||H.call(F))},Uh)},[m,S,f]);return xe(()=>{if(!t)return;const A=Hb(t,e,i,n,s,o,r,a,l,u);O.current=!1,T.current=!1,_(!1),b(null),C(!1),R.current=A;const x=()=>{re.info("Agent connected successfully"),O.current=!0,_(!0),f()},P=()=>{re.info("Agent disconnected"),O.current=!1,T.current=!1,_(!1)},M=W=>{if(re.error("AI Agent error:",W),$h(W)){if(O.current||T.current){re.debug("Ignoring retryable error — login already succeeded");return}k.current<Cs?(b(null),I(W.message)):(b(W),C(!1))}else b(W),C(!1)},F=A.telnyxRTC??null,H=()=>{g.current+=1,T.current=!1},$=()=>{re.info("Login succeeded; clearing pending login retry flow"),f()},Z=()=>{E.current+=1,T.current=!1},Y=()=>{T.current=!1};return A.on("agent.connected",x),A.on("agent.disconnected",P),A.on("agent.error",M),A.on("agent.login.started",H),A.on("agent.login.success",$),F&&typeof F=="object"&&(F.on(N.SocketOpen,Z),F.on(N.SocketClose,Y)),A.connect(),h(A),()=>{m(),A.off("agent.connected",x),A.off("agent.disconnected",P),A.off("agent.error",M),A.off("agent.login.started",H),A.off("agent.login.success",$),F&&typeof F=="object"&&(F.off(N.SocketOpen,Z),F.off(N.SocketClose,Y)),A.disconnect(),O.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:p,error:v,isReconnecting:w}},Kb="telnyx-ai-agent",Ye={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error",CLIENT_TOOLS_CONFIGURED:"client.tools.configured"};function Yb(t){var n,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;i.push({name:r.name,description:(n=r.client_side_tool)==null?void 0:n.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return i}function jh(){const t=document.querySelector(Kb);return t instanceof HTMLElement?t:null}function wt(t,e,i){const n=i||jh();if(!n){re.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),re.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const Xb=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=Mn(gu);xe(()=>{const c=i==null?void 0:i.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??jh()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const O=t.telnyxRTC,T={dc:(O==null?void 0:O.dc)??null,region:(O==null?void 0:O.region)??null,callReportId:(O==null?void 0:O.callReportId)??null};l(T),wt(Ye.AGENT_CONNECTED,T,c)},d=()=>{l(null),wt(Ye.AGENT_DISCONNECTED,void 0,c)},h=R=>{const O={message:R.message,name:R.name};if($h(R)){re.debug("Ignoring retryable agent.error in widget event layer"),wt(Ye.AGENT_ERROR,O,c);return}o(R),wt(Ye.AGENT_ERROR,O,c)},p=R=>{var O;s(R),wt(Ye.CONVERSATION_UPDATE,{type:R.type,callState:(O=R.call)==null?void 0:O.state},c)},_=R=>{wt(Ye.TRANSCRIPT_ITEM,R,c)},v=R=>{wt(Ye.CONVERSATION_AGENT_STATE,R,c)},b=R=>{wt(Ye.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const O=Yb(R);O&&wt(Ye.CLIENT_TOOLS_CONFIGURED,{tools:O},c)},L=R=>{const O=R,T={code:O==null?void 0:O.code,reason:O==null?void 0:O.reason,wasClean:O==null?void 0:O.wasClean,timestamp:new Date().toISOString()};re.info("[socket.close]",T),wt(Ye.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(N.SocketMessage,k),C.on(N.SocketClose,L)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",_),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",_),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),C&&typeof C=="object"&&(C.off(N.SocketMessage,k),C.off(N.SocketClose,L))}},[t,n,s,o,r,l])},Jb=2e3;async function Zb(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Wh(t){const e=t.split("-"),i=e[e.length-1];return i&&i.length===13&&/^\d+$/.test(i)?e.slice(0,-1).join("-"):t}const Qb=(t,e)=>{const[i,n]=Ae([]),[,s]=cr(),o=ue(e);xe(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return xe(()=>{if(!t)return;const c=h=>{n(p=>{const _=p[p.length-1];if(h.role==="assistant"&&_&&Wh(_.id)===Wh(h.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,w={..._,content:_.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...p.slice(0,-1),w]}if(h.role==="assistant"){s(w=>w==="thinking"||w==="processing_image"?"speaking":w);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const w={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,w]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(w=>w.id===h.id);if(v!==-1){const w=[...p];return w[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},w}if(_&&_.role==="user"&&h.timestamp.getTime()-_.timestamp.getTime()<Jb){const C={..._,id:h.id,content:_.content+" "+h.content,timestamp:h.timestamp,attachments:[..._.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...p,h]})},u=({state:h,userPerceivedLatencyMs:p,greetingLatencyMs:_,thinkingStartedAt:v})=>{(p!==void 0||_!==void 0)&&re.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${_} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),_!==void 0&&(a.current=_)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var _;const p=(_=h.call)==null?void 0:_.state;(p==="destroy"||p==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const p=await Zb(h);d.push(p)}catch(p){throw re.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Mi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class ew{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,i){var n;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,i),re.debug(`[client-tools] registered handler "${e}"`),(n=this.agent)==null||n.registerClientTool(e,i)}unregister(e){var n;const i=this.handlers.delete(e);return i&&(re.debug(`[client-tools] unregistered handler "${e}"`),(n=this.agent)==null||n.unregisterClientTool(e)),i}list(){return Array.from(this.handlers.keys())}attach(e,i){this.detach(),this.agent=e,this.listeners=i;for(const[n,s]of this.handlers)e.registerClientTool(n,s);this.boundInvoked=n=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(n)},this.boundCompleted=n=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(n)},this.boundError=n=>{var s;return(s=this.listeners)==null?void 0:s.onError(n)},e.on(Mi.INVOKED,this.boundInvoked),e.on(Mi.COMPLETED,this.boundCompleted),e.on(Mi.ERROR,this.boundError),this.handlers.size>0&&re.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Mi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Mi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Mi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function Vr(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const tw=(t,e)=>{const i=ue(null);i.current===null&&(i.current=new ew),Fs(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){re.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=i.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),xe(()=>{const n=i.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return n.attach(t,{onInvoked:o=>{Vr(s(),Ye.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{Vr(s(),Ye.CLIENT_TOOL_COMPLETED,o)},onError:o=>{Vr(s(),Ye.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},iw=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=Qt(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=Qb(e,i),d=ue(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,re.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[n,t]),r){case"collapsed":return D(Cu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(Ry,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(Cu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Br=()=>D(Si.div,{layoutId:dn,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:D("div",{className:"rounded-full animate-spin",children:D(Z_,{})})}),nw=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(Br,{});case"done":case"purged":case"destroy":return null;case"active":return D(iw,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(Br,{})}},sw=({className:t})=>D("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:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Hh(){const t=Qt();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(sw,{className:"w-8 h-8 mr-2"})}const ow=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=ue(!1),r=He(async()=>{if(!t){re.error("Client is not initialized.");return}if(!n){re.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){re.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,re.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(Si.div,{layoutId:dn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[D(Hh,{}),"Connecting..."]}):D(Si.button,{layoutId:dn,onClick:r,disabled:!n,"aria-busy":!n,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D(Hh,{}),s.start_call_text]})},rw='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@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)}}',aw=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),lw={duration:.1,ease:"circOut"},cw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?D(aw,{children:t}):t;return D("div",{ref:i,className:At(n.theme==="dark"&&"dark"),children:D(Wg,{transition:lw,children:[D("style",{children:rw}),o]})})},dw=t=>D(Si.div,{layoutId:dn,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:[D(X_,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("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"," ",D(oy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(ny,{className:"w-4 h-4"}),"Retry"]})]});function Pi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function uw({"agent-id":t,debug:e,"trickle-ice":i,"call-destination-number":n,"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":u,"conversation-id":d,"chat-mode":h,region:p,"skip-last-voice-sdk-id":_,environment:v,position:b="fixed","version-id":w}){const C=Pi(e),k=Pi(i),L=Pi(h),R=_===void 0?!0:Pi(_),O=Ze(()=>{if(l)try{return JSON.parse(l)}catch(he){re.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Ze(()=>({showUserPerceivedLatency:Pi(c),showGreetingLatency:Pi(u)}),[c,u]),{client:E,error:g,isConnected:m,isReconnecting:f}=zb(t,v,w,C,k,O,d,L,p,R),[S,I]=Ae(null),[A,x]=Ae(!1),[P,M]=Ae(!1),[F,H]=Ae(!1),[$,Z]=Ae(!1),Y=Mn(wu),W=C_(),ce={};if(n&&(ce.destinationNumber=n),s&&(ce.callerNumber=s),o&&(ce.callerName=o),r)try{ce.customHeaders=JSON.parse(r)}catch(he){re.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{ce.audio=JSON.parse(a);const he=ce.audio;if(typeof he=="object"){const oe=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(ge=>{oe[ge]||re.warn(`Audio constraint not supported by browser: ${ge}`)})}}catch(he){re.error("Invalid JSON for call-audio attribute:",a,he)}const J=He(()=>{x(!1)},[]),te=He(he=>{var oe;if(((oe=he.call)==null?void 0:oe.state)==="destroy")return Y(!1),Z(!0),I(null);I(he)},[Y]),ie=He(()=>{x(!1),f||M(!0)},[f]),ne=He(()=>{re.info("User triggered retry"),M(!1),x(!0),E&&E.connect()},[E]),me=He(he=>{if(S_(he)){const oe=he.params.widget_settings;oe&&Object.keys(oe).length>0&&(W(oe),H(!0))}},[W]),Le=ue(null);return Xb(E,{onReady:J,onConversationUpdate:te,onError:ie,onConfigMessage:me},Le),tw(E,Le),D(cw,{position:b,rootRef:Le,children:t?P||g?D(dw,{agentId:t,onRetry:ne}):A||f?D(Br,{message:f?"Retrying...":void 0}):S!=null&&S.call?D(nw,{call:S.call,client:E,latencySettings:T,chatMode:L,debug:C}):F?D(ow,{client:E,callProps:ce,chatMode:L&&!$,isReady:m&&!!E}):null:D("div",{children:"Please provide an assistant ID."})})}lf(uw,"telnyx-ai-agent",b_,{shadow:!0})})();
120
+ `)}))}),y.info(n)}),2e3)}}class Ss extends ti{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>Ss.ACTIVE_CALL_STATE_NAMES.has(e.state))}_extractSafeCallIdentifiers(e){var i,n;const s={callId:e.id,state:e.state,direction:e.direction};!((i=e.options)===null||i===void 0)&&i.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),!((n=e.options)===null||n===void 0)&&n.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const i=this.getActiveCalls().filter(r=>r.id!==e);if(i.length===0)return;const n=Ne(a0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};B(P.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),y.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${i.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return V(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return V(this,void 0,void 0,function*(){y.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return V(this,void 0,void 0,function*(){try{const n=yield vs({audio:e,video:i});return _n(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){y.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(W.Purge),y.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){y.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(W.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(rh(P.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return yn().catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return yn(yt.Video).catch(e=>(B(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return yn(yt.AudioIn).catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return yn(yt.AudioOut).catch(e=>(y.error("getAudioOutDevices",e),B(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return _s(e,i,n)}getDeviceResolutions(e){return V(this,void 0,void 0,function*(){try{return yield(i=>V(void 0,void 0,void 0,function*(){const n=[],s=yield vs({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<vh.length;r++){const[a,l]=vh[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return _n(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return V(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=Ou(e,["micId","micLabel"]);return X0(s),this._audioConstraints=yield((o,r,a,l)=>V(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield _s(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,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 i=this.options.env==="development";this._iceServers=i?S0:w0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=fn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=fn(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new G0({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return V(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new q0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Or(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return V(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new z0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Or(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ni.setStateTelnyx(e)}}Ss.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class Rh{constructor(e,i){this.code=i,this.message=e}}class db{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new $0(e,i);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*(e=2,i=6,Math.floor(Math.random()*(i-e+1)+e));var e,i}handleMessage(e){var i,n,s,o,r,a,l,c,u,d,h;const{session:p}=this;p.setPingReceived();const{id:_,method:v,params:b={},voice_sdk_id:w}=e,C=b==null?void 0:b.callID,k=b==null?void 0:b.eventChannel,L=b==null?void 0:b.eventType,R=p.calls[C],O=(i=R==null?void 0:R.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),T=new Set(Object.keys(p.calls));if(Array.isArray(b==null?void 0:b.reattached_sessions)&&T.size){y.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=b.reattached_sessions.length===0,S=b.reattached_sessions.some(I=>T.has(I));if(f||!S)for(const I of Object.keys(p.calls)){const A=p.calls[I];y.debug(`Session not reattached — terminating active call ${I} `);const x=ne(Vu);B(P.Error,{error:x,callId:I,sessionId:p.sessionid},p.uuid),A.hangup({},!1)}}if(Array.isArray(b==null?void 0:b.reattached_sessions)&&p.sessionid){const f=ih();if(f&&f.calls.length>0)if(f.sessionId!==p.sessionid)y.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${p.sessionid}) — ignoring all.`),ei();else{const S=new Set(b.reattached_sessions),I=[];for(const A of f.calls)try{if(S.has(A.id)){y.debug(`Recovery marker for call ${A.id} was reattached — keeping for Attach element restore.`),I.push(A);continue}y.info(`Recovery marker for call ${A.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const x=ne(Vu);B(P.Error,{error:x,callId:A.id,sessionId:p.sessionid,customHeaders:A.customHeaders},p.uuid)}catch(x){y.debug(`Recovery marker for a saved call failed to process (callId=${A==null?void 0:A.id}) — skipping: ${x instanceof Error?x.message:String(x)}`),I.push(A)}nh(I,f.sessionId,f.storedAt)}}if(L==="channelPvtData")return this._handlePvtEvent(b.pvtData);const E=({recoveredCallId:f,forceRelayCandidateForRecovery:S,mutedMicOnStart:I,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N}={})=>{var M,F,G,U,ae;const q={audio:!0,video:p.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Z.Attach,mediaSettings:b.mediaSettings,debug:(M=p.options.debug)!==null&&M!==void 0&&M,debugOutput:(F=p.options.debugOutput)!==null&&F!==void 0?F:"socket",trickleIce:(G=p.options.trickleIce)!==null&&G!==void 0&&G,prefetchIceCandidates:(U=p.options.prefetchIceCandidates)===null||U===void 0||U,forceRelayCandidate:S||p.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(ae=p.options.keepConnectionAliveOnSocketClose)!==null&&ae!==void 0&&ae,mutedMicOnStart:I??p.options.mutedMicOnStart};C&&(q.id=C),b.telnyx_call_control_id&&(q.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(q.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(q.telnyxLegId=b.telnyx_leg_id),b.client_state&&(q.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(q.customHeaders=b.dialogParams.custom_headers),f&&(q.recoveredCallId=f),N&&(q.wasHeldBeforeRecovery=N),A!==void 0&&(q.remoteElement=A),x!==void 0&&(q.localElement=x),performance.mark(re(q.id,"new-call-start"));const H=new ni(p,q);return H.nodeId=this.nodeId,H},g=new ch(w),m=new Ar(w);switch(v){case Z.Answer:case Z.Display:case Z.Candidate:case Z.Ringing:case Z.Bye:case Z.Media:if(!C||!R)return void y.error(`Received ${v} for non existing call:`,b);R.handleMessage(e),this._ack(_,v);break;case Z.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Z.Punt:p.options.keepConnectionAliveOnSocketClose&&O?(y.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(_,v)):(y.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Z.Invite:{const I=E();I.direction=_t.Inbound,I.playRingtone(),I.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(I.id),this._ack(_,v);break}case Z.Attach:{const I=R||null;if(Object.keys(p.calls).length===0){let A,x;y.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`);let N=!1;const M=ih();if(M&&M.sessionId===p.sessionid){const G=M.calls.find(U=>U.id===C);G&&(A=G.remoteElement,x=G.localElement,N=G.wasHeld===!0,(A||x)&&y.info(`[${C}] Attach: restoring per-call media elements from recovery marker (remoteElement=${A??"<none>"}, localElement=${x??"<none>"}).`))}const F=E({recoveredCallId:C,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N});F.answer(),this.session.emitMultipleActiveCallsWarning(F.id),this._ack(_,v);break}if(I){const A=I.id,x=(s=(n=I.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(I))!==null&&s!==void 0&&s,N=I.state==="held";x&&y.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),y.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${A}.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const M=E({recoveredCallId:A,forceRelayCandidateForRecovery:x,mutedMicOnStart:I.isAudioMuted,remoteElement:I.options.remoteElement,localElement:I.options.localElement,wasHeldBeforeRecovery:N});M.answer(),this.session.emitMultipleActiveCallsWarning(M.id),this._ack(_,v);break}y.warn(`Attach: callID ${C} does not match any active calls. `),B(P.Warning,{warning:Ne(u0),callId:C,params:b,sessionId:p.sessionid},p.uuid),this._ack(_,v);break}case Z.Event:case"webrtc.event":if(!k)return void y.error("Verto received an unknown event:",b);const f=p.relayProtocol,S=k.split(".")[0];p._existsSubscription(f,k)?B(f,b,k):k===p.sessionid?this._handleSessionEvent(b.eventData):p._existsSubscription(f,S)?B(f,b,S):p.calls.hasOwnProperty(k)?p.calls[k].handleMessage(e):B(P.Notification,b,p.uuid);break;case Z.Info:b.type=st.generic,B(P.Notification,b,p.uuid);break;case Z.ClientReady:this.session.execute(g);break;case"ai_conversation":B(P.AIConversationMessage,{method:"ai_conversation",params:b,voice_sdk_id:w},p.uuid);break;default:{const I=Cr(e);if(I){switch(I){case Oe.REGISTER:case Oe.REGED:if(!this.isDuplicateGatewayState(I,[Oe.REGED,Oe.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,I===Oe.REGED&&this.session.resetReconnectAttempts();const A=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.call_report_id;A&&(p.callReportId=A,y.debug("Captured call_report_id from REGED:",A));const x=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;x&&(p.dc=x);const N=(u=(c=e==null?void 0:e.result)===null||c===void 0?void 0:c.params)===null||u===void 0?void 0:u.region;N&&(p.region=N),y.info(`Connected to Telnyx — region: ${(d=p.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),b.type=st.vertoClientReady,B(P.Ready,b,p.uuid)}break;case Oe.UNREGED:case Oe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const A=new Rh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),x=ne(Bu,A);B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{this.session.execute(g)},this.reconnectDelay());break;case Oe.FAILED:case Oe.FAIL_WAIT:case Oe.TIMEOUT:if(!this.isDuplicateGatewayState(I,[Oe.FAILED,Oe.FAIL_WAIT,Oe.TIMEOUT])){const A=ne(Hy,new Error(`Gateway state: ${I}`));if(B(P.Error,{error:A,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,y.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${p.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const x=new Rh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const N=ne(br,x);B(P.Error,{error:N,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const x=ne(br,new Error("Connection Retry Failed"));B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{if(y.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some(x=>{var N;return((N=x.peer)===null||N===void 0?void 0:N.instance)&&!x.signalingStateClosed}))return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();y.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:y.warn("GatewayState message unknown method:",e)}break}y.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&y.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return V(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const w=h||this._retrieveCallId(b,o);if(w&&i.calls.hasOwnProperty(w)){const C=i.calls[w];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(_).catch(b=>{y.error("liveArray subscription error:",b);const w=ne(Uy,b);B(P.Error,{error:w,sessionId:i.sessionid},i.uuid)});Dr(v,o)&&p();break}case"conference-liveArray-part":{let p=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(p=i.calls[v]||null,v!==null){const b={type:st.conferenceUpdate,action:Ye.Leave,conferenceName:r,participantId:Number(u),role:d};B(P.Notification,b,v,!1)||B(P.Notification,b,i.uuid),p===null&&bt(P.Notification,null,v)}}const _=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{y.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Th(this.session,e);break;case"logo-info":{const i={type:st.conferenceUpdate,action:Ye.LogoInfo,logo:e.logoURL};B(P.Notification,i,this.session.uuid);break}}}}class ub extends Ss{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new db(this),window.addEventListener("beforeunload",i=>{if(y.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return th(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(y.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));this.calls&&Object.keys(this.calls).forEach(n=>{const s=this.calls[n];s!=null&&s.flushIntermediateCallReport&&(y.debug(`beforeunload: flushing call report for ${n}.`),s.flushIntermediateCallReport({type:"page-unload"}))});try{const n=(this.calls?Object.keys(this.calls):[]).filter(s=>!!this.calls[s]).map(s=>this.calls[s]).map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders};return s.state==="held"&&(o.wasHeld=!0),typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(!this.sessionid||n.length===0)return y.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void ei();y.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),nh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];y.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${s.join(", ")}]): ${n instanceof Error?n.message:String(n)}`)}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(y.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),kr(this.sessionid))})}validateOptions(){return ds(this.options)||pn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ne(By,void 0,"Error: destinationNumber is required");const i=new ni(this,e);return e.id||y.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(re(i.id,"new-call-start")),i.invite(),i}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!pn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return V(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),ds(this.options)?this.handleLoginOnSocketOpen():pn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class hb extends ub{constructor(e){super(e),y.info(`SDK version: ${dh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return J0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ee.not_supported},{browserName:"Firefox",supported:Ee.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",features:["audio"],supported:Ee.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",features:["audio"],supported:Ee.partial}]}]}}function fb(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const i=e;return i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"&&typeof i.arguments=="string"}function Ah(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var xh={exports:{}},Lh;function pb(){return Lh||(Lh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||l,h),_=i?i+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],p]:l._events[_].push(p):(l._events[_]=p,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,p=new Array(h);d<h;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,p){var _=i?i+l:l;if(!this._events[_])return!1;var v=this._events[_],b=arguments.length,w,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){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,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,p),!0}for(C=1,w=new Array(b-1);C<b;C++)w[C-1]=arguments[C];v.fn.apply(v.context,w)}else{var k=v.length,L;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!w)for(L=1,w=new Array(b-1);L<b;L++)w[L-1]=arguments[L];v[C].fn.apply(v[C].context,w)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var _=0,v=[],b=p.length;_<b;_++)(p[_].fn!==c||d&&!p[_].once||u&&p[_].context!==u)&&v.push(p[_]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=i?i+l:l,this._events[c]&&r(this,c)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(xh)),xh.exports}var gb=pb();const Nr=Ah(gb),Fr=new Nr;var Br={exports:{}},mb=Br.exports,Dh;function vb(){return Dh||(Dh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(mb,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var w=s[b];this[w]=b<v?e:this.methodFactory(w,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,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 b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Br)),Br.exports}var _b=vb();const yb=Ah(_b),bb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=yb.getLogger("telnyx-ai-agent"),wb=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=wb(t,e,i);return function(...s){n(bb(),"-",...s)}},fe.setLevel("info");function Sb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Cb=10,Tb=500,Eb=100,kb=300,Oh=20;class Ib{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,"remoteSilenceStartTime",null);j(this,"remoteSilenceThresholdMs");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",Sb(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Fr.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Cb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Tb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Eb,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??kb}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,i;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(i=this.remoteAudioContext)==null||i.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,i;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(i=this.localAudioContext)==null||i.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,this.remoteSilenceStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){fe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,fe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(fe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;fe.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 i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let n=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(i);const o=i.reduce((l,c)=>l+c,0)/i.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&fe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(this.remoteSilenceStartTime=null,n)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.remoteSilenceStartTime===null&&(this.remoteSilenceStartTime=performance.now()),performance.now()-this.remoteSilenceStartTime>=this.remoteSilenceThresholdMs&&this.updateAgentState({state:"listening"}));n=r};this.remoteIntervalId=window.setInterval(s,Oh)}startLocalMonitor(){if(!this.localStream){fe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,fe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(fe.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),i=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const n=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&fe.debug("Local audio volume:",n),n>=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(i,Oh)}destroy(){this.stopAudioStreamMonitor()}}function Rb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Ab(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function xb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Vr(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Lb(t){if(!Vr(t))return null;const e=t.params;return fb(e)?e.item:null}function Db(t){if(!Vr(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const n of e.client_side_tools)if(n&&typeof n=="object"&&typeof n.name=="string"){const s=n;i.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return i}function Ob(t){if(!Vr(t))return null;const e=t.params;if(!e||typeof e!="object")return null;const i=e;if(i.type==="response.audio.delta"){const n=i.format;if(!n||typeof n!="object")return null;const s=n;return typeof i.response_id!="string"||typeof i.delta!="string"||typeof i.sequence!="number"||!Number.isInteger(i.sequence)||typeof s.encoding!="string"||typeof s.sample_rate!="number"||typeof s.channels!="number"?null:{type:"response.audio.delta",response_id:i.response_id,item_id:typeof i.item_id=="string"?i.item_id:void 0,sequence:i.sequence,delta:i.delta,format:{encoding:s.encoding,sample_rate:s.sample_rate,channels:s.channels}}}return i.type==="response.audio.done"&&typeof i.response_id=="string"?{type:"response.audio.done",response_id:i.response_id}:i.type==="response.audio.interrupted"?{type:"response.audio.interrupted",response_id:typeof i.response_id=="string"?i.response_id:void 0}:null}function Mb(t){var i;if(!t||typeof t!="object")return!1;const e=t;return((i=e.params)==null?void 0:i.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const Pb=3e4;function Nb(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function Ur(t){return JSON.stringify({error:t})}class Fb{constructor(e){j(this,"registry",new Map);j(this,"toolTimeouts",new Map);j(this,"inFlight",new Set);j(this,"completed",new Set);j(this,"generation",0);j(this,"getActiveCall");j(this,"timeoutMs");j(this,"events");j(this,"handleEvent",e=>{const i=Db(e);if(i){this.ingestToolSettings(i);return}const n=Lb(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Pb,this.events={onInvoked:i=>this.safeEmit(()=>e.events.onInvoked(i)),onCompleted:i=>this.safeEmit(()=>e.events.onCompleted(i)),onError:i=>this.safeEmit(()=>e.events.onError(i))}}safeEmit(e){try{e()}catch(i){fe.warn(`[client-tools] lifecycle listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}register(e,i){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,i)}registerAll(e){for(const[i,n]of Object.entries(e))this.register(i,n)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:i,timeout_ms:n}of e)typeof n=="number"&&n>0&&this.toolTimeouts.set(i,n)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,i){this.generation===i&&this.completed.add(e)}async execute(e){const{call_id:i,name:n}=e;if(this.inFlight.has(i)||this.completed.has(i)){fe.debug(`[client-tools] duplicate function_call ignored (call_id=${i})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(n);if(!r){fe.warn(`[client-tools] no handler registered for tool "${n}"`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"unknown_tool"}),this.sendOutput(i,n,Ur("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{fe.warn(`[client-tools] invalid JSON arguments for tool "${n}" (call_id=${i})`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"invalid_arguments"}),this.sendOutput(i,n,Ur("invalid_arguments"),!0,s,o);return}this.inFlight.add(i),this.events.onInvoked({callId:i,toolName:n});const l={callId:i,toolName:n,rawArguments:e.arguments},c=this.toolTimeouts.get(n)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n,c);this.sendOutput(i,n,Nb(u),!1,s,o)}catch(u){const d=u instanceof Mh?"timeout":"handler_error";fe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,Ur(d),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Mh(n,i,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){fe.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){fe.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}if(!r||a!==r){fe.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:n}),this.events.onCompleted({callId:e,toolName:i,isError:s})}catch(l){fe.warn(`[client-tools] failed to send output for "${i}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:i,reason:"shutdown"})}}}class Mh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}class Bb{constructor(e){j(this,"enabled");j(this,"getActiveCall");j(this,"events");j(this,"subscriptionConfirmed",!1);j(this,"handleEvent",e=>{if(!this.enabled)return;this.subscriptionConfirmed||this.sendSubscription();const i=Ob(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Vb(i.delta)}catch(s){fe.warn(`[streaming-audio] invalid base64 delta for response ${i.response_id}: ${s instanceof Error?s.message:"unknown error"}`);return}this.emitSafely(()=>this.events.onDelta({responseId:i.response_id,itemId:i.item_id,sequence:i.sequence,audio:n,format:{encoding:i.format.encoding,sampleRate:i.format.sample_rate,channels:i.format.channels}}));return}if(i.type==="response.audio.done"){this.emitSafely(()=>this.events.onDone({responseId:i.response_id}));return}this.emitSafely(()=>this.events.onInterrupted({responseId:i.response_id}))}});this.enabled=e.enabled,this.getActiveCall=e.getActiveCall,this.events=e.events}onCallActive(){this.subscriptionConfirmed=!1,this.sendSubscription()}reset(){this.subscriptionConfirmed=!1}sendSubscription(){if(!this.enabled)return;const e=this.getActiveCall();if(e)try{const i={type:"response.audio_stream.subscribe"};e.sendAIConversationMessage(i)}catch(i){fe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){fe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}}function Vb(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Ub(t){return Ab(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function $b(t){if(!xb(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",i=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((n,s)=>(s.type==="text"&&(n+=s.text),n),""),i=t.params.item.content.reduce((n,s)=>(s.type==="image_url"&&s.image_url.url&&n.push({type:"image",url:s.image_url.url}),n),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:i}}class jb extends Nr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcript",[]);j(this,"onSocketMessage",i=>{if(Rb(i))switch(i.params.type){case"response.text.delta":{const n=Ub(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Mb(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=$b(i);if(n){const s=this.transcript.findIndex(o=>o.id===n.id);s!==-1?this.transcript[s]=n:this.transcript.push(n),this.emit("transcript.item",n)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage)}}const Dt=t=>typeof t=="object"&&t!==null,Ph=t=>{const e=Dt(t)&&Dt(t.result)?t.result:t;if(!(!Dt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Hb=t=>Dt(t)&&Dt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Wb=(t,e)=>{if(!e||!Dt(t)||!Dt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Dt(i.params))return;const n=i.params;Dt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class Gb extends Nr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcription");j(this,"removeLoginSuccessHook",null);j(this,"authenticated",!1);j(this,"authenticating",!1);j(this,"agentId");j(this,"versionId");j(this,"widgetVersion");j(this,"conversationId");j(this,"debug");j(this,"audioStreamMonitor");j(this,"clientTools");j(this,"streamingAudio");j(this,"activeCall");j(this,"chatMode");j(this,"dc",null);j(this,"region",null);j(this,"callReportId",null);j(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});j(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});j(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});j(this,"onSocketMessage",i=>{const n=Ph(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});j(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,this.streamingAudio.onCallActive(),i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.streamingAudio.reset(),this.audioStreamMonitor.stopAudioStreamMonitor()))});j(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});j(this,"onAgentStateChange",i=>{this.emit("conversation.agent.state",i)});this.agentId=i.agentId,this.versionId=i.versionId||"main",this.widgetVersion=i.widgetVersion,this.conversationId=i.conversationId,this.debug=i.debug||!1,this.chatMode=i.chatMode||!1,this.activeCall=null,fe.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId};i.conversationId&&(n.target_params={conversation_id:i.conversationId}),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new hb({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(P.Ready,this.onClientReady),this.telnyxRTC.on(P.Error,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketClose,this.onSocketClose),this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(P.Notification,this.onNotification),this.transcription=new jb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Fr.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Ib(i.vad),this.clientTools=new Fb({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:s=>this.emit("client.tool.invoked",s),onCompleted:s=>this.emit("client.tool.completed",s),onError:s=>this.emit("client.tool.error",s)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(P.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new Bb({enabled:i.streamingAudio??!1,getActiveCall:()=>this.activeCall,events:{onDelta:s=>this.emit("assistant.audio.delta",s),onDone:s=>this.emit("assistant.audio.done",s),onInterrupted:s=>this.emit("assistant.audio.interrupted",s)}}),this.telnyxRTC.on(P.AIConversationMessage,this.streamingAudio.handleEvent)}registerClientTool(i,n){this.clientTools.register(i,n)}unregisterClientTool(i){return this.clientTools.unregister(i)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var i;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(P.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(P.AIConversationMessage,this.streamingAudio.handleEvent),this.clientTools.reset(),this.streamingAudio.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(P.Ready,this.onClientReady),this.telnyxRTC.off(P.Error,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketClose,this.onSocketClose),this.telnyxRTC.off(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(P.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),Fr.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){fe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(i,n)}get transcript(){return this.transcription.transcript}async startConversation(i){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw fe.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw fe.warn(d.message),this.emit("agent.error",d),d}const n=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=i||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[n],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var i;return(i=this.activeCall)==null?void 0:i.hangup()}setRemoteStream(i){this.audioStreamMonitor.setRemoteStream(i)}installLoginSuccessHook(){const i=this.telnyxRTC,n=i.execute,s=i.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=p=>{c===p&&(this.authenticating=!1)},d=function(p){const _=Hb(p),v=c;return _&&Wb(p,a),n.call(this,p).then(b=>{const w=_?Ph(b):void 0;return l&&w!==void 0&&(u(v),r({sessionId:w})),b})},h=function(p){const _=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&i.login===h&&u(_)})};return i.execute=d,i.login=h,()=>{l=!1,i.execute===d&&(i.execute=n),i.login===h&&(i.login=s)}}emitLoginStarted(i){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",i)}emitLoginSuccess(i){const n=this.telnyxRTC,s=n.sessionid||null;i.sessionId&&(n.sessionid=i.sessionId);const o=i.sessionId||n.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}var Nh={exports:{}},bn={},Fh;function qb(){if(Fh)return bn;Fh=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(n,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:n,key:r,ref:s!==void 0?s:null,props:o}}return bn.Fragment=e,bn.jsx=i,bn.jsxs=i,bn}var Bh;function zb(){return Bh||(Bh=1,Nh.exports=qb()),Nh.exports}zb(),kt(void 0),kt(null);const Kb=(t,e,i,n,s,o,r,a,l,c)=>new Gb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Cs=10,Vh=5e3,Yb=[46001,46003],Xb=["login incorrect","authentication required","authentication failed"];function Uh(t){var n;const e=t.code;if(e&&Yb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Xb.some(s=>i.includes(s))}const Jb=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[p,_]=Ae(!1),[v,b]=Ae(null),[w,C]=Ae(!1),k=ue(0),L=ue(null),R=ue(null),O=ue(!1),T=ue(!1),E=ue(0),g=ue(0),m=Ge(()=>{L.current&&(clearTimeout(L.current),L.current=null)},[]),f=Ge(()=>{m(),k.current=0,T.current=!0,C(!1),b(null)},[m]),S=Ge(()=>{m(),C(!1)},[m]),I=Ge(A=>{if(m(),k.current>=Cs){oe.error(`Max login retry attempts (${Cs}) exceeded`),C(!1);return}k.current+=1;const x=E.current,N=g.current;oe.info(`Scheduling login retry attempt ${k.current}/${Cs} in ${Vh}ms due to: ${A}`),C(!0),L.current=window.setTimeout(()=>{var G;L.current=null;const M=R.current,F=M==null?void 0:M.telnyxRTC;if(E.current!==x||g.current!==N||M!=null&&M.isAuthenticating){oe.info("Skipping login retry because a newer socket/login is already in progress"),S();return}if(O.current||T.current||M!=null&&M.isAuthenticated){oe.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(oe.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(G=F==null?void 0:F.socketDisconnect)==null||G.call(F))},Vh)},[m,S,f]);return xe(()=>{if(!t)return;const A=Kb(t,e,i,n,s,o,r,a,l,u);O.current=!1,T.current=!1,_(!1),b(null),C(!1),R.current=A;const x=()=>{oe.info("Agent connected successfully"),O.current=!0,_(!0),f()},N=()=>{oe.info("Agent disconnected"),O.current=!1,T.current=!1,_(!1)},M=H=>{if(oe.error("AI Agent error:",H),Uh(H)){if(O.current||T.current){oe.debug("Ignoring retryable error — login already succeeded");return}k.current<Cs?(b(null),I(H.message)):(b(H),C(!1))}else b(H),C(!1)},F=A.telnyxRTC??null,G=()=>{g.current+=1,T.current=!1},U=()=>{oe.info("Login succeeded; clearing pending login retry flow"),f()},ae=()=>{E.current+=1,T.current=!1},q=()=>{T.current=!1};return A.on("agent.connected",x),A.on("agent.disconnected",N),A.on("agent.error",M),A.on("agent.login.started",G),A.on("agent.login.success",U),F&&typeof F=="object"&&(F.on(P.SocketOpen,ae),F.on(P.SocketClose,q)),A.connect(),h(A),()=>{m(),A.off("agent.connected",x),A.off("agent.disconnected",N),A.off("agent.error",M),A.off("agent.login.started",G),A.off("agent.login.success",U),F&&typeof F=="object"&&(F.off(P.SocketOpen,ae),F.off(P.SocketClose,q)),A.disconnect(),O.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:p,error:v,isReconnecting:w}},Zb="telnyx-ai-agent",Xe={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error",CLIENT_TOOLS_CONFIGURED:"client.tools.configured"};function Qb(t){var n,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;i.push({name:r.name,description:(n=r.client_side_tool)==null?void 0:n.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return i}function $h(){const t=document.querySelector(Zb);return t instanceof HTMLElement?t:null}function wt(t,e,i){const n=i||$h();if(!n){oe.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),oe.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const ew=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=Mn(_u);xe(()=>{const c=i==null?void 0:i.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??$h()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const O=t.telnyxRTC,T={dc:(O==null?void 0:O.dc)??null,region:(O==null?void 0:O.region)??null,callReportId:(O==null?void 0:O.callReportId)??null};l(T),wt(Xe.AGENT_CONNECTED,T,c)},d=()=>{l(null),wt(Xe.AGENT_DISCONNECTED,void 0,c)},h=R=>{const O={message:R.message,name:R.name};if(Uh(R)){oe.debug("Ignoring retryable agent.error in widget event layer"),wt(Xe.AGENT_ERROR,O,c);return}o(R),wt(Xe.AGENT_ERROR,O,c)},p=R=>{var O;s(R),wt(Xe.CONVERSATION_UPDATE,{type:R.type,callState:(O=R.call)==null?void 0:O.state},c)},_=R=>{wt(Xe.TRANSCRIPT_ITEM,R,c)},v=R=>{wt(Xe.CONVERSATION_AGENT_STATE,R,c)},b=R=>{wt(Xe.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const O=Qb(R);O&&wt(Xe.CLIENT_TOOLS_CONFIGURED,{tools:O},c)},L=R=>{const O=R,T={code:O==null?void 0:O.code,reason:O==null?void 0:O.reason,wasClean:O==null?void 0:O.wasClean,timestamp:new Date().toISOString()};oe.info("[socket.close]",T),wt(Xe.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(P.SocketMessage,k),C.on(P.SocketClose,L)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",_),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",_),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),C&&typeof C=="object"&&(C.off(P.SocketMessage,k),C.off(P.SocketClose,L))}},[t,n,s,o,r,l])},tw=2e3;async function iw(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function jh(t){const e=t.split("-"),i=e[e.length-1];return i&&i.length===13&&/^\d+$/.test(i)?e.slice(0,-1).join("-"):t}const nw=(t,e)=>{const[i,n]=Ae([]),[,s]=cr(),o=ue(e);xe(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return xe(()=>{if(!t)return;const c=h=>{n(p=>{const _=p[p.length-1];if(h.role==="assistant"&&_&&jh(_.id)===jh(h.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,w={..._,content:_.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...p.slice(0,-1),w]}if(h.role==="assistant"){s(w=>w==="thinking"||w==="processing_image"?"speaking":w);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const w={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,w]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(w=>w.id===h.id);if(v!==-1){const w=[...p];return w[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},w}if(_&&_.role==="user"&&h.timestamp.getTime()-_.timestamp.getTime()<tw){const C={..._,id:h.id,content:_.content+" "+h.content,timestamp:h.timestamp,attachments:[..._.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...p,h]})},u=({state:h,userPerceivedLatencyMs:p,greetingLatencyMs:_,thinkingStartedAt:v})=>{(p!==void 0||_!==void 0)&&oe.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${_} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),_!==void 0&&(a.current=_)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var _;const p=(_=h.call)==null?void 0:_.state;(p==="destroy"||p==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const p=await iw(h);d.push(p)}catch(p){throw oe.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Mi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class sw{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,i){var n;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,i),oe.debug(`[client-tools] registered handler "${e}"`),(n=this.agent)==null||n.registerClientTool(e,i)}unregister(e){var n;const i=this.handlers.delete(e);return i&&(oe.debug(`[client-tools] unregistered handler "${e}"`),(n=this.agent)==null||n.unregisterClientTool(e)),i}list(){return Array.from(this.handlers.keys())}attach(e,i){this.detach(),this.agent=e,this.listeners=i;for(const[n,s]of this.handlers)e.registerClientTool(n,s);this.boundInvoked=n=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(n)},this.boundCompleted=n=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(n)},this.boundError=n=>{var s;return(s=this.listeners)==null?void 0:s.onError(n)},e.on(Mi.INVOKED,this.boundInvoked),e.on(Mi.COMPLETED,this.boundCompleted),e.on(Mi.ERROR,this.boundError),this.handlers.size>0&&oe.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Mi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Mi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Mi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function $r(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const ow=(t,e)=>{const i=ue(null);i.current===null&&(i.current=new sw),Fs(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){oe.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=i.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),xe(()=>{const n=i.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return n.attach(t,{onInvoked:o=>{$r(s(),Xe.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{$r(s(),Xe.CLIENT_TOOL_COMPLETED,o)},onError:o=>{$r(s(),Xe.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},rw=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=Qt(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=nw(e,i),d=ue(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,oe.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[n,t]),r){case"collapsed":return D(ku,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(Iy,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(ku,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},jr=()=>D(Si.div,{layoutId:dn,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:D("div",{className:"rounded-full animate-spin",children:D(J_,{})})}),aw=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(jr,{});case"done":case"purged":case"destroy":return null;case"active":return D(rw,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(jr,{})}},lw=({className:t})=>D("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:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Hh(){const t=Qt();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(lw,{className:"w-8 h-8 mr-2"})}const cw=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=ue(!1),r=Ge(async()=>{if(!t){oe.error("Client is not initialized.");return}if(!n){oe.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){oe.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,oe.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(Si.div,{layoutId:dn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[D(Hh,{}),"Connecting..."]}):D(Si.button,{layoutId:dn,onClick:r,disabled:!n,"aria-busy":!n,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D(Hh,{}),s.start_call_text]})},dw='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@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)}}',uw=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),hw={duration:.1,ease:"circOut"},fw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?D(uw,{children:t}):t;return D("div",{ref:i,className:At(n.theme==="dark"&&"dark"),children:D(jg,{transition:hw,children:[D("style",{children:dw}),o]})})},pw=t=>D(Si.div,{layoutId:dn,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:[D(Y_,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("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"," ",D(sy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(iy,{className:"w-4 h-4"}),"Retry"]})]});function Pi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function gw({"agent-id":t,debug:e,"trickle-ice":i,"call-destination-number":n,"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":u,"conversation-id":d,"chat-mode":h,region:p,"skip-last-voice-sdk-id":_,environment:v,position:b="fixed","version-id":w}){const C=Pi(e),k=Pi(i),L=Pi(h),R=_===void 0?!0:Pi(_),O=Qe(()=>{if(l)try{return JSON.parse(l)}catch(he){oe.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Qe(()=>({showUserPerceivedLatency:Pi(c),showGreetingLatency:Pi(u)}),[c,u]),{client:E,error:g,isConnected:m,isReconnecting:f}=Jb(t,v,w,C,k,O,d,L,p,R),[S,I]=Ae(null),[A,x]=Ae(!1),[N,M]=Ae(!1),[F,G]=Ae(!1),[U,ae]=Ae(!1),q=Mn(Tu),H=S_(),ce={};if(n&&(ce.destinationNumber=n),s&&(ce.callerNumber=s),o&&(ce.callerName=o),r)try{ce.customHeaders=JSON.parse(r)}catch(he){oe.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{ce.audio=JSON.parse(a);const he=ce.audio;if(typeof he=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(ge=>{se[ge]||oe.warn(`Audio constraint not supported by browser: ${ge}`)})}}catch(he){oe.error("Invalid JSON for call-audio attribute:",a,he)}const J=Ge(()=>{x(!1)},[]),ee=Ge(he=>{var se;if(((se=he.call)==null?void 0:se.state)==="destroy")return q(!1),ae(!0),I(null);I(he)},[q]),te=Ge(()=>{x(!1),f||M(!0)},[f]),ie=Ge(()=>{oe.info("User triggered retry"),M(!1),x(!0),E&&E.connect()},[E]),me=Ge(he=>{if(w_(he)){const se=he.params.widget_settings;se&&Object.keys(se).length>0&&(H(se),G(!0))}},[H]),Le=ue(null);return ew(E,{onReady:J,onConversationUpdate:ee,onError:te,onConfigMessage:me},Le),ow(E,Le),D(fw,{position:b,rootRef:Le,children:t?N||g?D(pw,{agentId:t,onRetry:ie}):A||f?D(jr,{message:f?"Retrying...":void 0}):S!=null&&S.call?D(aw,{call:S.call,client:E,latencySettings:T,chatMode:L,debug:C}):F?D(cw,{client:E,callProps:ce,chatMode:L&&!U,isReady:m&&!!E}):null:D("div",{children:"Please provide an assistant ID."})})}af(gw,"telnyx-ai-agent",y_,{shadow:!0})})();