(function(ae,ie){typeof exports=="object"&&typeof module<"u"?ie(exports):typeof define=="function"&&define.amd?define(["exports"],ie):(ae=typeof globalThis<"u"?globalThis:ae||self,ie(ae.AnamAgentWidget={}))})(this,(function(ae){"use strict";var ie,O,Tt,Rt,me,Nt,xt,Ot,kt,it,nt,rt,xe={},Dt=[],Pi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,$e=Array.isArray;function ee(t,e){for(var n in e)t[n]=e[n];return t}function ot(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ye(t,e,n){var o,c,s,u={};for(s in e)s=="key"?o=e[s]:s=="ref"?c=e[s]:u[s]=e[s];if(arguments.length>2&&(u.children=arguments.length>3?ie.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)u[s]===void 0&&(u[s]=t.defaultProps[s]);return Oe(t,u,o,c,null)}function Oe(t,e,n,o,c){var s={type:t,props:e,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:c??++Tt,__i:-1,__u:0};return c==null&&O.vnode!=null&&O.vnode(s),s}function le(t){return t.children}function Se(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Mt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Mt(t)}}function Ut(t){(!t.__d&&(t.__d=!0)&&me.push(t)&&!Ve.__r++||Nt!=O.debounceRendering)&&((Nt=O.debounceRendering)||xt)(Ve)}function Ve(){for(var t,e,n,o,c,s,u,l=1;me.length;)me.length>l&&me.sort(Ot),t=me.shift(),l=me.length,t.__d&&(n=void 0,o=void 0,c=(o=(e=t).__v).__e,s=[],u=[],e.__P&&((n=ee({},o)).__v=o.__v+1,O.vnode&&O.vnode(n),st(e.__P,n,o,e.__n,e.__P.namespaceURI,32&o.__u?[c]:null,s,c??we(o),!!(32&o.__u),u),n.__v=o.__v,n.__.__k[n.__i]=n,$t(s,n,u),o.__e=o.__=null,n.__e!=c&&Mt(n)));Ve.__r=0}function Lt(t,e,n,o,c,s,u,l,E,p,_){var d,y,g,S,C,A,I,b=o&&o.__k||Dt,T=e.length;for(E=Fi(n,e,b,E,T),d=0;d<T;d++)(g=n.__k[d])!=null&&(y=g.__i==-1?xe:b[g.__i]||xe,g.__i=d,A=st(t,g,y,c,s,u,l,E,p,_),S=g.__e,g.ref&&y.ref!=g.ref&&(y.ref&&lt(y.ref,null,g),_.push(g.ref,g.__c||S,g)),C==null&&S!=null&&(C=S),(I=!!(4&g.__u))||y.__k===g.__k?E=Bt(g,E,t,I):typeof g.type=="function"&&A!==void 0?E=A:S&&(E=S.nextSibling),g.__u&=-7);return n.__e=C,E}function Fi(t,e,n,o,c){var s,u,l,E,p,_=n.length,d=_,y=0;for(t.__k=new Array(c),s=0;s<c;s++)(u=e[s])!=null&&typeof u!="boolean"&&typeof u!="function"?(typeof u=="string"||typeof u=="number"||typeof u=="bigint"||u.constructor==String?u=t.__k[s]=Oe(null,u,null,null,null):$e(u)?u=t.__k[s]=Oe(le,{children:u},null,null,null):u.constructor===void 0&&u.__b>0?u=t.__k[s]=Oe(u.type,u.props,u.key,u.ref?u.ref:null,u.__v):t.__k[s]=u,E=s+y,u.__=t,u.__b=t.__b+1,l=null,(p=u.__i=$i(u,n,E,d))!=-1&&(d--,(l=n[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(c>_?y--:c<_&&y++),typeof u.type!="function"&&(u.__u|=4)):p!=E&&(p==E-1?y--:p==E+1?y++:(p>E?y--:y++,u.__u|=4))):t.__k[s]=null;if(d)for(s=0;s<_;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=we(l)),Gt(l,l));return o}function Bt(t,e,n,o){var c,s;if(typeof t.type=="function"){for(c=t.__k,s=0;c&&s<c.length;s++)c[s]&&(c[s].__=t,e=Bt(c[s],e,n,o));return e}t.__e!=e&&(o&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function $i(t,e,n,o){var c,s,u,l=t.key,E=t.type,p=e[n],_=p!=null&&(2&p.__u)==0;if(p===null&&l==null||_&&l==p.key&&E==p.type)return n;if(o>(_?1:0)){for(c=n-1,s=n+1;c>=0||s<e.length;)if((p=e[u=c>=0?c--:s++])!=null&&(2&p.__u)==0&&l==p.key&&E==p.type)return u}return-1}function Pt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Pi.test(e)?n:n+"px"}function Ge(t,e,n,o,c){var s,u;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof o=="string"&&(t.style.cssText=o=""),o)for(e in o)n&&e in n||Pt(t.style,e,"");if(n)for(e in n)o&&n[e]==o[e]||Pt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(kt,"$1")),u=e.toLowerCase(),e=u in t||e=="onFocusOut"||e=="onFocusIn"?u.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?o?n.u=o.u:(n.u=it,t.addEventListener(e,s?rt:nt,s)):t.removeEventListener(e,s?rt:nt,s);else{if(c=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Ft(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=it++;else if(e.t<n.u)return;return n(O.event?O.event(e):e)}}}function st(t,e,n,o,c,s,u,l,E,p){var _,d,y,g,S,C,A,I,b,T,D,N,Y,re,V,oe,se,Z=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(E=!!(32&n.__u),s=[l=e.__e=n.__e]),(_=O.__b)&&_(e);e:if(typeof Z=="function")try{if(I=e.props,b="prototype"in Z&&Z.prototype.render,T=(_=Z.contextType)&&o[_.__c],D=_?T?T.props.value:_.__:o,n.__c?A=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new Z(I,D):(e.__c=d=new Se(I,D),d.constructor=Z,d.render=Gi),T&&T.sub(d),d.state||(d.state={}),d.__n=o,y=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&Z.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ee({},d.__s)),ee(d.__s,Z.getDerivedStateFromProps(I,d.__s))),g=d.props,S=d.state,d.__v=e,y)b&&Z.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&Z.getDerivedStateFromProps==null&&I!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(I,D),e.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(I,d.__s,D)===!1){for(e.__v!=n.__v&&(d.props=I,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(_e){_e&&(_e.__=e)}),N=0;N<d._sb.length;N++)d.__h.push(d._sb[N]);d._sb=[],d.__h.length&&u.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(I,d.__s,D),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,S,C)})}if(d.context=D,d.props=I,d.__P=t,d.__e=!1,Y=O.__r,re=0,b){for(d.state=d.__s,d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),V=0;V<d._sb.length;V++)d.__h.push(d._sb[V]);d._sb=[]}else do d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++re<25);d.state=d.__s,d.getChildContext!=null&&(o=ee(ee({},o),d.getChildContext())),b&&!y&&d.getSnapshotBeforeUpdate!=null&&(C=d.getSnapshotBeforeUpdate(g,S)),oe=_,_!=null&&_.type===le&&_.key==null&&(oe=Vt(_.props.children)),l=Lt(t,$e(oe)?oe:[oe],e,n,o,c,s,u,l,E,p),d.base=e.__e,e.__u&=-161,d.__h.length&&u.push(d),A&&(d.__E=d.__=null)}catch(_e){if(e.__v=null,E||s!=null)if(_e.then){for(e.__u|=E?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,e.__e=l}else{for(se=s.length;se--;)ot(s[se]);at(e)}else e.__e=n.__e,e.__k=n.__k,_e.then||at(e);O.__e(_e,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Vi(n.__e,e,n,o,c,s,u,E,p);return(_=O.diffed)&&_(e),128&e.__u?void 0:l}function at(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(at)}function $t(t,e,n){for(var o=0;o<n.length;o++)lt(n[o],n[++o],n[++o]);O.__c&&O.__c(e,t),t.some(function(c){try{t=c.__h,c.__h=[],t.some(function(s){s.call(c)})}catch(s){O.__e(s,c.__v)}})}function Vt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:$e(t)?t.map(Vt):ee({},t)}function Vi(t,e,n,o,c,s,u,l,E){var p,_,d,y,g,S,C,A=n.props||xe,I=e.props,b=e.type;if(b=="svg"?c="http://www.w3.org/2000/svg":b=="math"?c="http://www.w3.org/1998/Math/MathML":c||(c="http://www.w3.org/1999/xhtml"),s!=null){for(p=0;p<s.length;p++)if((g=s[p])&&"setAttribute"in g==!!b&&(b?g.localName==b:g.nodeType==3)){t=g,s[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(I);t=document.createElementNS(c,b,I.is&&I),l&&(O.__m&&O.__m(e,s),l=!1),s=null}if(b==null)A===I||l&&t.data==I||(t.data=I);else{if(s=s&&ie.call(t.childNodes),!l&&s!=null)for(A={},p=0;p<t.attributes.length;p++)A[(g=t.attributes[p]).name]=g.value;for(p in A)if(g=A[p],p!="children"){if(p=="dangerouslySetInnerHTML")d=g;else if(!(p in I)){if(p=="value"&&"defaultValue"in I||p=="checked"&&"defaultChecked"in I)continue;Ge(t,p,null,g,c)}}for(p in I)g=I[p],p=="children"?y=g:p=="dangerouslySetInnerHTML"?_=g:p=="value"?S=g:p=="checked"?C=g:l&&typeof g!="function"||A[p]===g||Ge(t,p,g,A[p],c);if(_)l||d&&(_.__html==d.__html||_.__html==t.innerHTML)||(t.innerHTML=_.__html),e.__k=[];else if(d&&(t.innerHTML=""),Lt(e.type=="template"?t.content:t,$e(y)?y:[y],e,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":c,s,u,s?s[0]:n.__k&&we(n,0),l,E),s!=null)for(p=s.length;p--;)ot(s[p]);l||(p="value",b=="progress"&&S==null?t.removeAttribute("value"):S!=null&&(S!==t[p]||b=="progress"&&!S||b=="option"&&S!=A[p])&&Ge(t,p,S,A[p],c),p="checked",C!=null&&C!=t[p]&&Ge(t,p,C,A[p],c))}return t}function lt(t,e,n){try{if(typeof t=="function"){var o=typeof t.__u=="function";o&&t.__u(),o&&e==null||(t.__u=t(e))}else t.current=e}catch(c){O.__e(c,n)}}function Gt(t,e,n){var o,c;if(O.unmount&&O.unmount(t),(o=t.ref)&&(o.current&&o.current!=t.__e||lt(o,null,e)),(o=t.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){O.__e(s,e)}o.base=o.__P=null}if(o=t.__k)for(c=0;c<o.length;c++)o[c]&&Gt(o[c],e,n||typeof t.type!="function");n||ot(t.__e),t.__c=t.__=t.__e=void 0}function Gi(t,e,n){return this.constructor(t,n)}function je(t,e,n){var o,c,s,u;e==document&&(e=document.documentElement),O.__&&O.__(t,e),c=(o=typeof n=="function")?null:n&&n.__k||e.__k,s=[],u=[],st(e,t=(!o&&n||e).__k=ye(le,null,[t]),c||xe,xe,e.namespaceURI,!o&&n?[n]:c?null:e.firstChild?ie.call(e.childNodes):null,s,!o&&n?n:c?c.__e:e.firstChild,o,u),$t(s,t,u)}function jt(t,e){je(t,e,jt)}function Ht(t,e,n){var o,c,s,u,l=ee({},t.props);for(s in t.type&&t.type.defaultProps&&(u=t.type.defaultProps),e)s=="key"?o=e[s]:s=="ref"?c=e[s]:l[s]=e[s]===void 0&&u!=null?u[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?ie.call(arguments,2):n),Oe(t.type,l,o||t.key,c||t.ref,null)}ie=Dt.slice,O={__e:function(t,e,n,o){for(var c,s,u;e=e.__;)if((c=e.__c)&&!c.__)try{if((s=c.constructor)&&s.getDerivedStateFromError!=null&&(c.setState(s.getDerivedStateFromError(t)),u=c.__d),c.componentDidCatch!=null&&(c.componentDidCatch(t,o||{}),u=c.__d),u)return c.__E=c}catch(l){t=l}throw t}},Tt=0,Rt=function(t){return t!=null&&t.constructor===void 0},Se.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ee({},this.state),typeof t=="function"&&(t=t(ee({},n),this.props)),t&&ee(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ut(this))},Se.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ut(this))},Se.prototype.render=le,me=[],xt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ot=function(t,e){return t.__v.__b-e.__v.__b},Ve.__r=0,kt=/(PointerCapture)$|Capture$/i,it=0,nt=Ft(!1),rt=Ft(!0);function He(){return He=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},He.apply(this,arguments)}function Wt(t,e){if(t==null)return{};var n,o,c={},s=Object.keys(t);for(o=0;o<s.length;o++)e.indexOf(n=s[o])>=0||(c[n]=t[n]);return c}var ji=["context","children"],Hi=["useFragment"];function Wi(t,e,n,o){function c(){var s,u=Reflect.construct(HTMLElement,[],c);return u._vdomComponent=t,o&&o.shadow?(u._root=u.attachShadow({mode:o.mode||"open",serializable:(s=o.serializable)!=null&&s}),o.adoptedStyleSheets&&(u._root.adoptedStyleSheets=o.adoptedStyleSheets)):u._root=u,u}return(c.prototype=Object.create(HTMLElement.prototype)).constructor=c,c.prototype.connectedCallback=function(){qi.call(this,o)},c.prototype.attributeChangedCallback=Yi,c.prototype.disconnectedCallback=Ki,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),c.observedAttributes=n,t.formAssociated&&(c.formAssociated=!0),n.forEach(function(s){Object.defineProperty(c.prototype,s,{get:function(){return this._vdom?this._vdom.props[s]:this._props[s]},set:function(u){this._vdom?this.attributeChangedCallback(s,null,u):(this._props||(this._props={}),this._props[s]=u);var l=typeof u;u!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(s,u)}})}),customElements.define(e||t.tagName||t.displayName||t.name,c),c}function zi(t){this.getChildContext=function(){return t.context};var e=t.children,n=Wt(t,ji);return Ht(e,n)}function qi(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=ye(zi,He({},this._props,{context:e.detail.context}),Yt(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?jt:je)(this._vdom,this._root)}function zt(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Yi(t,e,n){if(this._vdom){var o={};o[t]=n=n??void 0,o[zt(t)]=n,this._vdom=Ht(this._vdom,o),je(this._vdom,this._root)}}function Ki(){je(this._vdom=null,this._root)}function qt(t,e){var n=this,o=t.useFragment,c=Wt(t,Hi);return ye(o?le:"slot",He({},c,{ref:function(s){s?(n.ref=s,n._listener||(n._listener=function(u){u.stopPropagation(),u.detail.context=e},s.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Yt(t,e,n){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var o=[],c={},s=0,u=t.attributes,l=t.childNodes;for(s=u.length;s--;)u[s].name!=="slot"&&(c[u[s].name]=u[s].value,c[zt(u[s].name)]=u[s].value);for(s=l.length;s--;){var E=Yt(l[s],null,n),p=l[s].slot;p?c[p]=ye(qt,{name:p},E):o[s]=E}var _=!(!n||!n.shadow),d=e?ye(qt,{useFragment:!_},o):o;return!_&&e&&(t.innerHTML=""),ye(e||t.nodeName.toLowerCase(),c,d)}var Ji=0;function w(t,e,n,o,c,s){e||(e={});var u,l,E=e;if("ref"in E)for(l in E={},e)l=="ref"?u=e[l]:E[l]=e[l];var p={type:t,props:E,key:n,ref:u,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ji,__i:-1,__u:0,__source:c,__self:s};if(typeof t=="function"&&(u=t.defaultProps))for(l in u)E[l]===void 0&&(E[l]=u[l]);return O.vnode&&O.vnode(p),p}var ke,P,ct,Kt,De=0,Jt=[],F=O,Xt=F.__b,Zt=F.__r,Qt=F.diffed,ei=F.__c,ti=F.unmount,ii=F.__;function ut(t,e){F.__h&&F.__h(P,t,De||e),De=0;var n=P.__H||(P.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function We(t){return De=1,Xi(oi,t)}function Xi(t,e,n){var o=ut(ke++,2);if(o.t=t,!o.__c&&(o.__=[oi(void 0,e),function(l){var E=o.__N?o.__N[0]:o.__[0],p=o.t(E,l);E!==p&&(o.__N=[p,o.__[1]],o.__c.setState({}))}],o.__c=P,!P.__f)){var c=function(l,E,p){if(!o.__c.__H)return!0;var _=o.__c.__H.__.filter(function(y){return!!y.__c});if(_.every(function(y){return!y.__N}))return!s||s.call(this,l,E,p);var d=o.__c.props!==l;return _.forEach(function(y){if(y.__N){var g=y.__[0];y.__=y.__N,y.__N=void 0,g!==y.__[0]&&(d=!0)}}),s&&s.call(this,l,E,p)||d};P.__f=!0;var s=P.shouldComponentUpdate,u=P.componentWillUpdate;P.componentWillUpdate=function(l,E,p){if(this.__e){var _=s;s=void 0,c(l,E,p),s=_}u&&u.call(this,l,E,p)},P.shouldComponentUpdate=c}return o.__N||o.__}function ze(t,e){var n=ut(ke++,3);!F.__s&&ri(n.__H,e)&&(n.__=t,n.u=e,P.__H.__h.push(n))}function Me(t){return De=5,Ce(function(){return{current:t}},[])}function Ce(t,e){var n=ut(ke++,7);return ri(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function qe(t,e){return De=8,Ce(function(){return t},e)}function Zi(){for(var t;t=Jt.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Ye),t.__H.__h.forEach(dt),t.__H.__h=[]}catch(e){t.__H.__h=[],F.__e(e,t.__v)}}F.__b=function(t){P=null,Xt&&Xt(t)},F.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ii&&ii(t,e)},F.__r=function(t){Zt&&Zt(t),ke=0;var e=(P=t.__c).__H;e&&(ct===P?(e.__h=[],P.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Ye),e.__h.forEach(dt),e.__h=[],ke=0)),ct=P},F.diffed=function(t){Qt&&Qt(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Jt.push(e)!==1&&Kt===F.requestAnimationFrame||((Kt=F.requestAnimationFrame)||Qi)(Zi)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ct=P=null},F.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Ye),n.__h=n.__h.filter(function(o){return!o.__||dt(o)})}catch(o){e.some(function(c){c.__h&&(c.__h=[])}),e=[],F.__e(o,n.__v)}}),ei&&ei(t,e)},F.unmount=function(t){ti&&ti(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(o){try{Ye(o)}catch(c){e=c}}),n.__H=void 0,e&&F.__e(e,n.__v))};var ni=typeof requestAnimationFrame=="function";function Qi(t){var e,n=function(){clearTimeout(o),ni&&cancelAnimationFrame(e),setTimeout(t)},o=setTimeout(n,35);ni&&(e=requestAnimationFrame(n))}function Ye(t){var e=P,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),P=e}function dt(t){var e=P;t.__c=t.__(),P=e}function ri(t,e){return!t||t.length!==e.length||e.some(function(n,o){return n!==t[o]})}function oi(t,e){return typeof e=="function"?e(t):e}var en=Symbol.for("preact-signals");function Ke(){if(ce>1)ce--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,ht++;n!==void 0;){var o=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&li(n))try{n.c()}catch(c){e||(t=c,e=!0)}n=o}}if(ht=0,ce--,e)throw t}}function tn(t){if(ce>0)return t();ce++;try{return t()}finally{Ke()}}var k=void 0;function si(t){var e=k;k=void 0;try{return t()}finally{k=e}}var Ue=void 0,ce=0,ht=0,Je=0;function ai(t){if(k!==void 0){var e=t.n;if(e===void 0||e.t!==k)return e={i:0,S:t,p:k.s,n:void 0,t:k,e:void 0,x:void 0,r:e},k.s!==void 0&&(k.s.n=e),k.s=e,t.n=e,32&k.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=k.s,e.n=void 0,k.s.n=e,k.s=e),e}}function j(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}j.prototype.brand=en,j.prototype.h=function(){return!0},j.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:si(function(){var o;(o=e.W)==null||o.call(e)}))},j.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,o=t.x;n!==void 0&&(n.x=o,t.e=void 0),o!==void 0&&(o.e=n,t.x=void 0),t===this.t&&(this.t=o,o===void 0&&si(function(){var c;(c=e.Z)==null||c.call(e)}))}},j.prototype.subscribe=function(t){var e=this;return Le(function(){var n=e.value,o=k;k=void 0;try{t(n)}finally{k=o}},{name:"sub"})},j.prototype.valueOf=function(){return this.value},j.prototype.toString=function(){return this.value+""},j.prototype.toJSON=function(){return this.value},j.prototype.peek=function(){var t=k;k=void 0;try{return this.value}finally{k=t}},Object.defineProperty(j.prototype,"value",{get:function(){var t=ai(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(ht>100)throw new Error("Cycle detected");this.v=t,this.i++,Je++,ce++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Ke()}}}});function z(t,e){return new j(t,e)}function li(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function ci(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function ui(t){for(var e=t.s,n=void 0;e!==void 0;){var o=e.p;e.i===-1?(e.S.U(e),o!==void 0&&(o.n=e.n),e.n!==void 0&&(e.n.p=o)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=o}t.s=n}function ge(t,e){j.call(this,void 0),this.x=t,this.s=void 0,this.g=Je-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ge.prototype=new j,ge.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Je))return!0;if(this.g=Je,this.f|=1,this.i>0&&!li(this))return this.f&=-2,!0;var t=k;try{ci(this),k=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return k=t,ui(this),this.f&=-2,!0},ge.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}j.prototype.S.call(this,t)},ge.prototype.U=function(t){if(this.t!==void 0&&(j.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ge.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ge.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=ai(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function di(t,e){return new ge(t,e)}function hi(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ce++;var n=k;k=void 0;try{e()}catch(o){throw t.f&=-2,t.f|=8,ft(t),o}finally{k=n,Ke()}}}function ft(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,hi(t)}function nn(t){if(k!==this)throw new Error("Out-of-order effect");ui(this),k=t,this.f&=-2,8&this.f&&ft(this),Ke()}function Ie(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ie.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ie.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,hi(this),ci(this),ce++;var t=k;return k=this,nn.bind(this,t)},Ie.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ie.prototype.d=function(){this.f|=8,1&this.f||ft(this)},Ie.prototype.dispose=function(){this.d()};function Le(t,e){var n=new Ie(t,e);try{n.c()}catch(c){throw n.d(),c}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var fi,pt,rn=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,pi=[];Le(function(){fi=this.N})();function be(t,e){O[t]=e.bind(null,O[t]||function(){})}function Xe(t){pt&&pt(),pt=t&&t.S()}function _i(t){var e=this,n=t.data,o=Ei(n);o.value=n;var c=Ce(function(){for(var l=e,E=e.__v;E=E.__;)if(E.__c){E.__c.__$f|=4;break}var p=di(function(){var g=o.value.value;return g===0?0:g===!0?"":g||""}),_=di(function(){return!Array.isArray(p.value)&&!Rt(p.value)}),d=Le(function(){if(this.N=mi,_.value){var g=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=g)}}),y=e.__$u.d;return e.__$u.d=function(){d(),y.call(this)},[_,p]},[]),s=c[0],u=c[1];return s.value?u.peek():u.value}_i.displayName="ReactiveTextNode",Object.defineProperties(j.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:_i},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),be("__b",function(t,e){if(typeof e.type=="string"){var n,o=e.props;for(var c in o)if(c!=="children"){var s=o[c];s instanceof j&&(n||(e.__np=n={}),n[c]=s,o[c]=s.peek())}}t(e)}),be("__r",function(t,e){if(e.type!==le){Xe();var n,o=e.__c;o&&(o.__$f&=-2,(n=o.__$u)===void 0&&(o.__$u=n=(function(c,s){var u;return Le(function(){u=this},{name:s}),u.c=c,u})(function(){var c;rn&&((c=n.y)==null||c.call(n)),o.__$f|=1,o.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Xe(n)}t(e)}),be("__e",function(t,e,n,o){Xe(),t(e,n,o)}),be("diffed",function(t,e){Xe();var n;if(typeof e.type=="string"&&(n=e.__e)){var o=e.__np,c=e.props;if(o){var s=n.U;if(s)for(var u in s){var l=s[u];l!==void 0&&!(u in o)&&(l.d(),s[u]=void 0)}else s={},n.U=s;for(var E in o){var p=s[E],_=o[E];p===void 0?(p=on(n,E,_,c),s[E]=p):p.o(_,c)}}}t(e)});function on(t,e,n,o){var c=e in t&&t.ownerSVGElement===void 0,s=z(n);return{o:function(u,l){s.value=u,o=l},d:Le(function(){this.N=mi;var u=s.value.value;o[e]!==u&&(o[e]=u,c?t[e]=u:u!=null&&(u!==!1||e[4]==="-")?t.setAttribute(e,u):t.removeAttribute(e))})}}be("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var c in o){var s=o[c];s&&s.d()}}}}else{var u=e.__c;if(u){var l=u.__$u;l&&(u.__$u=void 0,l.d())}}t(e)}),be("__h",function(t,e,n,o){(o<3||o===9)&&(e.__$f|=2),t(e,n,o)}),Se.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var c in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(o||s||4&this.__$f)||1&this.__$f)return!0}else if(!(o||4&this.__$f)||3&this.__$f)return!0;for(var u in t)if(u!=="__source"&&t[u]!==this.props[u])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Ei(t,e){return We(function(){return z(t,e)})[0]}var sn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function an(){tn(function(){for(var t;t=pi.shift();)fi.call(t)})}function mi(){pi.push(this)===1&&(O.requestAnimationFrame||sn)(an)}const _t={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},Ze={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}},ln=new Set(["top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left"]);function cn(t){if(Ze[t])return Ze[t];const e=t.match(/^\[(.+)\]$/);if(!e)return Ze["bottom-right"];const n={};for(const o of e[1].split(",")){const c=o.trim(),s=c.lastIndexOf("-");if(s<=0)continue;const u=c.slice(0,s);if(!ln.has(u))continue;const l=c.slice(s+1);/^[\w.%-]+$/.test(l)&&(n[u]=/^\d+$/.test(l)?`${l}px`:l)}return Object.keys(n).length>0?n:Ze["bottom-right"]}var Et={},Be={},gi;function un(){if(gi)return Be;gi=1,Be.byteLength=l,Be.toByteArray=p,Be.fromByteArray=y;for(var t=[],e=[],n=typeof Uint8Array<"u"?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,s=o.length;c<s;++c)t[c]=o[c],e[o.charCodeAt(c)]=c;e[45]=62,e[95]=63;function u(g){var S=g.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var C=g.indexOf("=");C===-1&&(C=S);var A=C===S?0:4-C%4;return[C,A]}function l(g){var S=u(g),C=S[0],A=S[1];return(C+A)*3/4-A}function E(g,S,C){return(S+C)*3/4-C}function p(g){var S,C=u(g),A=C[0],I=C[1],b=new n(E(g,A,I)),T=0,D=I>0?A-4:A,N;for(N=0;N<D;N+=4)S=e[g.charCodeAt(N)]<<18|e[g.charCodeAt(N+1)]<<12|e[g.charCodeAt(N+2)]<<6|e[g.charCodeAt(N+3)],b[T++]=S>>16&255,b[T++]=S>>8&255,b[T++]=S&255;return I===2&&(S=e[g.charCodeAt(N)]<<2|e[g.charCodeAt(N+1)]>>4,b[T++]=S&255),I===1&&(S=e[g.charCodeAt(N)]<<10|e[g.charCodeAt(N+1)]<<4|e[g.charCodeAt(N+2)]>>2,b[T++]=S>>8&255,b[T++]=S&255),b}function _(g){return t[g>>18&63]+t[g>>12&63]+t[g>>6&63]+t[g&63]}function d(g,S,C){for(var A,I=[],b=S;b<C;b+=3)A=(g[b]<<16&16711680)+(g[b+1]<<8&65280)+(g[b+2]&255),I.push(_(A));return I.join("")}function y(g){for(var S,C=g.length,A=C%3,I=[],b=16383,T=0,D=C-A;T<D;T+=b)I.push(d(g,T,T+b>D?D:T+b));return A===1?(S=g[C-1],I.push(t[S>>2]+t[S<<4&63]+"==")):A===2&&(S=(g[C-2]<<8)+g[C-1],I.push(t[S>>10]+t[S>>4&63]+t[S<<2&63]+"=")),I.join("")}return Be}var Qe={};var vi;function dn(){return vi||(vi=1,Qe.read=function(t,e,n,o,c){var s,u,l=c*8-o-1,E=(1<<l)-1,p=E>>1,_=-7,d=n?c-1:0,y=n?-1:1,g=t[e+d];for(d+=y,s=g&(1<<-_)-1,g>>=-_,_+=l;_>0;s=s*256+t[e+d],d+=y,_-=8);for(u=s&(1<<-_)-1,s>>=-_,_+=o;_>0;u=u*256+t[e+d],d+=y,_-=8);if(s===0)s=1-p;else{if(s===E)return u?NaN:(g?-1:1)*(1/0);u=u+Math.pow(2,o),s=s-p}return(g?-1:1)*u*Math.pow(2,s-o)},Qe.write=function(t,e,n,o,c,s){var u,l,E,p=s*8-c-1,_=(1<<p)-1,d=_>>1,y=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=o?0:s-1,S=o?1:-1,C=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,u=_):(u=Math.floor(Math.log(e)/Math.LN2),e*(E=Math.pow(2,-u))<1&&(u--,E*=2),u+d>=1?e+=y/E:e+=y*Math.pow(2,1-d),e*E>=2&&(u++,E/=2),u+d>=_?(l=0,u=_):u+d>=1?(l=(e*E-1)*Math.pow(2,c),u=u+d):(l=e*Math.pow(2,d-1)*Math.pow(2,c),u=0));c>=8;t[n+g]=l&255,g+=S,l/=256,c-=8);for(u=u<<c|l,p+=c;p>0;t[n+g]=u&255,g+=S,u/=256,p-=8);t[n+g-S]|=C*128}),Qe}var yi;function hn(){return yi||(yi=1,(function(t){const e=un(),n=dn(),o=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=b,t.INSPECT_MAX_BYTES=50;const c=2147483647;t.kMaxLength=c,l.TYPED_ARRAY_SUPPORT=s(),!l.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const a=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(a,i),a.foo()===42}catch{return!1}}Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}});function u(a){if(a>c)throw new RangeError('The value "'+a+'" is invalid for option "size"');const i=new Uint8Array(a);return Object.setPrototypeOf(i,l.prototype),i}function l(a,i,r){if(typeof a=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(a)}return E(a,i,r)}l.poolSize=8192;function E(a,i,r){if(typeof a=="string")return y(a,i);if(ArrayBuffer.isView(a))return S(a);if(a==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(te(a,ArrayBuffer)||a&&te(a.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(te(a,SharedArrayBuffer)||a&&te(a.buffer,SharedArrayBuffer)))return C(a,i,r);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=a.valueOf&&a.valueOf();if(h!=null&&h!==a)return l.from(h,i,r);const f=A(a);if(f)return f;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return l.from(a[Symbol.toPrimitive]("string"),i,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}l.from=function(a,i,r){return E(a,i,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(a<0)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function _(a,i,r){return p(a),a<=0?u(a):i!==void 0?typeof r=="string"?u(a).fill(i,r):u(a).fill(i):u(a)}l.alloc=function(a,i,r){return _(a,i,r)};function d(a){return p(a),u(a<0?0:I(a)|0)}l.allocUnsafe=function(a){return d(a)},l.allocUnsafeSlow=function(a){return d(a)};function y(a,i){if((typeof i!="string"||i==="")&&(i="utf8"),!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const r=T(a,i)|0;let h=u(r);const f=h.write(a,i);return f!==r&&(h=h.slice(0,f)),h}function g(a){const i=a.length<0?0:I(a.length)|0,r=u(i);for(let h=0;h<i;h+=1)r[h]=a[h]&255;return r}function S(a){if(te(a,Uint8Array)){const i=new Uint8Array(a);return C(i.buffer,i.byteOffset,i.byteLength)}return g(a)}function C(a,i,r){if(i<0||a.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(a.byteLength<i+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return i===void 0&&r===void 0?h=new Uint8Array(a):r===void 0?h=new Uint8Array(a,i):h=new Uint8Array(a,i,r),Object.setPrototypeOf(h,l.prototype),h}function A(a){if(l.isBuffer(a)){const i=I(a.length)|0,r=u(i);return r.length===0||a.copy(r,0,0,i),r}if(a.length!==void 0)return typeof a.length!="number"||At(a.length)?u(0):g(a);if(a.type==="Buffer"&&Array.isArray(a.data))return g(a.data)}function I(a){if(a>=c)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+c.toString(16)+" bytes");return a|0}function b(a){return+a!=a&&(a=0),l.alloc(+a)}l.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==l.prototype},l.compare=function(i,r){if(te(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),te(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(i)||!l.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===r)return 0;let h=i.length,f=r.length;for(let m=0,v=Math.min(h,f);m<v;++m)if(i[m]!==r[m]){h=i[m],f=r[m];break}return h<f?-1:f<h?1:0},l.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(i,r){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return l.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<i.length;++h)r+=i[h].length;const f=l.allocUnsafe(r);let m=0;for(h=0;h<i.length;++h){let v=i[h];if(te(v,Uint8Array))m+v.length>f.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(f,m)):Uint8Array.prototype.set.call(f,v,m);else if(l.isBuffer(v))v.copy(f,m);else throw new TypeError('"list" argument must be an Array of Buffers');m+=v.length}return f};function T(a,i){if(l.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||te(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);const r=a.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let f=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return bt(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Bi(a).length;default:if(f)return h?-1:bt(a).length;i=(""+i).toLowerCase(),f=!0}}l.byteLength=T;function D(a,i,r){let h=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,i>>>=0,r<=i))return"";for(a||(a="utf8");;)switch(a){case"hex":return Er(this,i,r);case"utf8":case"utf-8":return Ri(this,i,r);case"ascii":return pr(this,i,r);case"latin1":case"binary":return _r(this,i,r);case"base64":return hr(this,i,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return mr(this,i,r);default:if(h)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function N(a,i,r){const h=a[i];a[i]=a[r],a[r]=h}l.prototype.swap16=function(){const i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<i;r+=2)N(this,r,r+1);return this},l.prototype.swap32=function(){const i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<i;r+=4)N(this,r,r+3),N(this,r+1,r+2);return this},l.prototype.swap64=function(){const i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<i;r+=8)N(this,r,r+7),N(this,r+1,r+6),N(this,r+2,r+5),N(this,r+3,r+4);return this},l.prototype.toString=function(){const i=this.length;return i===0?"":arguments.length===0?Ri(this,0,i):D.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(i){if(!l.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:l.compare(this,i)===0},l.prototype.inspect=function(){let i="";const r=t.INSPECT_MAX_BYTES;return i=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(i+=" ... "),"<Buffer "+i+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(i,r,h,f,m){if(te(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),!l.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(r===void 0&&(r=0),h===void 0&&(h=i?i.length:0),f===void 0&&(f=0),m===void 0&&(m=this.length),r<0||h>i.length||f<0||m>this.length)throw new RangeError("out of range index");if(f>=m&&r>=h)return 0;if(f>=m)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,f>>>=0,m>>>=0,this===i)return 0;let v=m-f,R=h-r;const L=Math.min(v,R),U=this.slice(f,m),B=i.slice(r,h);for(let M=0;M<L;++M)if(U[M]!==B[M]){v=U[M],R=B[M];break}return v<R?-1:R<v?1:0};function Y(a,i,r,h,f){if(a.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,At(r)&&(r=f?0:a.length-1),r<0&&(r=a.length+r),r>=a.length){if(f)return-1;r=a.length-1}else if(r<0)if(f)r=0;else return-1;if(typeof i=="string"&&(i=l.from(i,h)),l.isBuffer(i))return i.length===0?-1:re(a,i,r,h,f);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?f?Uint8Array.prototype.indexOf.call(a,i,r):Uint8Array.prototype.lastIndexOf.call(a,i,r):re(a,[i],r,h,f);throw new TypeError("val must be string, number or Buffer")}function re(a,i,r,h,f){let m=1,v=a.length,R=i.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(a.length<2||i.length<2)return-1;m=2,v/=2,R/=2,r/=2}function L(B,M){return m===1?B[M]:B.readUInt16BE(M*m)}let U;if(f){let B=-1;for(U=r;U<v;U++)if(L(a,U)===L(i,B===-1?0:U-B)){if(B===-1&&(B=U),U-B+1===R)return B*m}else B!==-1&&(U-=U-B),B=-1}else for(r+R>v&&(r=v-R),U=r;U>=0;U--){let B=!0;for(let M=0;M<R;M++)if(L(a,U+M)!==L(i,M)){B=!1;break}if(B)return U}return-1}l.prototype.includes=function(i,r,h){return this.indexOf(i,r,h)!==-1},l.prototype.indexOf=function(i,r,h){return Y(this,i,r,h,!0)},l.prototype.lastIndexOf=function(i,r,h){return Y(this,i,r,h,!1)};function V(a,i,r,h){r=Number(r)||0;const f=a.length-r;h?(h=Number(h),h>f&&(h=f)):h=f;const m=i.length;h>m/2&&(h=m/2);let v;for(v=0;v<h;++v){const R=parseInt(i.substr(v*2,2),16);if(At(R))return v;a[r+v]=R}return v}function oe(a,i,r,h){return tt(bt(i,a.length-r),a,r,h)}function se(a,i,r,h){return tt(Sr(i),a,r,h)}function Z(a,i,r,h){return tt(Bi(i),a,r,h)}function _e(a,i,r,h){return tt(wr(i,a.length-r),a,r,h)}l.prototype.write=function(i,r,h,f){if(r===void 0)f="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")f=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,f===void 0&&(f="utf8")):(f=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const m=this.length-r;if((h===void 0||h>m)&&(h=m),i.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");f||(f="utf8");let v=!1;for(;;)switch(f){case"hex":return V(this,i,r,h);case"utf8":case"utf-8":return oe(this,i,r,h);case"ascii":case"latin1":case"binary":return se(this,i,r,h);case"base64":return Z(this,i,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _e(this,i,r,h);default:if(v)throw new TypeError("Unknown encoding: "+f);f=(""+f).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function hr(a,i,r){return i===0&&r===a.length?e.fromByteArray(a):e.fromByteArray(a.slice(i,r))}function Ri(a,i,r){r=Math.min(a.length,r);const h=[];let f=i;for(;f<r;){const m=a[f];let v=null,R=m>239?4:m>223?3:m>191?2:1;if(f+R<=r){let L,U,B,M;switch(R){case 1:m<128&&(v=m);break;case 2:L=a[f+1],(L&192)===128&&(M=(m&31)<<6|L&63,M>127&&(v=M));break;case 3:L=a[f+1],U=a[f+2],(L&192)===128&&(U&192)===128&&(M=(m&15)<<12|(L&63)<<6|U&63,M>2047&&(M<55296||M>57343)&&(v=M));break;case 4:L=a[f+1],U=a[f+2],B=a[f+3],(L&192)===128&&(U&192)===128&&(B&192)===128&&(M=(m&15)<<18|(L&63)<<12|(U&63)<<6|B&63,M>65535&&M<1114112&&(v=M))}}v===null?(v=65533,R=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),f+=R}return fr(h)}const Ni=4096;function fr(a){const i=a.length;if(i<=Ni)return String.fromCharCode.apply(String,a);let r="",h=0;for(;h<i;)r+=String.fromCharCode.apply(String,a.slice(h,h+=Ni));return r}function pr(a,i,r){let h="";r=Math.min(a.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(a[f]&127);return h}function _r(a,i,r){let h="";r=Math.min(a.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(a[f]);return h}function Er(a,i,r){const h=a.length;(!i||i<0)&&(i=0),(!r||r<0||r>h)&&(r=h);let f="";for(let m=i;m<r;++m)f+=Cr[a[m]];return f}function mr(a,i,r){const h=a.slice(i,r);let f="";for(let m=0;m<h.length-1;m+=2)f+=String.fromCharCode(h[m]+h[m+1]*256);return f}l.prototype.slice=function(i,r){const h=this.length;i=~~i,r=r===void 0?h:~~r,i<0?(i+=h,i<0&&(i=0)):i>h&&(i=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<i&&(r=i);const f=this.subarray(i,r);return Object.setPrototypeOf(f,l.prototype),f};function G(a,i,r){if(a%1!==0||a<0)throw new RangeError("offset is not uint");if(a+i>r)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],m=1,v=0;for(;++v<r&&(m*=256);)f+=this[i+v]*m;return f},l.prototype.readUintBE=l.prototype.readUIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i+--r],m=1;for(;r>0&&(m*=256);)f+=this[i+--r]*m;return f},l.prototype.readUint8=l.prototype.readUInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]|this[i+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]<<8|this[i+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])},l.prototype.readBigUInt64LE=Ee(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Fe(i,this.length-8);const f=r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,m=this[++i]+this[++i]*2**8+this[++i]*2**16+h*2**24;return BigInt(f)+(BigInt(m)<<BigInt(32))}),l.prototype.readBigUInt64BE=Ee(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Fe(i,this.length-8);const f=r*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],m=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h;return(BigInt(f)<<BigInt(32))+BigInt(m)}),l.prototype.readIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],m=1,v=0;for(;++v<r&&(m*=256);)f+=this[i+v]*m;return m*=128,f>=m&&(f-=Math.pow(2,8*r)),f},l.prototype.readIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=r,m=1,v=this[i+--f];for(;f>0&&(m*=256);)v+=this[i+--f]*m;return m*=128,v>=m&&(v-=Math.pow(2,8*r)),v},l.prototype.readInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]},l.prototype.readInt16LE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i]|this[i+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i+1]|this[i]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24},l.prototype.readInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]},l.prototype.readBigInt64LE=Ee(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Fe(i,this.length-8);const f=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(h<<24);return(BigInt(f)<<BigInt(32))+BigInt(r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)}),l.prototype.readBigInt64BE=Ee(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Fe(i,this.length-8);const f=(r<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(f)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h)}),l.prototype.readFloatLE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!0,23,4)},l.prototype.readFloatBE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!1,23,4)},l.prototype.readDoubleLE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!0,52,8)},l.prototype.readDoubleBE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!1,52,8)};function K(a,i,r,h,f,m){if(!l.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>f||i<m)throw new RangeError('"value" argument is out of bounds');if(r+h>a.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const R=Math.pow(2,8*h)-1;K(this,i,r,h,R,0)}let m=1,v=0;for(this[r]=i&255;++v<h&&(m*=256);)this[r+v]=i/m&255;return r+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const R=Math.pow(2,8*h)-1;K(this,i,r,h,R,0)}let m=h-1,v=1;for(this[r+m]=i&255;--m>=0&&(v*=256);)this[r+m]=i/v&255;return r+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,255,0),this[r]=i&255,r+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r+3]=i>>>24,this[r+2]=i>>>16,this[r+1]=i>>>8,this[r]=i&255,r+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};function xi(a,i,r,h,f){Li(i,h,f,a,r,7);let m=Number(i&BigInt(4294967295));a[r++]=m,m=m>>8,a[r++]=m,m=m>>8,a[r++]=m,m=m>>8,a[r++]=m;let v=Number(i>>BigInt(32)&BigInt(4294967295));return a[r++]=v,v=v>>8,a[r++]=v,v=v>>8,a[r++]=v,v=v>>8,a[r++]=v,r}function Oi(a,i,r,h,f){Li(i,h,f,a,r,7);let m=Number(i&BigInt(4294967295));a[r+7]=m,m=m>>8,a[r+6]=m,m=m>>8,a[r+5]=m,m=m>>8,a[r+4]=m;let v=Number(i>>BigInt(32)&BigInt(4294967295));return a[r+3]=v,v=v>>8,a[r+2]=v,v=v>>8,a[r+1]=v,v=v>>8,a[r]=v,r+8}l.prototype.writeBigUInt64LE=Ee(function(i,r=0){return xi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Ee(function(i,r=0){return Oi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let m=0,v=1,R=0;for(this[r]=i&255;++m<h&&(v*=256);)i<0&&R===0&&this[r+m-1]!==0&&(R=1),this[r+m]=(i/v>>0)-R&255;return r+h},l.prototype.writeIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let m=h-1,v=1,R=0;for(this[r+m]=i&255;--m>=0&&(v*=256);)i<0&&R===0&&this[r+m+1]!==0&&(R=1),this[r+m]=(i/v>>0)-R&255;return r+h},l.prototype.writeInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,127,-128),i<0&&(i=255+i+1),this[r]=i&255,r+1},l.prototype.writeInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),this[r]=i&255,this[r+1]=i>>>8,this[r+2]=i>>>16,this[r+3]=i>>>24,r+4},l.prototype.writeInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4},l.prototype.writeBigInt64LE=Ee(function(i,r=0){return xi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Ee(function(i,r=0){return Oi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ki(a,i,r,h,f,m){if(r+h>a.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Di(a,i,r,h,f){return i=+i,r=r>>>0,f||ki(a,i,r,4),n.write(a,i,r,h,23,4),r+4}l.prototype.writeFloatLE=function(i,r,h){return Di(this,i,r,!0,h)},l.prototype.writeFloatBE=function(i,r,h){return Di(this,i,r,!1,h)};function Mi(a,i,r,h,f){return i=+i,r=r>>>0,f||ki(a,i,r,8),n.write(a,i,r,h,52,8),r+8}l.prototype.writeDoubleLE=function(i,r,h){return Mi(this,i,r,!0,h)},l.prototype.writeDoubleBE=function(i,r,h){return Mi(this,i,r,!1,h)},l.prototype.copy=function(i,r,h,f){if(!l.isBuffer(i))throw new TypeError("argument should be a Buffer");if(h||(h=0),!f&&f!==0&&(f=this.length),r>=i.length&&(r=i.length),r||(r=0),f>0&&f<h&&(f=h),f===h||i.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("sourceEnd out of bounds");f>this.length&&(f=this.length),i.length-r<f-h&&(f=i.length-r+h);const m=f-h;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,f):Uint8Array.prototype.set.call(i,this.subarray(h,f),r),m},l.prototype.fill=function(i,r,h,f){if(typeof i=="string"){if(typeof r=="string"?(f=r,r=0,h=this.length):typeof h=="string"&&(f=h,h=this.length),f!==void 0&&typeof f!="string")throw new TypeError("encoding must be a string");if(typeof f=="string"&&!l.isEncoding(f))throw new TypeError("Unknown encoding: "+f);if(i.length===1){const v=i.charCodeAt(0);(f==="utf8"&&v<128||f==="latin1")&&(i=v)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(r<0||this.length<r||this.length<h)throw new RangeError("Out of range index");if(h<=r)return this;r=r>>>0,h=h===void 0?this.length:h>>>0,i||(i=0);let m;if(typeof i=="number")for(m=r;m<h;++m)this[m]=i;else{const v=l.isBuffer(i)?i:l.from(i,f),R=v.length;if(R===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(m=0;m<h-r;++m)this[m+r]=v[m%R]}return this};const Re={};function It(a,i,r){Re[a]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${a}]`,this.stack,delete this.name}get code(){return a}set code(f){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:f,writable:!0})}toString(){return`${this.name} [${a}]: ${this.message}`}}}It("ERR_BUFFER_OUT_OF_BOUNDS",function(a){return a?`${a} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),It("ERR_INVALID_ARG_TYPE",function(a,i){return`The "${a}" argument must be of type number. Received type ${typeof i}`},TypeError),It("ERR_OUT_OF_RANGE",function(a,i,r){let h=`The value of "${a}" is out of range.`,f=r;return Number.isInteger(r)&&Math.abs(r)>2**32?f=Ui(String(r)):typeof r=="bigint"&&(f=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(f=Ui(f)),f+="n"),h+=` It must be ${i}. Received ${f}`,h},RangeError);function Ui(a){let i="",r=a.length;const h=a[0]==="-"?1:0;for(;r>=h+4;r-=3)i=`_${a.slice(r-3,r)}${i}`;return`${a.slice(0,r)}${i}`}function gr(a,i,r){Ne(i,"offset"),(a[i]===void 0||a[i+r]===void 0)&&Fe(i,a.length-(r+1))}function Li(a,i,r,h,f,m){if(a>r||a<i){const v=typeof i=="bigint"?"n":"";let R;throw i===0||i===BigInt(0)?R=`>= 0${v} and < 2${v} ** ${(m+1)*8}${v}`:R=`>= -(2${v} ** ${(m+1)*8-1}${v}) and < 2 ** ${(m+1)*8-1}${v}`,new Re.ERR_OUT_OF_RANGE("value",R,a)}gr(h,f,m)}function Ne(a,i){if(typeof a!="number")throw new Re.ERR_INVALID_ARG_TYPE(i,"number",a)}function Fe(a,i,r){throw Math.floor(a)!==a?(Ne(a,r),new Re.ERR_OUT_OF_RANGE("offset","an integer",a)):i<0?new Re.ERR_BUFFER_OUT_OF_BOUNDS:new Re.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${i}`,a)}const vr=/[^+/0-9A-Za-z-_]/g;function yr(a){if(a=a.split("=")[0],a=a.trim().replace(vr,""),a.length<2)return"";for(;a.length%4!==0;)a=a+"=";return a}function bt(a,i){i=i||1/0;let r;const h=a.length;let f=null;const m=[];for(let v=0;v<h;++v){if(r=a.charCodeAt(v),r>55295&&r<57344){if(!f){if(r>56319){(i-=3)>-1&&m.push(239,191,189);continue}else if(v+1===h){(i-=3)>-1&&m.push(239,191,189);continue}f=r;continue}if(r<56320){(i-=3)>-1&&m.push(239,191,189),f=r;continue}r=(f-55296<<10|r-56320)+65536}else f&&(i-=3)>-1&&m.push(239,191,189);if(f=null,r<128){if((i-=1)<0)break;m.push(r)}else if(r<2048){if((i-=2)<0)break;m.push(r>>6|192,r&63|128)}else if(r<65536){if((i-=3)<0)break;m.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((i-=4)<0)break;m.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return m}function Sr(a){const i=[];for(let r=0;r<a.length;++r)i.push(a.charCodeAt(r)&255);return i}function wr(a,i){let r,h,f;const m=[];for(let v=0;v<a.length&&!((i-=2)<0);++v)r=a.charCodeAt(v),h=r>>8,f=r%256,m.push(f),m.push(h);return m}function Bi(a){return e.toByteArray(yr(a))}function tt(a,i,r,h){let f;for(f=0;f<h&&!(f+r>=i.length||f>=a.length);++f)i[f+r]=a[f];return f}function te(a,i){return a instanceof i||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===i.name}function At(a){return a!==a}const Cr=(function(){const a="0123456789abcdef",i=new Array(256);for(let r=0;r<16;++r){const h=r*16;for(let f=0;f<16;++f)i[h+f]=a[r]+a[f]}return i})();function Ee(a){return typeof BigInt>"u"?Ir:a}function Ir(){throw new Error("BigInt not supported")}})(Et)),Et}var fn=hn();const pn="https://api.anam.ai",_n="/v1",Si={client:"js-sdk",version:"4.8.0"};var En=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};const wi="https://api.anam.ai",mt="/v1";var ne;(function(t){t.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(ne||(ne={}));let gt=wi,Ci=mt,ue,Ii=!1;const mn=(t,e=mt)=>{gt=t,Ci=e},gn=t=>{ue=t},vn=t=>{Ii=t};let de={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ae=t=>{de=Object.assign(Object.assign({},de),t)},ve=(t,e,n)=>En(void 0,void 0,void 0,function*(){if(!Ii)try{const o=Object.assign(Object.assign({},Si),n);de.sessionId&&(o.sessionId=de.sessionId),de.organizationId&&(o.organizationId=de.organizationId),de.attemptCorrelationId&&(o.attemptCorrelationId=de.attemptCorrelationId);const c=`${Ci}/metrics/client`;let s,u={"Content-Type":"application/json"};ue?.enabled&&ue?.baseUrl?(s=`${ue.baseUrl}${c}`,u["X-Anam-Target-Url"]=`${gt}${c}`):s=`${gt}${c}`,yield fetch(s,{method:"POST",headers:u,body:JSON.stringify({name:t,value:e,tags:o})})}catch(o){console.error("Failed to send error metric:",o)}}),yn=(t,e="console")=>{var n,o,c;const s={};t.forEach(d=>{s[d.type]||(s[d.type]=[]),s[d.type].push(d)});const u={issues:[]},l=((n=s["inbound-rtp"])===null||n===void 0?void 0:n.filter(d=>d.kind==="video"))||[];l.length>0&&(u.personaVideoStream=[],l.forEach(d=>{var y,g,S,C,A;const I={framesReceived:(y=d.framesReceived)!==null&&y!==void 0?y:"unknown",framesDropped:(g=d.framesDropped)!==null&&g!==void 0?g:"unknown",framesPerSecond:(S=d.framesPerSecond)!==null&&S!==void 0?S:"unknown",packetsReceived:(C=d.packetsReceived)!==null&&C!==void 0?C:"unknown",packetsLost:(A=d.packetsLost)!==null&&A!==void 0?A:"unknown",resolution:d.frameWidth&&d.frameHeight?`${d.frameWidth}x${d.frameHeight}`:void 0,jitter:d.jitter!==void 0?d.jitter:void 0};u.personaVideoStream.push(I)}));const E=((o=s["inbound-rtp"])===null||o===void 0?void 0:o.filter(d=>d.kind==="audio"))||[];E.length>0&&(u.personaAudioStream=[],E.forEach(d=>{var y,g,S;const C={packetsReceived:(y=d.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(g=d.packetsLost)!==null&&g!==void 0?g:"unknown",audioLevel:(S=d.audioLevel)!==null&&S!==void 0?S:"unknown",jitter:d.jitter!==void 0?d.jitter:void 0,totalAudioEnergy:d.totalAudioEnergy!==void 0?d.totalAudioEnergy:void 0};u.personaAudioStream.push(C)}));const p=((c=s["outbound-rtp"])===null||c===void 0?void 0:c.filter(d=>d.kind==="audio"))||[];p.length>0&&(u.userAudioInput=[],p.forEach(d=>{var y,g;const S={packetsSent:(y=d.packetsSent)!==null&&y!==void 0?y:"unknown",retransmittedPackets:(g=d.retransmittedPacketsSent)!==null&&g!==void 0?g:void 0,avgPacketSendDelay:d.totalPacketSendDelay!==void 0?d.totalPacketSendDelay/(d.packetsSent||1)*1e3:void 0};u.userAudioInput.push(S)})),s.codec&&(u.codecs=[],s.codec.forEach(d=>{const y={status:d.payloadType?"Active":"Available",mimeType:d.mimeType||"Unknown",payloadType:d.payloadType||"N/A",clockRate:d.clockRate||void 0,channels:d.channels||void 0};u.codecs.push(y)})),s.transport&&(u.transportLayer=[],s.transport.forEach(d=>{const y={dtlsState:d.dtlsState||"unknown",iceState:d.iceState||"unknown",bytesSent:d.bytesSent||void 0,bytesReceived:d.bytesReceived||void 0};u.transportLayer.push(y)}));const _=[];if(l.forEach(d=>{typeof d.framesDropped=="number"&&d.framesDropped>0&&_.push(`Video: ${d.framesDropped} frames dropped`),typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Video: ${d.packetsLost} packets lost`),typeof d.framesPerSecond=="number"&&d.framesPerSecond<23&&_.push(`Video: Low frame rate (${d.framesPerSecond} fps)`)}),E.forEach(d=>{typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Audio: ${d.packetsLost} packets lost`),typeof d.jitter=="number"&&d.jitter>.1&&_.push(`Audio: High jitter (${(d.jitter*1e3).toFixed(1)}ms)`)}),u.issues=_,e==="json")return u;console.group("📊 WebRTC Session Statistics Report"),u.personaVideoStream&&u.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),u.personaVideoStream.forEach(d=>{console.log(`Frames Received: ${d.framesReceived}`),console.log(`Frames Dropped: ${d.framesDropped}`),console.log(`Frames Per Second: ${d.framesPerSecond}`),console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),d.resolution&&console.log(`Resolution: ${d.resolution}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`)}),console.groupEnd()),u.personaAudioStream&&u.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),u.personaAudioStream.forEach(d=>{console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),console.log(`Audio Level: ${d.audioLevel}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`),d.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${d.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),u.userAudioInput&&u.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),u.userAudioInput.forEach(d=>{console.log(`Packets Sent: ${typeof d.packetsSent=="number"?d.packetsSent.toLocaleString():d.packetsSent}`),d.retransmittedPackets&&console.log(`Retransmitted Packets: ${d.retransmittedPackets}`),d.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${d.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),u.codecs&&u.codecs.length>0&&(console.group("🔧 Codecs Used"),u.codecs.forEach(d=>{console.log(`${d.status} ${d.mimeType} - Payload Type: ${d.payloadType}`),d.clockRate&&console.log(`  Clock Rate: ${d.clockRate}Hz`),d.channels&&console.log(`  Channels: ${d.channels}`)}),console.groupEnd()),u.transportLayer&&u.transportLayer.length>0&&(console.group("🚚 Transport Layer"),u.transportLayer.forEach(d=>{console.log(`DTLS State: ${d.dtlsState}`),console.log(`ICE State: ${d.iceState}`),(d.bytesReceived||d.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(d.bytesSent||0).toLocaleString()}, Received: ${(d.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),u.issues.length>0?(console.group("⚠️ Potential Issues Detected"),u.issues.forEach(d=>console.warn(d)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var H;(function(t){t.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",t.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",t.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",t.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",t.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",t.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",t.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",t.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",t.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",t.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(H||(H={}));class $ extends Error{constructor(e,n,o=500,c){super(e),this.name="ClientError",this.code=n,this.statusCode=o,this.details=c,Object.setPrototypeOf(this,$.prototype),ve(ne.CLIENT_METRIC_MEASUREMENT_ERROR,n,{details:c,statusCode:o})}}function bi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function Sn(t){if(!(!t||!t.enabled)){if(!t.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(t.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${t.baseUrl}`}if(t.wsPath&&!t.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var W;(function(t){t.OFFER="offer",t.ANSWER="answer",t.ICE_CANDIDATE="icecandidate",t.END_SESSION="endsession",t.HEARTBEAT="heartbeat",t.WARNING="warning",t.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",t.TALK_STREAM_INPUT="talkstream",t.SESSION_READY="sessionready",t.AGENT_AUDIO_INPUT="agentaudioinput",t.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(W||(W={}));var Pe;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.REASONING_TEXT="reasoningText"})(Pe||(Pe={}));var he;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(he||(he={}));var et;(function(t){t.USER="user",t.PERSONA="persona"})(et||(et={}));var x;(function(t){t.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",t.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",t.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",t.CONNECTION_CLOSED="CONNECTION_CLOSED",t.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",t.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",t.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",t.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",t.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",t.SESSION_READY="SESSION_READY",t.SERVER_WARNING="SERVER_WARNING",t.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",t.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",t.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",t.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",t.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"})(x||(x={}));var J;(function(t){t.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",t.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",t.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(J||(J={}));var fe;(function(t){t.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",t.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",t.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",t.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",t.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(fe||(fe={}));class wn{constructor(e,n){this.sequenceNumber=0,this.config=e,this.signallingClient=n}sendAudioChunk(e){const o={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(o)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const n=e instanceof Uint8Array?e:new Uint8Array(e),o=Array.from(n,c=>String.fromCharCode(c)).join("");return btoa(o)}}var Te=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};const Cn=5,In=5;class bn{constructor(e,n,o,c,s){var u,l,E,p,_;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=o,this.internalEventEmitter=c,this.apiGatewayConfig=s,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:d,maxWsReconnectionAttempts:y,url:g}=n;if(this.heartbeatIntervalSeconds=d||Cn,this.maxWsReconnectionAttempts=y||In,!g.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((u=this.apiGatewayConfig)===null||u===void 0)&&u.enabled&&(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.baseUrl)){const S=new URL(this.apiGatewayConfig.baseUrl),C=(E=this.apiGatewayConfig.wsPath)!==null&&E!==void 0?E:"/ws";S.protocol=S.protocol.replace("http","ws"),S.pathname=C,this.url=S;const A=g.protocol||"https",I=A==="http"?"ws":"wss",b=`${A}://${g.baseUrl}`,T=(p=g.signallingPath)!==null&&p!==void 0?p:"/ws",D=new URL(b);D.protocol=I==="ws"?"ws:":"wss:",g.port&&(D.port=g.port),D.pathname=T,D.searchParams.append("session_id",e),this.url.searchParams.append("target_url",D.href)}else{const C=`${g.protocol||"https"}://${g.baseUrl}`;this.url=new URL(C),this.url.protocol=g.protocol==="http"?"ws:":"wss:",g.port&&(this.url.port=g.port),this.url.pathname=(_=g.signallingPath)!==null&&_!==void 0?_:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Te(this,void 0,void 0,function*(){const n={connectionDescription:e,userUid:this.sessionId},o={actionType:W.OFFER,sessionId:this.sessionId,payload:n};this.sendSignalMessage(o)})}sendIceCandidate(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(n)})}sendSignalMessage(e){var n;if(((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(o){console.error("SignallingClient - sendSignalMessage: error sending message",o)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)})}sendAgentAudioInput(e){const n={actionType:W.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)}sendAgentAudioInputEnd(){const e={actionType:W.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Te(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(J.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Te(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(n=>{var o;((o=this.socket)===null||o===void 0?void 0:o.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(n)):e.push(n)}),this.sendingBuffer=e}onMessage(e){return Te(this,void 0,void 0,function*(){const n=JSON.parse(e.data);this.internalEventEmitter.emit(J.SIGNAL_MESSAGE_RECEIVED,n)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,n={actionType:W.HEARTBEAT,sessionId:this.sessionId,payload:""},o=JSON.stringify(n);this.heartBeatIntervalRef=setInterval(()=>{var c;this.stopSignal||((c=this.socket)===null||c===void 0?void 0:c.readyState)===WebSocket.OPEN&&this.socket.send(o)},e)}}function An(t){return"brainType"in t||"llmId"in t}var Ai=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};class Tn{constructor(e,n,o){if(!e&&!n)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=n||null,this.baseUrl=o?.baseUrl||pn,this.apiVersion=o?.apiVersion||_n,this.apiGatewayConfig=o?.apiGateway||void 0}buildGatewayUrlAndHeaders(e,n){var o,c;if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((c=this.apiGatewayConfig)===null||c===void 0)&&c.baseUrl)){const s=`${this.apiGatewayConfig.baseUrl}${e}`,u=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},n),{"X-Anam-Target-Url":u.href});return{url:s,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:n}}startSession(e,n){return Ai(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const o=`${this.apiVersion}/engine/session`,{url:c,headers:s}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),u=yield fetch(c,{method:"POST",headers:s,body:JSON.stringify({personaConfig:e,sessionOptions:n,clientMetadata:Si})}),l=yield u.json(),E=l.error;switch(u.status){case 200:case 201:return l;case 400:throw new $("Invalid request to start session",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new $("Please sign up for a plan to start a session",H.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw E==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):E==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",H.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new $("Usage limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new $("There are no available personas, please try again later",H.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new $("Unknown error when starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(o){throw o instanceof $?o:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:o instanceof Error?o.message:String(o)})}})}unsafe_getSessionToken(e){return Ai(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let n={clientLabel:"js-sdk-api-key"};An(e)&&(n=Object.assign(Object.assign({},n),{personaConfig:e}));try{const o=`${this.apiVersion}/auth/session-token`,{url:c,headers:s}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(c,{method:"POST",headers:s,body:JSON.stringify(n)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Rn=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};class Nn{constructor(e,n,o){this.baseUrl=e,this.sessionId=n,this.apiGatewayConfig=o}sendTalkCommand(e){return Rn(this,void 0,void 0,function*(){var n,o;try{let c,s={"Content-Type":"application/json"};const u="/talk",l=`?session_id=${this.sessionId}`;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.baseUrl)){c=`${this.apiGatewayConfig.baseUrl}${u}${l}`;const p=new URL(`${this.baseUrl}${u}${l}`);s["X-Anam-Target-Url"]=p.href}else c=`${this.baseUrl}${u}${l}`;const E=yield fetch(c,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!E.ok)throw new Error(`Failed to send talk command: ${E.status} ${E.statusText}`)}catch(c){throw console.error(c),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class xn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}class On{constructor(e,n){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const n={id:e.id,content:e.content,role:e.role};this.messages.push(n)}processPersonaMessage(e){const n={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},o=this.messages.findIndex(c=>c.id===n.id);if(o!==-1){const c=this.messages[o];this.messages[o]=Object.assign(Object.assign({},c),{content:c.content+n.content,interrupted:c.interrupted||n.interrupted})}else this.messages.push(n)}processWebRtcTextMessageEvent(e){const n=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(x.MESSAGE_STREAM_EVENT_RECEIVED,n),n.role){case et.USER:this.processUserMessage(n);break;case et.PERSONA:this.processPersonaMessage(n);break}n.endOfSpeech&&this.publicEventEmitter.emit(x.MESSAGE_HISTORY_UPDATED,this.messages)}}class kn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){if(e===x.CONNECTION_ESTABLISHED&&ve(ne.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===x.CONNECTION_CLOSED){const[o,c]=n;ve(ne.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,o,c?{details:c}:void 0)}this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}var q;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(q||(q={}));var vt=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};class Dn{constructor(e,n,o){this.state=q.UNSTARTED,this.correlationId=e,this.internalEventEmitter=n,this.signallingClient=o,this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return vt(this,void 0,void 0,function*(){e.actionType===W.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=q.INTERRUPTED,this.onDeactivate())})}endMessage(){return vt(this,void 0,void 0,function*(){if(this.state===q.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==q.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=q.ENDED,this.onDeactivate()})}streamMessageChunk(e,n){return vt(this,void 0,void 0,function*(){if(this.state!==q.STREAMING&&this.state!==q.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const o={content:e,startOfSpeech:this.state===q.UNSTARTED,endOfSpeech:n,correlationId:this.correlationId};this.state=n?q.ENDED:q.STREAMING,this.state===q.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(o)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===q.STREAMING||this.state===q.UNSTARTED}getState(){return this.state}}var X=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};const Mn=15e3,Un=5e3,Ln=2;class Bn{constructor(e,n,o,c){var s,u,l,E;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:he.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=o,this.internalEventEmitter=c,this.apiGatewayConfig=n.apiGateway;const{inputAudio:p}=n;this.inputAudioState=p.inputAudioState,n.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=n.inputAudio.userProvidedMediaStream),this.disableInputAudio=n.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(J.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.iceServers=n.iceServers,this.signallingClient=new bn(e,n.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new Nn(n.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=n.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(u=(s=n.metrics)===null||s===void 0?void 0:s.showPeerConnectionStatsReport)!==null&&u!==void 0?u:!1,this.peerConnectionStatsReportOutputFormat=(E=(l=n.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&E!==void 0?E:"console"}onInputAudioStateChange(e,n){e.isMuted!==n.isMuted&&(n.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>X(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),Un))}sendClientSideMetrics(e){e.forEach(n=>{if(n.type==="inbound-rtp"){const o={message_type:"remote_rtp_stats",data:n};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(o))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Mn);this.successMetricPoller=setInterval(()=>X(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const n=yield this.peerConnection.getStats();let o=!1,c=null;n.forEach(s=>{s.type==="inbound-rtp"&&s.kind==="video"&&(s.framesDecoded!==void 0&&s.framesDecoded>0?(o=!0,c="framesDecoded"):s.framesReceived!==void 0&&s.framesReceived>0?(o=!0,c="framesReceived"):s.bytesReceived>0&&s.packetsReceived>0&&s.bytesReceived>1e5&&(o=!0,c="bytesReceived"))}),o&&!this.successMetricFired&&(this.successMetricFired=!0,ve(ne.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",c?{detectionMethod:c}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const n=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(c=>{c.stop()});const o={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:o}),this.audioDeviceId=e,yield this.setupAudioTrack(),n&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(x.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(o){throw console.error("Failed to change audio input device:",o),new Error(`StreamingClient - changeAudioInputDevice: ${o instanceof Error?o.message:String(o)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const n=document.getElementById(e);if(!n)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=n}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return X(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Dn(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new wn(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return X(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:Ln}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case W.ANSWER:const n=e.payload;yield this.peerConnection.setRemoteDescription(n),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case W.ICE_CANDIDATE:const o=e.payload,c=new RTCIceCandidate(o);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(c):this.remoteIceCandidateBuffer.push(c);break;case W.END_SESSION:const s=e.payload;this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.SERVER_CLOSED_CONNECTION,s),this.shutdown();break;case W.WARNING:const u=e.payload;console.warn("Warning received from server: "+u),this.publicEventEmitter.emit(x.SERVER_WARNING,u);break;case W.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(x.TALK_STREAM_INTERRUPTED,l.correlationId);break;case W.SESSION_READY:const E=e.sessionId;this.publicEventEmitter.emit(x.SESSION_READY,E);break;case W.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return X(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var n;(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,n;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(x.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.WEBRTC_FAILURE);try{this.stopConnection()}catch(n){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",n)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(x.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const n=this.videoElement.requestVideoFrameCallback(()=>{var o;(o=this.videoElement)===null||o===void 0||o.cancelVideoFrameCallback(n),this.publicEventEmitter.emit(x.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ve(ne.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(x.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=n=>{try{const o=JSON.parse(n.data);switch(o.messageType){case Pe.SPEECH_TEXT:this.internalEventEmitter.emit(J.WEBRTC_CHAT_MESSAGE_RECEIVED,o.data);break;case Pe.CLIENT_TOOL_EVENT:const c=o.data;this.internalEventEmitter.emit(J.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,c);const s=Pn.WebRTCClientToolEventToClientToolEvent(c);this.publicEventEmitter.emit(x.CLIENT_TOOL_EVENT_RECEIVED,s);break;case Pe.REASONING_TEXT:this.internalEventEmitter.emit(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,o.data);break;default:break}}catch(o){console.error("Failed to parse data channel message:",o)}}})}requestMicrophonePermissionAsync(){return X(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==he.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.PENDING}),this.publicEventEmitter.emit(x.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.GRANTED}),this.publicEventEmitter.emit(x.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.DENIED});const n=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(x.MIC_PERMISSION_DENIED,n)}}})}setupAudioTrack(){return X(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],o=this.peerConnection.getSenders().find(c=>{var s;return((s=c.track)===null||s===void 0?void 0:s.kind)==="audio"||c.track===null&&c.dtmf!==null});if(o)try{yield o.replaceTrack(e)}catch(c){console.error("Failed to replace audio track:",c),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(x.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return X(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return X(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const n=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(n){const o=yn(n,this.peerConnectionStatsReportOutputFormat);o&&console.log(o,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(n=>{n.stop()}),this.inputAudioStream=null}catch(n){console.error("StreamingClient - shutdown: error stopping input audio stream",n)}try{this.signallingClient.stop()}catch(n){console.error("StreamingClient - shutdown: error stopping signallilng",n)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(n){console.error("StreamingClient - shutdown: error closing peer connection",n)}})}}class Pn{static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}class Fn{constructor(e,n){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const n=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(x.REASONING_STREAM_EVENT_RECEIVED,n);const o={id:n.id,content:n.content,role:n.role},c=this.reasoning_messages.findIndex(s=>s.id===o.id);if(c!==-1){const s=this.reasoning_messages[c];s.content+=o.content,this.reasoning_messages[c]=s}else this.reasoning_messages.push(o);n.endOfThought&&this.publicEventEmitter.emit(x.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var pe=function(t,e,n,o){function c(s){return s instanceof n?s:new n(function(u){u(s)})}return new(n||(n=Promise))(function(s,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function E(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?s(_.value):c(_.value).then(l,E)}p((o=o.apply(t,e||[])).next())})};class $n{constructor(e,n,o){var c,s,u,l,E;this.inputAudioState={isMuted:!1,permissionState:he.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,n,o);if(p)throw new $(p,H.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=n,this.clientOptions=o,(!((c=o?.api)===null||c===void 0)&&c.baseUrl||!((s=o?.api)===null||s===void 0)&&s.apiVersion)&&mn(o.api.baseUrl||wi,o.api.apiVersion||mt),!((l=(u=o?.api)===null||u===void 0?void 0:u.apiGateway)===null||l===void 0)&&l.enabled&&gn(o.api.apiGateway),!((E=o?.metrics)===null||E===void 0)&&E.disableClientMetrics&&vn(!0),this.publicEventEmitter=new kn,this.internalEventEmitter=new xn,this.apiClient=new Tn(e,o?.apiKey,o?.api),this.messageHistoryClient=new On(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Fn(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const n=e.split(".")[1],o=fn.Buffer.from(n,"base64").toString("utf8");return JSON.parse(o)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,n,o){var c,s;if(!e&&!o?.apiKey)return"Either sessionToken or apiKey must be provided";if(o?.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const u=Sn((c=o?.api)===null||c===void 0?void 0:c.apiGateway);if(u)return u;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,Ae({organizationId:this.organizationId});const E=(s=l.type)===null||s===void 0?void 0:s.toLowerCase();if(E==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((E==="ephemeral"||E==="stateful")&&n)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!n)return"Missing persona config. Persona configuration must be provided when using apiKey";if(o?.voiceDetection){if(o.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(o.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof o.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(o.voiceDetection.endOfSpeechSensitivity<0||o.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const n={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(n.voiceDetection=this.clientOptions.voiceDetection),Object.keys(n).length!==0)return n}startSession(e){return pe(this,void 0,void 0,function*(){var n,o,c,s,u,l,E,p,_,d,y,g;const S=this.personaConfig,C=this.buildStartSessionOptionsForClient(),A=yield this.apiClient.startSession(S,C),{sessionId:I,clientConfig:b,engineHost:T,engineProtocol:D,signallingEndpoint:N}=A,{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:re,iceServers:V}=b;this.sessionId=I,Ae({sessionId:this.sessionId});const oe=!((n=this.clientOptions)===null||n===void 0)&&n.iceServers?this.clientOptions.iceServers:V;try{this.streamingClient=new Bn(I,{engine:{baseUrl:`${D}://${T}`},signalling:{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:re,url:{baseUrl:T,protocol:D,signallingPath:N}},iceServers:oe,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio?void 0:e,audioDeviceId:(c=this.clientOptions)===null||c===void 0?void 0:c.audioDeviceId,disableInputAudio:(s=this.clientOptions)===null||s===void 0?void 0:s.disableInputAudio},apiGateway:(l=(u=this.clientOptions)===null||u===void 0?void 0:u.api)===null||l===void 0?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:(_=(p=(E=this.clientOptions)===null||E===void 0?void 0:E.metrics)===null||p===void 0?void 0:p.showPeerConnectionStatsReport)!==null&&_!==void 0?_:!1,peerConnectionStatsReportOutputFormat:(g=(y=(d=this.clientOptions)===null||d===void 0?void 0:d.metrics)===null||y===void 0?void 0:y.peerConnectionStatsReportOutputFormat)!==null&&g!==void 0?g:"console"}},this.publicEventEmitter,this.internalEventEmitter)}catch(se){throw Ae({sessionId:null}),new $("Failed to initialize streaming client",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:se instanceof Error?se.message:String(se),sessionId:I})}return I})}startSessionIfNeeded(e){return pe(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new $("Session ID or streaming client is not available after starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return pe(this,void 0,void 0,function*(){var n;if(this._isStreaming)throw new Error("Already streaming");const o=bi();return Ae({attemptCorrelationId:o,sessionId:null}),ve(ne.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(c=>{var s;const u=[];let l=!1,E=!1;this.publicEventEmitter.addListener(x.VIDEO_STREAM_STARTED,p=>{u.push(p),l=!0,E&&c(u)}),this.publicEventEmitter.addListener(x.AUDIO_STREAM_STARTED,p=>{u.push(p),E=!0,l&&c(u)}),(s=this.streamingClient)===null||s===void 0||s.startConnection()})})}streamToVideoAndAudioElements(e,n,o){return pe(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,o)})}streamToVideoElement(e,n){return pe(this,void 0,void 0,function*(){var o;const c=bi();Ae({attemptCorrelationId:c,sessionId:null}),ve(ne.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio&&n&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(n)}catch(s){throw s instanceof $?s:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return pe(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const n=this.getActiveSessionId();if(!n)throw new Error("Failed to send user message: no active session");const o=new Date().toISOString().replace("Z",""),c=JSON.stringify({content:e,timestamp:o,session_id:n,message_type:"speech"});this.sendDataMessage(c)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const n=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(n)}stopStreaming(){return pe(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(x.CONNECTION_CLOSED,fe.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ae({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return pe(this,void 0,void 0,function*(){var n;if(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,n){this.publicEventEmitter.addListener(e,n)}removeListener(e,n){this.publicEventEmitter.removeListener(e,n)}getActiveSessionId(){return this.sessionId}}const Vn=(t,e)=>new $n(t,void 0,e),Q={SESSION_STARTED:"anam-agent:session-started",SESSION_ENDED:"anam-agent:session-ended",MESSAGE_RECEIVED:"anam-agent:message-received",MESSAGE_SENT:"anam-agent:message-sent",EXPANDED:"anam-agent:expanded",COLLAPSED:"anam-agent:collapsed",ERROR:"anam-agent:error",MIC_MUTED:"anam-agent:mic-muted",MIC_UNMUTED:"anam-agent:mic-unmuted"},Gn="https://api.anam.ai";function Ti(t){return/^[a-zA-Z0-9_-]{1,128}$/.test(t)}function jn(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}function Hn(t,e){return e===401||e===403?"This agent is not authorized. Check your agent ID.":e===404?"Agent not found. Check your agent ID.":e===429?"Too many requests. Please wait a moment.":e&&e>=500?"Server error. Please try again later.":t instanceof TypeError&&t.message==="Failed to fetch"?"Unable to connect. Check your network connection.":t instanceof Error&&t.message.length<80?t.message:"Something went wrong. Please try again."}function Wn(){return{client:z(null),connectionStatus:z("idle"),isStreaming:z(!1),isMuted:z(!1),messages:z([]),error:z(null),sessionId:z(null),avatarThumbnailUrl:z(null),avatarVideoUrl:z(null),personaName:z(null),serverConfig:z(null),isConfigured:z(!1),isReady:z(!1),generation:0,prevMessageCount:0,dispatch:null}}async function zn(t,e,n){if(t.isReady.value=!1,!Ti(e)){console.error("[AnamWidget] Invalid agent ID format:",e);return}try{const o=await fetch(`${n}/v1/personas/${e}/widget`);if(!o.ok){const s=o.status===404?"Agent not found. Check your agent ID.":o.status===401||o.status===403?"Not authorized. Check your agent ID.":"Server error. Please try again later.";console.error(`[AnamWidget] Failed to load widget config: ${s}`);return}const c=await o.json();t.avatarThumbnailUrl.value=c.persona?.avatarImageUrl||null,t.avatarVideoUrl.value=c.persona?.avatarVideoUrl||null,t.personaName.value=c.persona?.name||null,t.serverConfig.value=c.widgetConfig||null,t.isReady.value=!0}catch(o){console.error("[AnamWidget] Failed to load widget config:",o)}}async function qn(t,e,n,o,c){if(t.connectionStatus.value==="connecting"||t.connectionStatus.value==="connected")return;const s=++t.generation;t.connectionStatus.value="connecting",t.error.value=null;let u;try{let l;if(c)l=c;else{if(!Ti(e))throw new Error("Invalid agent ID format");const _=await fetch(`${n}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:e})});if(s!==t.generation)return;if(u=_.status,!_.ok){const y=await _.json().catch(()=>({}));throw new Error(y.error||`HTTP ${_.status}`)}l=(await _.json()).sessionToken}if(s!==t.generation)return;const E=Vn(l,{api:n?{baseUrl:n}:void 0,metrics:{disableClientMetrics:!0}});E.addListener(x.CONNECTION_ESTABLISHED,()=>{s===t.generation&&(t.connectionStatus.value="connected")}),E.addListener(x.VIDEO_STREAM_STARTED,()=>{s===t.generation&&(t.isStreaming.value=!0)}),E.addListener(x.AUDIO_STREAM_STARTED,()=>{}),E.addListener(x.MESSAGE_HISTORY_UPDATED,_=>{if(s===t.generation){for(let d=t.prevMessageCount;d<_.length;d++){const y=_[d];t.dispatch?.(Q.MESSAGE_RECEIVED,{role:y.role==="persona"?"agent":"user",content:y.content})}t.prevMessageCount=_.length,t.messages.value=[..._]}}),E.addListener(x.CONNECTION_CLOSED,(_,d)=>{if(s!==t.generation)return;const y=t.sessionId.value;t.connectionStatus.value="idle",t.isStreaming.value=!1,t.sessionId.value=null,t.dispatch?.(Q.SESSION_ENDED,{sessionId:y??"",reason:d??_})}),E.addListener(x.SESSION_READY,_=>{s===t.generation&&(t.sessionId.value=_,t.dispatch?.(Q.SESSION_STARTED,{sessionId:_}))});const p=await E.stream();if(s!==t.generation){try{await E.stopStreaming()}catch{}return}if(t.client.value=E,o&&p.length>0){const _=p.find(d=>d.getVideoTracks().length>0);_&&(o.srcObject=_)}}catch(l){if(s!==t.generation)return;console.error("[AnamWidget] Failed to start session:",l);const E=Hn(l,u);t.error.value=E,t.connectionStatus.value="error",t.client.value=null,t.dispatch?.(Q.ERROR,{code:u?`HTTP_${u}`:"SESSION_ERROR",message:E})}}async function Yn(t){const e=t.sessionId.value,n=t.connectionStatus.value!=="idle";if(t.generation++,t.client.value)try{await t.client.value.stopStreaming()}catch(o){console.error("[AnamWidget] Failed to stop session:",o)}t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.isMuted.value=!1,t.messages.value=[],t.sessionId.value=null,t.prevMessageCount=0,n&&t.dispatch?.(Q.SESSION_ENDED,{sessionId:e??"",reason:"USER_ENDED"})}function Kn(t,e){!t.client.value||t.connectionStatus.value!=="connected"||(t.client.value.sendUserMessage(e),t.dispatch?.(Q.MESSAGE_SENT,{content:e}))}function Jn(t){t.client.value&&(t.isMuted.value?(t.client.value.unmuteInputAudio(),t.isMuted.value=!1,t.dispatch?.(Q.MIC_UNMUTED,{})):(t.client.value.muteInputAudio(),t.isMuted.value=!0,t.dispatch?.(Q.MIC_MUTED,{})))}function Xn(t){t.generation++,t.client.value?.isStreaming()&&t.client.value.stopStreaming(),t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.isMuted.value=!1,t.messages.value=[],t.error.value=null,t.sessionId.value=null,t.avatarThumbnailUrl.value=null,t.avatarVideoUrl.value=null,t.personaName.value=null,t.serverConfig.value=null,t.prevMessageCount=0}function Zn(t,e,n,o){const c=Me();c.current||(c.current=Wn());const s=c.current;s.dispatch=o??null;const u=t||(n?jn(n).personaId:void 0),l=!!u||!!n;s.isConfigured.value!==l&&(s.isConfigured.value=l);const E=e||Gn;return{connectionStatus:s.connectionStatus,isStreaming:s.isStreaming,isMuted:s.isMuted,messages:s.messages,error:s.error,sessionId:s.sessionId,isConfigured:s.isConfigured,isReady:s.isReady,avatarThumbnailUrl:s.avatarThumbnailUrl,avatarVideoUrl:s.avatarVideoUrl,personaName:s.personaName,serverConfig:s.serverConfig,fetchWidgetConfig:()=>{if(!u){s.isReady.value=!0;return}zn(s,u,E)},startSession:p=>!u&&!n?(s.error.value="No agent ID or session token configured",Promise.resolve()):qn(s,u||"",E,p,n),stopSession:()=>Yn(s),sendMessage:p=>Kn(s,p),toggleMute:()=>Jn(s),cleanup:()=>Xn(s)}}function Qn(t,e,n){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:n}))}const er='@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-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid}}}@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;--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%;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}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-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 components;@layer utilities{.visible{visibility:visible}.block{display:block}.flex{display:flex}.inline{display:inline}.flex-shrink{flex-shrink:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.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,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))}}:host{--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:#18181b;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:DM Sans,system-ui,-apple-system,sans-serif;font-size:15px;line-height:1.5}@media(max-width:640px){:host{--anam-trigger-size:72px;--anam-sheet-width: calc(100vw - 24px) ;--anam-sheet-height: calc(100dvh - 100px) }}.anam-widget{z-index:9999;font-family:inherit}.anam-widget[data-layout=floating]{position:fixed}.anam-widget[data-layout=inline]{position:relative}.anam-trigger{width:var(--anam-trigger-size);height:var(--anam-trigger-size);cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:all .25s cubic-bezier(.4,0,.2,1);display:flex;overflow:hidden;box-shadow:0 2px 8px #00000014,0 8px 24px -4px #0000002e}.anam-trigger:hover{transform:scale(1.06);box-shadow:0 4px 12px #0000001a,0 12px 32px -4px #00000040}.anam-trigger:active{transform:scale(.97)}.anam-trigger img{object-fit:cover;width:100%;height:100%;display:block}.anam-sheet{width:var(--anam-sheet-width);aspect-ratio:16/10;max-height:var(--anam-sheet-height);border-radius:8px;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-widget[data-layout=inline] .anam-sheet{aspect-ratio:3/2;border-radius:8px;width:100%;max-height:none;animation:none}@keyframes sheetIn{0%{opacity:0;transform:translateY(8px)scale(.97)}to{opacity:1;transform:translateY(0)scale(1)}}.anam-video{object-fit:cover;background:#000;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-video[data-hidden=true]{visibility:hidden}.anam-overlay-idle{z-index:2;position:absolute;inset:0}.anam-overlay-idle img{object-fit:cover;width:100%;height:100%;display:block}.anam-preview-video{object-fit:cover;z-index:1;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-preview-fallback{z-index:0;position:absolute;inset:0}.anam-cta-pill{z-index:2;-webkit-backdrop-filter:blur(12px);color:#2a2220;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#ffffff8c;border:none;border-radius:999px;justify-content:center;align-items:center;gap:10px;padding:14px 28px;font-family:inherit;font-size:18px;font-weight:600;transition:all .2s;display:flex;position:absolute;bottom:20px;left:50%;transform:translate(-50%)}.anam-cta-pill:hover{background:#ffffffb3;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0;transform:translateY(-1px)}.anam-overlay-unconfigured{z-index:2;background:#111;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-unconfigured span{color:#ffffff59;letter-spacing:-.01em;font-size:14px;font-weight:400}.anam-overlay-loading{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:20px;display:flex;position:absolute;inset:0}.anam-overlay-loading span{color:#fffc;letter-spacing:-.01em;font-size:15px;font-weight:400}.anam-overlay-error{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-error-text{color:#fff9;text-align:center;max-width:260px;font-size:14px;line-height:1.5}.anam-overlay-error .anam-retry-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff1f;border:1px solid #ffffff1a;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s}.anam-overlay-error .anam-retry-btn:hover{background:#fff3}.anam-spinner{border:2.5px solid #ffffff1f;border-top-color:#fff;border-radius:50%;width:32px;height:32px;animation:.75s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}}.anam-close-btn{z-index:10;-webkit-backdrop-filter:blur(12px);color:#2a2220;cursor:pointer;background:#ffffff8c;border:none;border-radius:50%;justify-content:center;align-items:center;width:28px;height:28px;padding:0;transition:background .15s;display:flex;position:absolute;top:12px;right:12px}.anam-close-btn:hover{background:#ffffffb3}.anam-toast{z-index:10;-webkit-backdrop-filter:blur(16px);color:#18181b;letter-spacing:-.01em;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:#ffffffeb;border:1px solid #00000014;border-radius:999px;max-width:85%;padding:10px 22px;font-size:14px;font-weight:400;animation:.25s cubic-bezier(.16,1,.3,1) toastIn;position:absolute;bottom:80px;left:50%;overflow:hidden;transform:translate(-50%)}.anam-toast-out{animation:.4s forwards toastOut}@keyframes toastIn{0%{opacity:0;transform:translate(-50%)translateY(6px)}to{opacity:1;transform:translate(-50%)translateY(0)}}@keyframes toastOut{0%{opacity:1}to{opacity:0}}.anam-control-bar{z-index:10;background:0 0;justify-content:center;align-items:center;gap:8px;padding:0;display:flex;position:absolute;bottom:12px;left:12px;right:12px}.anam-ctl-btn{-webkit-backdrop-filter:blur(12px);color:#2a2220;cursor:pointer;background:#ffffff8c;border:none;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex}.anam-ctl-btn:hover{background:#ffffffb3}.anam-ctl-btn:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-input-wrap{flex:1;align-items:center;min-width:0;display:flex;position:relative}.anam-ctl-input{-webkit-backdrop-filter:blur(12px);color:#2a2220;background:#ffffff8c;border:none;border-radius:999px;outline:none;width:100%;padding:11px 44px 11px 18px;font-family:inherit;font-size:14px;transition:background .15s}.anam-ctl-input::placeholder{color:#2a222080}.anam-ctl-input:focus{background:#ffffffb3}.anam-ctl-input:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-send{color:#2a222080;cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:color .15s;display:flex;position:absolute;right:6px}.anam-ctl-send:hover{color:#2a2220}.anam-ctl-send:disabled{opacity:.35;cursor:not-allowed}.anam-watermark{z-index:11;opacity:.5;line-height:0;text-decoration:none;transition:opacity .15s;position:absolute;top:16px;left:16px}.anam-watermark:hover{opacity:.8}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}';class tr extends Se{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("[AnamWidget] Render error:",e)}render(){return this.state.hasError?w("div",{class:"anam-overlay-error",children:w("div",{class:"anam-overlay-error-text",children:"Widget failed to load"})}):this.props.children}}function yt(t,e){const n={...t};for(const o of Object.keys(e)){const c=e[o];c!==void 0&&(c!==null&&typeof c=="object"&&!Array.isArray(c)&&typeof n[o]=="object"&&n[o]!==null&&!Array.isArray(n[o])?n[o]=yt(n[o],c):n[o]=c)}return n}function St(t){if(t!==void 0)return t==="true"}function ir(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const n=St(t["ui-mute-button"]);n!==void 0&&(e.showMuteButton=n);const o=St(t["ui-text-input"]);o!==void 0&&(e.showTextInput=o);const c=St(t["ui-captions"]);return c!==void 0&&(e.showCaptions=c),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const nr=()=>w("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round",children:w("path",{d:"M18 6L6 18M6 6l12 12"})}),rr=()=>w("svg",{width:"24",height:"24",viewBox:"0 0 640 640",fill:"currentColor",children:w("path",{d:"M187.2 100.9C174.8 94.1 159.8 94.4 147.6 101.6C135.4 108.8 128 121.9 128 136L128 504C128 518.1 135.5 531.2 147.6 538.4C159.7 545.6 174.8 545.9 187.2 539.1L523.2 355.1C536 348.1 544 334.6 544 320C544 305.4 536 291.9 523.2 284.9L187.2 100.9z"})}),or=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),w("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),sr=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),w("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),w("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),ar=()=>w("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),w("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),wt=()=>w("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[w("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),w("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function lr({config:t,session:e,videoRef:n,avatarSrc:o,avatarVideoSrc:c,displayCta:s,onCollapse:u,onStop:l}){const E=Me(null),[p,_]=We(""),[d,y]=We(null),[g,S]=We(!1),C=Me(null),A=e.connectionStatus.value==="connected",I=e.connectionStatus.value==="connecting",b=e.connectionStatus.value==="error",T=e.isStreaming.value,D=!I&&!A&&!b,N=qe(async()=>{n.current&&await e.startSession(n.current)},[e.startSession]),Y=qe(()=>{if(!p.trim())return;const V=p.trim();e.sendMessage(V),_(""),E.current?.focus(),C.current&&clearTimeout(C.current),S(!1),y(V),C.current=window.setTimeout(()=>{S(!0),C.current=window.setTimeout(()=>{y(null),S(!1)},400)},2600)},[p]),re=qe(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Y())},[Y]);return ze(()=>()=>{C.current&&clearTimeout(C.current)},[]),w("div",{class:"anam-sheet",children:[w("video",{ref:n,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":T?void 0:"true"}),D&&(e.isConfigured.value?w("div",{class:"anam-overlay-idle",children:[c?w("video",{src:c,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:V=>{V.target.style.display="none"}}):null,o?w("img",{src:o,alt:"Avatar",class:c?"anam-preview-fallback":void 0}):w(wt,{}),w("button",{class:"anam-cta-pill",onClick:N,children:[w(rr,{}),s]})]}):w("div",{class:"anam-overlay-unconfigured",children:[w(wt,{}),w("span",{children:"Agent not configured"})]})),I&&w("div",{class:"anam-overlay-loading",children:[w("span",{class:"anam-spinner"}),w("span",{children:"Starting your conversation..."})]}),b&&w("div",{class:"anam-overlay-error",children:[w("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),w("button",{class:"anam-retry-btn",onClick:N,children:"Try Again"})]}),(u||l&&(A||I||T))&&w("button",{class:"anam-close-btn",onClick:u||l,"aria-label":u?"Close":"End call",children:w(nr,{})}),(A||T)&&w(le,{children:[d&&w("div",{class:`anam-toast ${g?"anam-toast-out":""}`,children:d}),w("div",{class:"anam-control-bar",children:[t.showMuteButton&&w("button",{class:`anam-ctl-btn ${e.isMuted.value?"anam-ctl-btn-muted":""}`,onClick:()=>e.toggleMute(),"aria-label":e.isMuted.value?"Unmute":"Mute",children:e.isMuted.value?w(sr,{}):w(or,{})}),t.showTextInput&&w("div",{class:"anam-ctl-input-wrap",children:[w("input",{ref:E,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:p,onInput:V=>_(V.target.value),onKeyDown:re,disabled:!A}),w("button",{class:"anam-ctl-send",onClick:Y,disabled:!A||!p.trim(),"aria-label":"Send message",children:w(ar,{})})]})]})]}),!t.removeWatermark&&w("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:w("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[w("path",{d:"M18.1491 28.1986L16.2127 21.63L6.3408 21.63L4.40439 28.1986H0L9.03659 -1.79687L13.4789 -1.79687L22.5535 28.1986H18.1491ZM7.47986 17.8331L15.0736 17.8331L11.2767 4.96161L7.47986 17.8331Z"}),w("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),w("path",{d:"M61.0239 28.1984V7.69518L85.7037 7.69518V28.1984H81.5271V11.4921L75.4521 11.4921V28.1984L71.2755 28.1984V11.4921L65.2005 11.4921V28.1984H61.0239Z"}),w("path",{d:"M42.8948 7.69518L57.7026 7.69518V28.1984L53.5261 28.1984V27.1353C52.4629 28.0466 51.0201 28.5781 49.3495 28.5781C45.4007 28.5781 42.8948 25.7305 42.8948 21.2501C42.8948 16.8457 45.4007 14.074 49.3495 14.074C51.0201 14.074 52.4629 14.5676 53.5261 15.4788V11.3022L42.8948 11.3022V7.69518ZM50.4885 24.7812C52.6148 24.7812 53.9437 23.4143 53.9057 21.2501C53.8678 19.0859 52.5389 17.681 50.4885 17.681C48.4003 17.681 47.0713 19.0859 47.0713 21.2501C47.0713 23.4143 48.4003 24.7812 50.4885 24.7812Z"})]})})]})}function cr(t){return w(le,{children:[w("style",{children:er}),w(tr,{children:w(ur,{...t})})]})}function ur(t){const e=Me(null),n=Me(null),o=qe((T,D)=>{const N=n.current?.getRootNode();N&&N instanceof ShadowRoot&&Qn(N.host,T,D)},[]);t["agent-id"]&&t["session-token"]&&console.warn("[AnamWidget] Both agent-id and session-token are set. Use one or the other. Ignoring agent-id.");const c=t["session-token"]?void 0:t["agent-id"],s=Zn(c,t["api-base-url"],t["session-token"],o);ze(()=>()=>{s.cleanup()},[]);const u=Ce(()=>ir(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["call-to-action"]]),l=Ce(()=>{const T=s.serverConfig.value;return yt(yt({..._t},T??{}),u)},[s.serverConfig.value,u]),E=Ei(l.layout==="floating"?l.initialState:"expanded");ze(()=>{l.layout==="inline"?E.value="expanded":E.value=l.initialState},[l.layout,l.initialState]),ze(()=>{s.fetchWidgetConfig()},[c,t["api-base-url"],t["session-token"]]);const p=t["avatar-url"]||s.avatarThumbnailUrl.value||null,_=t["avatar-video-url"]||s.avatarVideoUrl.value||null,y=t["agent-name"]||s.personaName.value,g=l.callToAction===_t.callToAction&&y?`Talk to ${y}`:l.callToAction,S=Ce(()=>{if(l.layout==="inline")return"";const T=cn(l.position);return Object.entries(T).map(([D,N])=>`${D}: ${N}`).join("; ")},[l.layout,l.position]),C=l.layout==="floating",A=()=>{E.value="expanded",o(Q.EXPANDED,{})},I=async()=>{s.connectionStatus.value!=="idle"&&await s.stopSession(),E.value="minimized",o(Q.COLLAPSED,{})},b=C?E.value==="expanded":!0;return s.isReady.value?w("div",{ref:n,class:"anam-widget","data-layout":l.layout,"data-state":E.value,style:S,children:[C&&E.value==="minimized"&&w("button",{class:"anam-trigger",onClick:A,"aria-label":g,children:p?w("img",{src:p,alt:"Avatar"}):w(wt,{})}),b&&w(lr,{config:l,session:s,videoRef:e,avatarSrc:p,avatarVideoSrc:_,displayCta:g,onCollapse:C?I:null,onStop:C?null:()=>s.stopSession()})]}):null}const dr=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","call-to-action","avatar-url","avatar-video-url","agent-name"];function Ct(t="anam-agent"){Wi(cr,t,[...dr],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Ct()):Ct()),ae.DefaultConfig=_t,ae.WidgetEventNames=Q,ae.registerWidget=Ct,Object.defineProperty(ae,Symbol.toStringTag,{value:"Module"})}));
