@anam-ai/agent-widget 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/index.js +2780 -2143
- package/dist/index.umd.js +1 -1
- package/package.json +2 -2
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(le,oe){typeof exports=="object"&&typeof module<"u"?oe(exports):typeof define=="function"&&define.amd?define(["exports"],oe):(le=typeof globalThis<"u"?globalThis:le||self,oe(le.AnamAgentWidget={}))})(this,(function(le){"use strict";var oe,x,kt,Mt,me,Ut,Bt,Pt,Ft,st,at,lt,xe={},$t=[],Wi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ve=Array.isArray;function ee(t,e){for(var i in e)t[i]=e[i];return t}function ct(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Se(t,e,i){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?oe.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)u[s]===void 0&&(u[s]=t.defaultProps[s]);return Le(t,u,o,c,null)}function Le(t,e,i,o,c){var s={type:t,props:e,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:c??++kt,__i:-1,__u:0};return c==null&&x.vnode!=null&&x.vnode(s),s}function ce(t){return t.children}function Ce(t,e){this.props=t,this.context=e}function Te(t,e){if(e==null)return t.__?Te(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?Te(t):null}function Vt(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return Vt(t)}}function Gt(t){(!t.__d&&(t.__d=!0)&&me.push(t)&&!Ge.__r++||Ut!=x.debounceRendering)&&((Ut=x.debounceRendering)||Bt)(Ge)}function Ge(){for(var t,e,i,o,c,s,u,a=1;me.length;)me.length>a&&me.sort(Pt),t=me.shift(),a=me.length,t.__d&&(i=void 0,o=void 0,c=(o=(e=t).__v).__e,s=[],u=[],e.__P&&((i=ee({},o)).__v=o.__v+1,x.vnode&&x.vnode(i),ut(e.__P,i,o,e.__n,e.__P.namespaceURI,32&o.__u?[c]:null,s,c??Te(o),!!(32&o.__u),u),i.__v=o.__v,i.__.__k[i.__i]=i,qt(s,i,u),o.__e=o.__=null,i.__e!=c&&Vt(i)));Ge.__r=0}function jt(t,e,i,o,c,s,u,a,E,p,f){var d,y,g,S,T,A,w,I=o&&o.__k||$t,R=e.length;for(E=zi(i,e,I,E,R),d=0;d<R;d++)(g=i.__k[d])!=null&&(y=g.__i==-1?xe:I[g.__i]||xe,g.__i=d,A=ut(t,g,y,c,s,u,a,E,p,f),S=g.__e,g.ref&&y.ref!=g.ref&&(y.ref&&ht(y.ref,null,g),f.push(g.ref,g.__c||S,g)),T==null&&S!=null&&(T=S),(w=!!(4&g.__u))||y.__k===g.__k?E=Ht(g,E,t,w):typeof g.type=="function"&&A!==void 0?E=A:S&&(E=S.nextSibling),g.__u&=-7);return i.__e=T,E}function zi(t,e,i,o,c){var s,u,a,E,p,f=i.length,d=f,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]=Le(null,u,null,null,null):Ve(u)?u=t.__k[s]=Le(ce,{children:u},null,null,null):u.constructor===void 0&&u.__b>0?u=t.__k[s]=Le(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,a=null,(p=u.__i=qi(u,i,E,d))!=-1&&(d--,(a=i[p])&&(a.__u|=2)),a==null||a.__v==null?(p==-1&&(c>f?y--:c<f&&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<f;s++)(a=i[s])!=null&&(2&a.__u)==0&&(a.__e==o&&(o=Te(a)),Kt(a,a));return o}function Ht(t,e,i,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=Ht(c[s],e,i,o));return e}t.__e!=e&&(o&&(e&&t.type&&!e.parentNode&&(e=Te(t)),i.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function qi(t,e,i,o){var c,s,u,a=t.key,E=t.type,p=e[i],f=p!=null&&(2&p.__u)==0;if(p===null&&a==null||f&&a==p.key&&E==p.type)return i;if(o>(f?1:0)){for(c=i-1,s=i+1;c>=0||s<e.length;)if((p=e[u=c>=0?c--:s++])!=null&&(2&p.__u)==0&&a==p.key&&E==p.type)return u}return-1}function Wt(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Wi.test(e)?i:i+"px"}function je(t,e,i,o,c){var s,u;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof o=="string"&&(t.style.cssText=o=""),o)for(e in o)i&&e in i||Wt(t.style,e,"");if(i)for(e in i)o&&i[e]==o[e]||Wt(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Ft,"$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]=i,i?o?i.u=o.u:(i.u=st,t.addEventListener(e,s?lt:at,s)):t.removeEventListener(e,s?lt:at,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]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function zt(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=st++;else if(e.t<i.u)return;return i(x.event?x.event(e):e)}}}function ut(t,e,i,o,c,s,u,a,E,p){var f,d,y,g,S,T,A,w,I,R,D,N,j,ae,G,ie,ye,X=e.type;if(e.constructor!==void 0)return null;128&i.__u&&(E=!!(32&i.__u),s=[a=e.__e=i.__e]),(f=x.__b)&&f(e);e:if(typeof X=="function")try{if(w=e.props,I="prototype"in X&&X.prototype.render,R=(f=X.contextType)&&o[f.__c],D=f?R?R.props.value:f.__:o,i.__c?A=(d=e.__c=i.__c).__=d.__E:(I?e.__c=d=new X(w,D):(e.__c=d=new Ce(w,D),d.constructor=X,d.render=Ki),R&&R.sub(d),d.state||(d.state={}),d.__n=o,y=d.__d=!0,d.__h=[],d._sb=[]),I&&d.__s==null&&(d.__s=d.state),I&&X.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ee({},d.__s)),ee(d.__s,X.getDerivedStateFromProps(w,d.__s))),g=d.props,S=d.state,d.__v=e,y)I&&X.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),I&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(I&&X.getDerivedStateFromProps==null&&w!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,D),e.__v==i.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,D)===!1){for(e.__v!=i.__v&&(d.props=w,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(ne){ne&&(ne.__=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(w,d.__s,D),I&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,S,T)})}if(d.context=D,d.props=w,d.__P=t,d.__e=!1,j=x.__r,ae=0,I){for(d.state=d.__s,d.__d=!1,j&&j(e),f=d.render(d.props,d.state,d.context),G=0;G<d._sb.length;G++)d.__h.push(d._sb[G]);d._sb=[]}else do d.__d=!1,j&&j(e),f=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++ae<25);d.state=d.__s,d.getChildContext!=null&&(o=ee(ee({},o),d.getChildContext())),I&&!y&&d.getSnapshotBeforeUpdate!=null&&(T=d.getSnapshotBeforeUpdate(g,S)),ie=f,f!=null&&f.type===ce&&f.key==null&&(ie=Yt(f.props.children)),a=jt(t,Ve(ie)?ie:[ie],e,i,o,c,s,u,a,E,p),d.base=e.__e,e.__u&=-161,d.__h.length&&u.push(d),A&&(d.__E=d.__=null)}catch(ne){if(e.__v=null,E||s!=null)if(ne.then){for(e.__u|=E?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,e.__e=a}else{for(ye=s.length;ye--;)ct(s[ye]);dt(e)}else e.__e=i.__e,e.__k=i.__k,ne.then||dt(e);x.__e(ne,e,i)}else s==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Yi(i.__e,e,i,o,c,s,u,E,p);return(f=x.diffed)&&f(e),128&e.__u?void 0:a}function dt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(dt)}function qt(t,e,i){for(var o=0;o<i.length;o++)ht(i[o],i[++o],i[++o]);x.__c&&x.__c(e,t),t.some(function(c){try{t=c.__h,c.__h=[],t.some(function(s){s.call(c)})}catch(s){x.__e(s,c.__v)}})}function Yt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ve(t)?t.map(Yt):ee({},t)}function Yi(t,e,i,o,c,s,u,a,E){var p,f,d,y,g,S,T,A=i.props||xe,w=e.props,I=e.type;if(I=="svg"?c="http://www.w3.org/2000/svg":I=="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==!!I&&(I?g.localName==I:g.nodeType==3)){t=g,s[p]=null;break}}if(t==null){if(I==null)return document.createTextNode(w);t=document.createElementNS(c,I,w.is&&w),a&&(x.__m&&x.__m(e,s),a=!1),s=null}if(I==null)A===w||a&&t.data==w||(t.data=w);else{if(s=s&&oe.call(t.childNodes),!a&&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 w)){if(p=="value"&&"defaultValue"in w||p=="checked"&&"defaultChecked"in w)continue;je(t,p,null,g,c)}}for(p in w)g=w[p],p=="children"?y=g:p=="dangerouslySetInnerHTML"?f=g:p=="value"?S=g:p=="checked"?T=g:a&&typeof g!="function"||A[p]===g||je(t,p,g,A[p],c);if(f)a||d&&(f.__html==d.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(d&&(t.innerHTML=""),jt(e.type=="template"?t.content:t,Ve(y)?y:[y],e,i,o,I=="foreignObject"?"http://www.w3.org/1999/xhtml":c,s,u,s?s[0]:i.__k&&Te(i,0),a,E),s!=null)for(p=s.length;p--;)ct(s[p]);a||(p="value",I=="progress"&&S==null?t.removeAttribute("value"):S!=null&&(S!==t[p]||I=="progress"&&!S||I=="option"&&S!=A[p])&&je(t,p,S,A[p],c),p="checked",T!=null&&T!=t[p]&&je(t,p,T,A[p],c))}return t}function ht(t,e,i){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){x.__e(c,i)}}function Kt(t,e,i){var o,c;if(x.unmount&&x.unmount(t),(o=t.ref)&&(o.current&&o.current!=t.__e||ht(o,null,e)),(o=t.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){x.__e(s,e)}o.base=o.__P=null}if(o=t.__k)for(c=0;c<o.length;c++)o[c]&&Kt(o[c],e,i||typeof t.type!="function");i||ct(t.__e),t.__c=t.__=t.__e=void 0}function Ki(t,e,i){return this.constructor(t,i)}function He(t,e,i){var o,c,s,u;e==document&&(e=document.documentElement),x.__&&x.__(t,e),c=(o=typeof i=="function")?null:i&&i.__k||e.__k,s=[],u=[],ut(e,t=(!o&&i||e).__k=Se(ce,null,[t]),c||xe,xe,e.namespaceURI,!o&&i?[i]:c?null:e.firstChild?oe.call(e.childNodes):null,s,!o&&i?i:c?c.__e:e.firstChild,o,u),qt(s,t,u)}function Jt(t,e){He(t,e,Jt)}function Xt(t,e,i){var o,c,s,u,a=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]:a[s]=e[s]===void 0&&u!=null?u[s]:e[s];return arguments.length>2&&(a.children=arguments.length>3?oe.call(arguments,2):i),Le(t.type,a,o||t.key,c||t.ref,null)}oe=$t.slice,x={__e:function(t,e,i,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(a){t=a}throw t}},kt=0,Mt=function(t){return t!=null&&t.constructor===void 0},Ce.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ee({},this.state),typeof t=="function"&&(t=t(ee({},i),this.props)),t&&ee(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Gt(this))},Ce.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Gt(this))},Ce.prototype.render=ce,me=[],Bt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Pt=function(t,e){return t.__v.__b-e.__v.__b},Ge.__r=0,Ft=/(PointerCapture)$|Capture$/i,st=0,at=zt(!1),lt=zt(!0);function We(){return We=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(t[o]=i[o])}return t},We.apply(this,arguments)}function Zt(t,e){if(t==null)return{};var i,o,c={},s=Object.keys(t);for(o=0;o<s.length;o++)e.indexOf(i=s[o])>=0||(c[i]=t[i]);return c}var Ji=["context","children"],Xi=["useFragment"];function Zi(t,e,i,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(){en.call(this,o)},c.prototype.attributeChangedCallback=tn,c.prototype.disconnectedCallback=nn,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),c.observedAttributes=i,t.formAssociated&&(c.formAssociated=!0),i.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 a=typeof u;u!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(s,u)}})}),customElements.define(e||t.tagName||t.displayName||t.name,c),c}function Qi(t){this.getChildContext=function(){return t.context};var e=t.children,i=Zt(t,Ji);return Xt(e,i)}function en(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Se(Qi,We({},this._props,{context:e.detail.context}),ti(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?Jt:He)(this._vdom,this._root)}function Qt(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function tn(t,e,i){if(this._vdom){var o={};o[t]=i=i??void 0,o[Qt(t)]=i,this._vdom=Xt(this._vdom,o),He(this._vdom,this._root)}}function nn(){He(this._vdom=null,this._root)}function ei(t,e){var i=this,o=t.useFragment,c=Zt(t,Xi);return Se(o?ce:"slot",We({},c,{ref:function(s){s?(i.ref=s,i._listener||(i._listener=function(u){u.stopPropagation(),u.detail.context=e},s.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function ti(t,e,i){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var o=[],c={},s=0,u=t.attributes,a=t.childNodes;for(s=u.length;s--;)u[s].name!=="slot"&&(c[u[s].name]=u[s].value,c[Qt(u[s].name)]=u[s].value);for(s=a.length;s--;){var E=ti(a[s],null,i),p=a[s].slot;p?c[p]=Se(ei,{name:p},E):o[s]=E}var f=!(!i||!i.shadow),d=e?Se(ei,{useFragment:!f},o):o;return!f&&e&&(t.innerHTML=""),Se(e||t.nodeName.toLowerCase(),c,d)}var rn=0;function C(t,e,i,o,c,s){e||(e={});var u,a,E=e;if("ref"in E)for(a in E={},e)a=="ref"?u=e[a]:E[a]=e[a];var p={type:t,props:E,key:i,ref:u,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--rn,__i:-1,__u:0,__source:c,__self:s};if(typeof t=="function"&&(u=t.defaultProps))for(a in u)E[a]===void 0&&(E[a]=u[a]);return x.vnode&&x.vnode(p),p}var De,P,ft,ii,ke=0,ni=[],$=x,ri=$.__b,oi=$.__r,si=$.diffed,ai=$.__c,li=$.unmount,ci=$.__;function pt(t,e){$.__h&&$.__h(P,t,ke||e),ke=0;var i=P.__H||(P.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function ze(t){return ke=1,on(hi,t)}function on(t,e,i){var o=pt(De++,2);if(o.t=t,!o.__c&&(o.__=[hi(void 0,e),function(a){var E=o.__N?o.__N[0]:o.__[0],p=o.t(E,a);E!==p&&(o.__N=[p,o.__[1]],o.__c.setState({}))}],o.__c=P,!P.__f)){var c=function(a,E,p){if(!o.__c.__H)return!0;var f=o.__c.__H.__.filter(function(y){return!!y.__c});if(f.every(function(y){return!y.__N}))return!s||s.call(this,a,E,p);var d=o.__c.props!==a;return f.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,a,E,p)||d};P.__f=!0;var s=P.shouldComponentUpdate,u=P.componentWillUpdate;P.componentWillUpdate=function(a,E,p){if(this.__e){var f=s;s=void 0,c(a,E,p),s=f}u&&u.call(this,a,E,p)},P.shouldComponentUpdate=c}return o.__N||o.__}function qe(t,e){var i=pt(De++,3);!$.__s&&di(i.__H,e)&&(i.__=t,i.u=e,P.__H.__h.push(i))}function Me(t){return ke=5,Ie(function(){return{current:t}},[])}function Ie(t,e){var i=pt(De++,7);return di(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ye(t,e){return ke=8,Ie(function(){return t},e)}function sn(){for(var t;t=ni.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Ke),t.__H.__h.forEach(_t),t.__H.__h=[]}catch(e){t.__H.__h=[],$.__e(e,t.__v)}}$.__b=function(t){P=null,ri&&ri(t)},$.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ci&&ci(t,e)},$.__r=function(t){oi&&oi(t),De=0;var e=(P=t.__c).__H;e&&(ft===P?(e.__h=[],P.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Ke),e.__h.forEach(_t),e.__h=[],De=0)),ft=P},$.diffed=function(t){si&&si(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ni.push(e)!==1&&ii===$.requestAnimationFrame||((ii=$.requestAnimationFrame)||an)(sn)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),ft=P=null},$.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Ke),i.__h=i.__h.filter(function(o){return!o.__||_t(o)})}catch(o){e.some(function(c){c.__h&&(c.__h=[])}),e=[],$.__e(o,i.__v)}}),ai&&ai(t,e)},$.unmount=function(t){li&&li(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(o){try{Ke(o)}catch(c){e=c}}),i.__H=void 0,e&&$.__e(e,i.__v))};var ui=typeof requestAnimationFrame=="function";function an(t){var e,i=function(){clearTimeout(o),ui&&cancelAnimationFrame(e),setTimeout(t)},o=setTimeout(i,35);ui&&(e=requestAnimationFrame(i))}function Ke(t){var e=P,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),P=e}function _t(t){var e=P;t.__c=t.__(),P=e}function di(t,e){return!t||t.length!==e.length||e.some(function(i,o){return i!==t[o]})}function hi(t,e){return typeof e=="function"?e(t):e}var ln=Symbol.for("preact-signals");function Je(){if(ue>1)ue--;else{for(var t,e=!1;Ue!==void 0;){var i=Ue;for(Ue=void 0,Et++;i!==void 0;){var o=i.o;if(i.o=void 0,i.f&=-3,!(8&i.f)&&_i(i))try{i.c()}catch(c){e||(t=c,e=!0)}i=o}}if(Et=0,ue--,e)throw t}}function cn(t){if(ue>0)return t();ue++;try{return t()}finally{Je()}}var L=void 0;function fi(t){var e=L;L=void 0;try{return t()}finally{L=e}}var Ue=void 0,ue=0,Et=0,Xe=0;function pi(t){if(L!==void 0){var e=t.n;if(e===void 0||e.t!==L)return e={i:0,S:t,p:L.s,n:void 0,t:L,e:void 0,x:void 0,r:e},L.s!==void 0&&(L.s.n=e),L.s=e,t.n=e,32&L.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=L.s,e.n=void 0,L.s.n=e,L.s=e),e}}function W(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}W.prototype.brand=ln,W.prototype.h=function(){return!0},W.prototype.S=function(t){var e=this,i=this.t;i!==t&&t.e===void 0&&(t.x=i,this.t=t,i!==void 0?i.e=t:fi(function(){var o;(o=e.W)==null||o.call(e)}))},W.prototype.U=function(t){var e=this;if(this.t!==void 0){var i=t.e,o=t.x;i!==void 0&&(i.x=o,t.e=void 0),o!==void 0&&(o.e=i,t.x=void 0),t===this.t&&(this.t=o,o===void 0&&fi(function(){var c;(c=e.Z)==null||c.call(e)}))}},W.prototype.subscribe=function(t){var e=this;return Be(function(){var i=e.value,o=L;L=void 0;try{t(i)}finally{L=o}},{name:"sub"})},W.prototype.valueOf=function(){return this.value},W.prototype.toString=function(){return this.value+""},W.prototype.toJSON=function(){return this.value},W.prototype.peek=function(){var t=L;L=void 0;try{return this.value}finally{L=t}},Object.defineProperty(W.prototype,"value",{get:function(){var t=pi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Et>100)throw new Error("Cycle detected");this.v=t,this.i++,Xe++,ue++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function Y(t,e){return new W(t,e)}function _i(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 Ei(t){for(var e=t.s;e!==void 0;e=e.n){var i=e.S.n;if(i!==void 0&&(e.r=i),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function mi(t){for(var e=t.s,i=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)):i=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=o}t.s=i}function ge(t,e){W.call(this,void 0),this.x=t,this.s=void 0,this.g=Xe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ge.prototype=new W,ge.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Xe))return!0;if(this.g=Xe,this.f|=1,this.i>0&&!_i(this))return this.f&=-2,!0;var t=L;try{Ei(this),L=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(i){this.v=i,this.f|=16,this.i++}return L=t,mi(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)}W.prototype.S.call(this,t)},ge.prototype.U=function(t){if(this.t!==void 0&&(W.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=pi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function gi(t,e){return new ge(t,e)}function vi(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ue++;var i=L;L=void 0;try{e()}catch(o){throw t.f&=-2,t.f|=8,mt(t),o}finally{L=i,Je()}}}function mt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,vi(t)}function un(t){if(L!==this)throw new Error("Out-of-order effect");mi(this),L=t,this.f&=-2,8&this.f&&mt(this),Je()}function we(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}we.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()}},we.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,vi(this),Ei(this),ue++;var t=L;return L=this,un.bind(this,t)},we.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},we.prototype.d=function(){this.f|=8,1&this.f||mt(this)},we.prototype.dispose=function(){this.d()};function Be(t,e){var i=new we(t,e);try{i.c()}catch(c){throw i.d(),c}var o=i.d.bind(i);return o[Symbol.dispose]=o,o}var yi,gt,dn=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Si=[];Be(function(){yi=this.N})();function Ae(t,e){x[t]=e.bind(null,x[t]||function(){})}function Ze(t){gt&>(),gt=t&&t.S()}function Ci(t){var e=this,i=t.data,o=Ti(i);o.value=i;var c=Ie(function(){for(var a=e,E=e.__v;E=E.__;)if(E.__c){E.__c.__$f|=4;break}var p=gi(function(){var g=o.value.value;return g===0?0:g===!0?"":g||""}),f=gi(function(){return!Array.isArray(p.value)&&!Mt(p.value)}),d=Be(function(){if(this.N=Ii,f.value){var g=p.value;a.__v&&a.__v.__e&&a.__v.__e.nodeType===3&&(a.__v.__e.data=g)}}),y=e.__$u.d;return e.__$u.d=function(){d(),y.call(this)},[f,p]},[]),s=c[0],u=c[1];return s.value?u.peek():u.value}Ci.displayName="ReactiveTextNode",Object.defineProperties(W.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ci},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Ae("__b",function(t,e){if(typeof e.type=="string"){var i,o=e.props;for(var c in o)if(c!=="children"){var s=o[c];s instanceof W&&(i||(e.__np=i={}),i[c]=s,o[c]=s.peek())}}t(e)}),Ae("__r",function(t,e){if(e.type!==ce){Ze();var i,o=e.__c;o&&(o.__$f&=-2,(i=o.__$u)===void 0&&(o.__$u=i=(function(c,s){var u;return Be(function(){u=this},{name:s}),u.c=c,u})(function(){var c;dn&&((c=i.y)==null||c.call(i)),o.__$f|=1,o.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Ze(i)}t(e)}),Ae("__e",function(t,e,i,o){Ze(),t(e,i,o)}),Ae("diffed",function(t,e){Ze();var i;if(typeof e.type=="string"&&(i=e.__e)){var o=e.__np,c=e.props;if(o){var s=i.U;if(s)for(var u in s){var a=s[u];a!==void 0&&!(u in o)&&(a.d(),s[u]=void 0)}else s={},i.U=s;for(var E in o){var p=s[E],f=o[E];p===void 0?(p=hn(i,E,f,c),s[E]=p):p.o(f,c)}}}t(e)});function hn(t,e,i,o){var c=e in t&&t.ownerSVGElement===void 0,s=Y(i);return{o:function(u,a){s.value=u,o=a},d:Be(function(){this.N=Ii;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))})}}Ae("unmount",function(t,e){if(typeof e.type=="string"){var i=e.__e;if(i){var o=i.U;if(o){i.U=void 0;for(var c in o){var s=o[c];s&&s.d()}}}}else{var u=e.__c;if(u){var a=u.__$u;a&&(u.__$u=void 0,a.d())}}t(e)}),Ae("__h",function(t,e,i,o){(o<3||o===9)&&(e.__$f|=2),t(e,i,o)}),Ce.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var i=this.__$u,o=i&&i.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 a in this.props)if(!(a in t))return!0;return!1};function Ti(t,e){return ze(function(){return Y(t,e)})[0]}var fn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function pn(){cn(function(){for(var t;t=Si.shift();)yi.call(t)})}function Ii(){Si.push(this)===1&&(x.requestAnimationFrame||fn)(pn)}const vt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},Qe={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}},_n=new Set(["top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left"]);function En(t){if(Qe[t])return Qe[t];const e=t.match(/^\[(.+)\]$/);if(!e)return Qe["bottom-right"];const i={};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(!_n.has(u))continue;const a=c.slice(s+1);/^[\w.%-]+$/.test(a)&&(i[u]=/^\d+$/.test(a)?`${a}px`:a)}return Object.keys(i).length>0?i:Qe["bottom-right"]}var yt={},Pe={},wi;function mn(){if(wi)return Pe;wi=1,Pe.byteLength=a,Pe.toByteArray=p,Pe.fromByteArray=y;for(var t=[],e=[],i=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 T=g.indexOf("=");T===-1&&(T=S);var A=T===S?0:4-T%4;return[T,A]}function a(g){var S=u(g),T=S[0],A=S[1];return(T+A)*3/4-A}function E(g,S,T){return(S+T)*3/4-T}function p(g){var S,T=u(g),A=T[0],w=T[1],I=new i(E(g,A,w)),R=0,D=w>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)],I[R++]=S>>16&255,I[R++]=S>>8&255,I[R++]=S&255;return w===2&&(S=e[g.charCodeAt(N)]<<2|e[g.charCodeAt(N+1)]>>4,I[R++]=S&255),w===1&&(S=e[g.charCodeAt(N)]<<10|e[g.charCodeAt(N+1)]<<4|e[g.charCodeAt(N+2)]>>2,I[R++]=S>>8&255,I[R++]=S&255),I}function f(g){return t[g>>18&63]+t[g>>12&63]+t[g>>6&63]+t[g&63]}function d(g,S,T){for(var A,w=[],I=S;I<T;I+=3)A=(g[I]<<16&16711680)+(g[I+1]<<8&65280)+(g[I+2]&255),w.push(f(A));return w.join("")}function y(g){for(var S,T=g.length,A=T%3,w=[],I=16383,R=0,D=T-A;R<D;R+=I)w.push(d(g,R,R+I>D?D:R+I));return A===1?(S=g[T-1],w.push(t[S>>2]+t[S<<4&63]+"==")):A===2&&(S=(g[T-2]<<8)+g[T-1],w.push(t[S>>10]+t[S>>4&63]+t[S<<2&63]+"=")),w.join("")}return Pe}var et={};var Ai;function gn(){return Ai||(Ai=1,et.read=function(t,e,i,o,c){var s,u,a=c*8-o-1,E=(1<<a)-1,p=E>>1,f=-7,d=i?c-1:0,y=i?-1:1,g=t[e+d];for(d+=y,s=g&(1<<-f)-1,g>>=-f,f+=a;f>0;s=s*256+t[e+d],d+=y,f-=8);for(u=s&(1<<-f)-1,s>>=-f,f+=o;f>0;u=u*256+t[e+d],d+=y,f-=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)},et.write=function(t,e,i,o,c,s){var u,a,E,p=s*8-c-1,f=(1<<p)-1,d=f>>1,y=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=o?0:s-1,S=o?1:-1,T=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,u=f):(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>=f?(a=0,u=f):u+d>=1?(a=(e*E-1)*Math.pow(2,c),u=u+d):(a=e*Math.pow(2,d-1)*Math.pow(2,c),u=0));c>=8;t[i+g]=a&255,g+=S,a/=256,c-=8);for(u=u<<c|a,p+=c;p>0;t[i+g]=u&255,g+=S,u/=256,p-=8);t[i+g-S]|=T*128}),et}var bi;function vn(){return bi||(bi=1,(function(t){const e=mn(),i=gn(),o=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=a,t.SlowBuffer=I,t.INSPECT_MAX_BYTES=50;const c=2147483647;t.kMaxLength=c,a.TYPED_ARRAY_SUPPORT=s(),!a.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 l=new Uint8Array(1),n={foo:function(){return 42}};return Object.setPrototypeOf(n,Uint8Array.prototype),Object.setPrototypeOf(l,n),l.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function u(l){if(l>c)throw new RangeError('The value "'+l+'" is invalid for option "size"');const n=new Uint8Array(l);return Object.setPrototypeOf(n,a.prototype),n}function a(l,n,r){if(typeof l=="number"){if(typeof n=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(l)}return E(l,n,r)}a.poolSize=8192;function E(l,n,r){if(typeof l=="string")return y(l,n);if(ArrayBuffer.isView(l))return S(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(re(l,ArrayBuffer)||l&&re(l.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(re(l,SharedArrayBuffer)||l&&re(l.buffer,SharedArrayBuffer)))return T(l,n,r);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=l.valueOf&&l.valueOf();if(h!=null&&h!==l)return a.from(h,n,r);const _=A(l);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return a.from(l[Symbol.toPrimitive]("string"),n,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}a.from=function(l,n,r){return E(l,n,r)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function p(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function f(l,n,r){return p(l),l<=0?u(l):n!==void 0?typeof r=="string"?u(l).fill(n,r):u(l).fill(n):u(l)}a.alloc=function(l,n,r){return f(l,n,r)};function d(l){return p(l),u(l<0?0:w(l)|0)}a.allocUnsafe=function(l){return d(l)},a.allocUnsafeSlow=function(l){return d(l)};function y(l,n){if((typeof n!="string"||n==="")&&(n="utf8"),!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n);const r=R(l,n)|0;let h=u(r);const _=h.write(l,n);return _!==r&&(h=h.slice(0,_)),h}function g(l){const n=l.length<0?0:w(l.length)|0,r=u(n);for(let h=0;h<n;h+=1)r[h]=l[h]&255;return r}function S(l){if(re(l,Uint8Array)){const n=new Uint8Array(l);return T(n.buffer,n.byteOffset,n.byteLength)}return g(l)}function T(l,n,r){if(n<0||l.byteLength<n)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<n+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return n===void 0&&r===void 0?h=new Uint8Array(l):r===void 0?h=new Uint8Array(l,n):h=new Uint8Array(l,n,r),Object.setPrototypeOf(h,a.prototype),h}function A(l){if(a.isBuffer(l)){const n=w(l.length)|0,r=u(n);return r.length===0||l.copy(r,0,0,n),r}if(l.length!==void 0)return typeof l.length!="number"||Dt(l.length)?u(0):g(l);if(l.type==="Buffer"&&Array.isArray(l.data))return g(l.data)}function w(l){if(l>=c)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+c.toString(16)+" bytes");return l|0}function I(l){return+l!=l&&(l=0),a.alloc(+l)}a.isBuffer=function(n){return n!=null&&n._isBuffer===!0&&n!==a.prototype},a.compare=function(n,r){if(re(n,Uint8Array)&&(n=a.from(n,n.offset,n.byteLength)),re(r,Uint8Array)&&(r=a.from(r,r.offset,r.byteLength)),!a.isBuffer(n)||!a.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(n===r)return 0;let h=n.length,_=r.length;for(let m=0,v=Math.min(h,_);m<v;++m)if(n[m]!==r[m]){h=n[m],_=r[m];break}return h<_?-1:_<h?1:0},a.isEncoding=function(n){switch(String(n).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}},a.concat=function(n,r){if(!Array.isArray(n))throw new TypeError('"list" argument must be an Array of Buffers');if(n.length===0)return a.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<n.length;++h)r+=n[h].length;const _=a.allocUnsafe(r);let m=0;for(h=0;h<n.length;++h){let v=n[h];if(re(v,Uint8Array))m+v.length>_.length?(a.isBuffer(v)||(v=a.from(v)),v.copy(_,m)):Uint8Array.prototype.set.call(_,v,m);else if(a.isBuffer(v))v.copy(_,m);else throw new TypeError('"list" argument must be an Array of Buffers');m+=v.length}return _};function R(l,n){if(a.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||re(l,ArrayBuffer))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);const r=l.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let _=!1;for(;;)switch(n){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Lt(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Hi(l).length;default:if(_)return h?-1:Lt(l).length;n=(""+n).toLowerCase(),_=!0}}a.byteLength=R;function D(l,n,r){let h=!1;if((n===void 0||n<0)&&(n=0),n>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,n>>>=0,r<=n))return"";for(l||(l="utf8");;)switch(l){case"hex":return Ar(this,n,r);case"utf8":case"utf-8":return nt(this,n,r);case"ascii":return Ir(this,n,r);case"latin1":case"binary":return wr(this,n,r);case"base64":return Nt(this,n,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return br(this,n,r);default:if(h)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),h=!0}}a.prototype._isBuffer=!0;function N(l,n,r){const h=l[n];l[n]=l[r],l[r]=h}a.prototype.swap16=function(){const n=this.length;if(n%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<n;r+=2)N(this,r,r+1);return this},a.prototype.swap32=function(){const n=this.length;if(n%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<n;r+=4)N(this,r,r+3),N(this,r+1,r+2);return this},a.prototype.swap64=function(){const n=this.length;if(n%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<n;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},a.prototype.toString=function(){const n=this.length;return n===0?"":arguments.length===0?nt(this,0,n):D.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(n){if(!a.isBuffer(n))throw new TypeError("Argument must be a Buffer");return this===n?!0:a.compare(this,n)===0},a.prototype.inspect=function(){let n="";const r=t.INSPECT_MAX_BYTES;return n=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(n+=" ... "),"<Buffer "+n+">"},o&&(a.prototype[o]=a.prototype.inspect),a.prototype.compare=function(n,r,h,_,m){if(re(n,Uint8Array)&&(n=a.from(n,n.offset,n.byteLength)),!a.isBuffer(n))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof n);if(r===void 0&&(r=0),h===void 0&&(h=n?n.length:0),_===void 0&&(_=0),m===void 0&&(m=this.length),r<0||h>n.length||_<0||m>this.length)throw new RangeError("out of range index");if(_>=m&&r>=h)return 0;if(_>=m)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,_>>>=0,m>>>=0,this===n)return 0;let v=m-_,O=h-r;const U=Math.min(v,O),M=this.slice(_,m),B=n.slice(r,h);for(let k=0;k<U;++k)if(M[k]!==B[k]){v=M[k],O=B[k];break}return v<O?-1:O<v?1:0};function j(l,n,r,h,_){if(l.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Dt(r)&&(r=_?0:l.length-1),r<0&&(r=l.length+r),r>=l.length){if(_)return-1;r=l.length-1}else if(r<0)if(_)r=0;else return-1;if(typeof n=="string"&&(n=a.from(n,h)),a.isBuffer(n))return n.length===0?-1:ae(l,n,r,h,_);if(typeof n=="number")return n=n&255,typeof Uint8Array.prototype.indexOf=="function"?_?Uint8Array.prototype.indexOf.call(l,n,r):Uint8Array.prototype.lastIndexOf.call(l,n,r):ae(l,[n],r,h,_);throw new TypeError("val must be string, number or Buffer")}function ae(l,n,r,h,_){let m=1,v=l.length,O=n.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(l.length<2||n.length<2)return-1;m=2,v/=2,O/=2,r/=2}function U(B,k){return m===1?B[k]:B.readUInt16BE(k*m)}let M;if(_){let B=-1;for(M=r;M<v;M++)if(U(l,M)===U(n,B===-1?0:M-B)){if(B===-1&&(B=M),M-B+1===O)return B*m}else B!==-1&&(M-=M-B),B=-1}else for(r+O>v&&(r=v-O),M=r;M>=0;M--){let B=!0;for(let k=0;k<O;k++)if(U(l,M+k)!==U(n,k)){B=!1;break}if(B)return M}return-1}a.prototype.includes=function(n,r,h){return this.indexOf(n,r,h)!==-1},a.prototype.indexOf=function(n,r,h){return j(this,n,r,h,!0)},a.prototype.lastIndexOf=function(n,r,h){return j(this,n,r,h,!1)};function G(l,n,r,h){r=Number(r)||0;const _=l.length-r;h?(h=Number(h),h>_&&(h=_)):h=_;const m=n.length;h>m/2&&(h=m/2);let v;for(v=0;v<h;++v){const O=parseInt(n.substr(v*2,2),16);if(Dt(O))return v;l[r+v]=O}return v}function ie(l,n,r,h){return ot(Lt(n,l.length-r),l,r,h)}function ye(l,n,r,h){return ot(xr(n),l,r,h)}function X(l,n,r,h){return ot(Hi(n),l,r,h)}function ne(l,n,r,h){return ot(Lr(n,l.length-r),l,r,h)}a.prototype.write=function(n,r,h,_){if(r===void 0)_="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")_=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,_===void 0&&(_="utf8")):(_=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),n.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let v=!1;for(;;)switch(_){case"hex":return G(this,n,r,h);case"utf8":case"utf-8":return ie(this,n,r,h);case"ascii":case"latin1":case"binary":return ye(this,n,r,h);case"base64":return X(this,n,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ne(this,n,r,h);default:if(v)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),v=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Nt(l,n,r){return n===0&&r===l.length?e.fromByteArray(l):e.fromByteArray(l.slice(n,r))}function nt(l,n,r){r=Math.min(l.length,r);const h=[];let _=n;for(;_<r;){const m=l[_];let v=null,O=m>239?4:m>223?3:m>191?2:1;if(_+O<=r){let U,M,B,k;switch(O){case 1:m<128&&(v=m);break;case 2:U=l[_+1],(U&192)===128&&(k=(m&31)<<6|U&63,k>127&&(v=k));break;case 3:U=l[_+1],M=l[_+2],(U&192)===128&&(M&192)===128&&(k=(m&15)<<12|(U&63)<<6|M&63,k>2047&&(k<55296||k>57343)&&(v=k));break;case 4:U=l[_+1],M=l[_+2],B=l[_+3],(U&192)===128&&(M&192)===128&&(B&192)===128&&(k=(m&15)<<18|(U&63)<<12|(M&63)<<6|B&63,k>65535&&k<1114112&&(v=k))}}v===null?(v=65533,O=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),_+=O}return Fe(h)}const rt=4096;function Fe(l){const n=l.length;if(n<=rt)return String.fromCharCode.apply(String,l);let r="",h=0;for(;h<n;)r+=String.fromCharCode.apply(String,l.slice(h,h+=rt));return r}function Ir(l,n,r){let h="";r=Math.min(l.length,r);for(let _=n;_<r;++_)h+=String.fromCharCode(l[_]&127);return h}function wr(l,n,r){let h="";r=Math.min(l.length,r);for(let _=n;_<r;++_)h+=String.fromCharCode(l[_]);return h}function Ar(l,n,r){const h=l.length;(!n||n<0)&&(n=0),(!r||r<0||r>h)&&(r=h);let _="";for(let m=n;m<r;++m)_+=Dr[l[m]];return _}function br(l,n,r){const h=l.slice(n,r);let _="";for(let m=0;m<h.length-1;m+=2)_+=String.fromCharCode(h[m]+h[m+1]*256);return _}a.prototype.slice=function(n,r){const h=this.length;n=~~n,r=r===void 0?h:~~r,n<0?(n+=h,n<0&&(n=0)):n>h&&(n=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<n&&(r=n);const _=this.subarray(n,r);return Object.setPrototypeOf(_,a.prototype),_};function H(l,n,r){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+n>r)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(n,r,h){n=n>>>0,r=r>>>0,h||H(n,r,this.length);let _=this[n],m=1,v=0;for(;++v<r&&(m*=256);)_+=this[n+v]*m;return _},a.prototype.readUintBE=a.prototype.readUIntBE=function(n,r,h){n=n>>>0,r=r>>>0,h||H(n,r,this.length);let _=this[n+--r],m=1;for(;r>0&&(m*=256);)_+=this[n+--r]*m;return _},a.prototype.readUint8=a.prototype.readUInt8=function(n,r){return n=n>>>0,r||H(n,1,this.length),this[n]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(n,r){return n=n>>>0,r||H(n,2,this.length),this[n]|this[n+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(n,r){return n=n>>>0,r||H(n,2,this.length),this[n]<<8|this[n+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(n,r){return n=n>>>0,r||H(n,4,this.length),(this[n]|this[n+1]<<8|this[n+2]<<16)+this[n+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(n,r){return n=n>>>0,r||H(n,4,this.length),this[n]*16777216+(this[n+1]<<16|this[n+2]<<8|this[n+3])},a.prototype.readBigUInt64LE=Ee(function(n){n=n>>>0,Ne(n,"offset");const r=this[n],h=this[n+7];(r===void 0||h===void 0)&&$e(n,this.length-8);const _=r+this[++n]*2**8+this[++n]*2**16+this[++n]*2**24,m=this[++n]+this[++n]*2**8+this[++n]*2**16+h*2**24;return BigInt(_)+(BigInt(m)<<BigInt(32))}),a.prototype.readBigUInt64BE=Ee(function(n){n=n>>>0,Ne(n,"offset");const r=this[n],h=this[n+7];(r===void 0||h===void 0)&&$e(n,this.length-8);const _=r*2**24+this[++n]*2**16+this[++n]*2**8+this[++n],m=this[++n]*2**24+this[++n]*2**16+this[++n]*2**8+h;return(BigInt(_)<<BigInt(32))+BigInt(m)}),a.prototype.readIntLE=function(n,r,h){n=n>>>0,r=r>>>0,h||H(n,r,this.length);let _=this[n],m=1,v=0;for(;++v<r&&(m*=256);)_+=this[n+v]*m;return m*=128,_>=m&&(_-=Math.pow(2,8*r)),_},a.prototype.readIntBE=function(n,r,h){n=n>>>0,r=r>>>0,h||H(n,r,this.length);let _=r,m=1,v=this[n+--_];for(;_>0&&(m*=256);)v+=this[n+--_]*m;return m*=128,v>=m&&(v-=Math.pow(2,8*r)),v},a.prototype.readInt8=function(n,r){return n=n>>>0,r||H(n,1,this.length),this[n]&128?(255-this[n]+1)*-1:this[n]},a.prototype.readInt16LE=function(n,r){n=n>>>0,r||H(n,2,this.length);const h=this[n]|this[n+1]<<8;return h&32768?h|4294901760:h},a.prototype.readInt16BE=function(n,r){n=n>>>0,r||H(n,2,this.length);const h=this[n+1]|this[n]<<8;return h&32768?h|4294901760:h},a.prototype.readInt32LE=function(n,r){return n=n>>>0,r||H(n,4,this.length),this[n]|this[n+1]<<8|this[n+2]<<16|this[n+3]<<24},a.prototype.readInt32BE=function(n,r){return n=n>>>0,r||H(n,4,this.length),this[n]<<24|this[n+1]<<16|this[n+2]<<8|this[n+3]},a.prototype.readBigInt64LE=Ee(function(n){n=n>>>0,Ne(n,"offset");const r=this[n],h=this[n+7];(r===void 0||h===void 0)&&$e(n,this.length-8);const _=this[n+4]+this[n+5]*2**8+this[n+6]*2**16+(h<<24);return(BigInt(_)<<BigInt(32))+BigInt(r+this[++n]*2**8+this[++n]*2**16+this[++n]*2**24)}),a.prototype.readBigInt64BE=Ee(function(n){n=n>>>0,Ne(n,"offset");const r=this[n],h=this[n+7];(r===void 0||h===void 0)&&$e(n,this.length-8);const _=(r<<24)+this[++n]*2**16+this[++n]*2**8+this[++n];return(BigInt(_)<<BigInt(32))+BigInt(this[++n]*2**24+this[++n]*2**16+this[++n]*2**8+h)}),a.prototype.readFloatLE=function(n,r){return n=n>>>0,r||H(n,4,this.length),i.read(this,n,!0,23,4)},a.prototype.readFloatBE=function(n,r){return n=n>>>0,r||H(n,4,this.length),i.read(this,n,!1,23,4)},a.prototype.readDoubleLE=function(n,r){return n=n>>>0,r||H(n,8,this.length),i.read(this,n,!0,52,8)},a.prototype.readDoubleBE=function(n,r){return n=n>>>0,r||H(n,8,this.length),i.read(this,n,!1,52,8)};function Z(l,n,r,h,_,m){if(!a.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>_||n<m)throw new RangeError('"value" argument is out of bounds');if(r+h>l.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(n,r,h,_){if(n=+n,r=r>>>0,h=h>>>0,!_){const O=Math.pow(2,8*h)-1;Z(this,n,r,h,O,0)}let m=1,v=0;for(this[r]=n&255;++v<h&&(m*=256);)this[r+v]=n/m&255;return r+h},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(n,r,h,_){if(n=+n,r=r>>>0,h=h>>>0,!_){const O=Math.pow(2,8*h)-1;Z(this,n,r,h,O,0)}let m=h-1,v=1;for(this[r+m]=n&255;--m>=0&&(v*=256);)this[r+m]=n/v&255;return r+h},a.prototype.writeUint8=a.prototype.writeUInt8=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,1,255,0),this[r]=n&255,r+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,2,65535,0),this[r]=n&255,this[r+1]=n>>>8,r+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,2,65535,0),this[r]=n>>>8,this[r+1]=n&255,r+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,4,4294967295,0),this[r+3]=n>>>24,this[r+2]=n>>>16,this[r+1]=n>>>8,this[r]=n&255,r+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,4,4294967295,0),this[r]=n>>>24,this[r+1]=n>>>16,this[r+2]=n>>>8,this[r+3]=n&255,r+4};function Bi(l,n,r,h,_){ji(n,h,_,l,r,7);let m=Number(n&BigInt(4294967295));l[r++]=m,m=m>>8,l[r++]=m,m=m>>8,l[r++]=m,m=m>>8,l[r++]=m;let v=Number(n>>BigInt(32)&BigInt(4294967295));return l[r++]=v,v=v>>8,l[r++]=v,v=v>>8,l[r++]=v,v=v>>8,l[r++]=v,r}function Pi(l,n,r,h,_){ji(n,h,_,l,r,7);let m=Number(n&BigInt(4294967295));l[r+7]=m,m=m>>8,l[r+6]=m,m=m>>8,l[r+5]=m,m=m>>8,l[r+4]=m;let v=Number(n>>BigInt(32)&BigInt(4294967295));return l[r+3]=v,v=v>>8,l[r+2]=v,v=v>>8,l[r+1]=v,v=v>>8,l[r]=v,r+8}a.prototype.writeBigUInt64LE=Ee(function(n,r=0){return Bi(this,n,r,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Ee(function(n,r=0){return Pi(this,n,r,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(n,r,h,_){if(n=+n,r=r>>>0,!_){const U=Math.pow(2,8*h-1);Z(this,n,r,h,U-1,-U)}let m=0,v=1,O=0;for(this[r]=n&255;++m<h&&(v*=256);)n<0&&O===0&&this[r+m-1]!==0&&(O=1),this[r+m]=(n/v>>0)-O&255;return r+h},a.prototype.writeIntBE=function(n,r,h,_){if(n=+n,r=r>>>0,!_){const U=Math.pow(2,8*h-1);Z(this,n,r,h,U-1,-U)}let m=h-1,v=1,O=0;for(this[r+m]=n&255;--m>=0&&(v*=256);)n<0&&O===0&&this[r+m+1]!==0&&(O=1),this[r+m]=(n/v>>0)-O&255;return r+h},a.prototype.writeInt8=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,1,127,-128),n<0&&(n=255+n+1),this[r]=n&255,r+1},a.prototype.writeInt16LE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,2,32767,-32768),this[r]=n&255,this[r+1]=n>>>8,r+2},a.prototype.writeInt16BE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,2,32767,-32768),this[r]=n>>>8,this[r+1]=n&255,r+2},a.prototype.writeInt32LE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,4,2147483647,-2147483648),this[r]=n&255,this[r+1]=n>>>8,this[r+2]=n>>>16,this[r+3]=n>>>24,r+4},a.prototype.writeInt32BE=function(n,r,h){return n=+n,r=r>>>0,h||Z(this,n,r,4,2147483647,-2147483648),n<0&&(n=4294967295+n+1),this[r]=n>>>24,this[r+1]=n>>>16,this[r+2]=n>>>8,this[r+3]=n&255,r+4},a.prototype.writeBigInt64LE=Ee(function(n,r=0){return Bi(this,n,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Ee(function(n,r=0){return Pi(this,n,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Fi(l,n,r,h,_,m){if(r+h>l.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function $i(l,n,r,h,_){return n=+n,r=r>>>0,_||Fi(l,n,r,4),i.write(l,n,r,h,23,4),r+4}a.prototype.writeFloatLE=function(n,r,h){return $i(this,n,r,!0,h)},a.prototype.writeFloatBE=function(n,r,h){return $i(this,n,r,!1,h)};function Vi(l,n,r,h,_){return n=+n,r=r>>>0,_||Fi(l,n,r,8),i.write(l,n,r,h,52,8),r+8}a.prototype.writeDoubleLE=function(n,r,h){return Vi(this,n,r,!0,h)},a.prototype.writeDoubleBE=function(n,r,h){return Vi(this,n,r,!1,h)},a.prototype.copy=function(n,r,h,_){if(!a.isBuffer(n))throw new TypeError("argument should be a Buffer");if(h||(h=0),!_&&_!==0&&(_=this.length),r>=n.length&&(r=n.length),r||(r=0),_>0&&_<h&&(_=h),_===h||n.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(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),n.length-r<_-h&&(_=n.length-r+h);const m=_-h;return this===n&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,_):Uint8Array.prototype.set.call(n,this.subarray(h,_),r),m},a.prototype.fill=function(n,r,h,_){if(typeof n=="string"){if(typeof r=="string"?(_=r,r=0,h=this.length):typeof h=="string"&&(_=h,h=this.length),_!==void 0&&typeof _!="string")throw new TypeError("encoding must be a string");if(typeof _=="string"&&!a.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(n.length===1){const v=n.charCodeAt(0);(_==="utf8"&&v<128||_==="latin1")&&(n=v)}}else typeof n=="number"?n=n&255:typeof n=="boolean"&&(n=Number(n));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,n||(n=0);let m;if(typeof n=="number")for(m=r;m<h;++m)this[m]=n;else{const v=a.isBuffer(n)?n:a.from(n,_),O=v.length;if(O===0)throw new TypeError('The value "'+n+'" is invalid for argument "value"');for(m=0;m<h-r;++m)this[m+r]=v[m%O]}return this};const Oe={};function xt(l,n,r){Oe[l]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:n.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(_){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:_,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}xt("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),xt("ERR_INVALID_ARG_TYPE",function(l,n){return`The "${l}" argument must be of type number. Received type ${typeof n}`},TypeError),xt("ERR_OUT_OF_RANGE",function(l,n,r){let h=`The value of "${l}" is out of range.`,_=r;return Number.isInteger(r)&&Math.abs(r)>2**32?_=Gi(String(r)):typeof r=="bigint"&&(_=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(_=Gi(_)),_+="n"),h+=` It must be ${n}. Received ${_}`,h},RangeError);function Gi(l){let n="",r=l.length;const h=l[0]==="-"?1:0;for(;r>=h+4;r-=3)n=`_${l.slice(r-3,r)}${n}`;return`${l.slice(0,r)}${n}`}function Rr(l,n,r){Ne(n,"offset"),(l[n]===void 0||l[n+r]===void 0)&&$e(n,l.length-(r+1))}function ji(l,n,r,h,_,m){if(l>r||l<n){const v=typeof n=="bigint"?"n":"";let O;throw n===0||n===BigInt(0)?O=`>= 0${v} and < 2${v} ** ${(m+1)*8}${v}`:O=`>= -(2${v} ** ${(m+1)*8-1}${v}) and < 2 ** ${(m+1)*8-1}${v}`,new Oe.ERR_OUT_OF_RANGE("value",O,l)}Rr(h,_,m)}function Ne(l,n){if(typeof l!="number")throw new Oe.ERR_INVALID_ARG_TYPE(n,"number",l)}function $e(l,n,r){throw Math.floor(l)!==l?(Ne(l,r),new Oe.ERR_OUT_OF_RANGE("offset","an integer",l)):n<0?new Oe.ERR_BUFFER_OUT_OF_BOUNDS:new Oe.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${n}`,l)}const Or=/[^+/0-9A-Za-z-_]/g;function Nr(l){if(l=l.split("=")[0],l=l.trim().replace(Or,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function Lt(l,n){n=n||1/0;let r;const h=l.length;let _=null;const m=[];for(let v=0;v<h;++v){if(r=l.charCodeAt(v),r>55295&&r<57344){if(!_){if(r>56319){(n-=3)>-1&&m.push(239,191,189);continue}else if(v+1===h){(n-=3)>-1&&m.push(239,191,189);continue}_=r;continue}if(r<56320){(n-=3)>-1&&m.push(239,191,189),_=r;continue}r=(_-55296<<10|r-56320)+65536}else _&&(n-=3)>-1&&m.push(239,191,189);if(_=null,r<128){if((n-=1)<0)break;m.push(r)}else if(r<2048){if((n-=2)<0)break;m.push(r>>6|192,r&63|128)}else if(r<65536){if((n-=3)<0)break;m.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((n-=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 xr(l){const n=[];for(let r=0;r<l.length;++r)n.push(l.charCodeAt(r)&255);return n}function Lr(l,n){let r,h,_;const m=[];for(let v=0;v<l.length&&!((n-=2)<0);++v)r=l.charCodeAt(v),h=r>>8,_=r%256,m.push(_),m.push(h);return m}function Hi(l){return e.toByteArray(Nr(l))}function ot(l,n,r,h){let _;for(_=0;_<h&&!(_+r>=n.length||_>=l.length);++_)n[_+r]=l[_];return _}function re(l,n){return l instanceof n||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===n.name}function Dt(l){return l!==l}const Dr=(function(){const l="0123456789abcdef",n=new Array(256);for(let r=0;r<16;++r){const h=r*16;for(let _=0;_<16;++_)n[h+_]=l[r]+l[_]}return n})();function Ee(l){return typeof BigInt>"u"?kr:l}function kr(){throw new Error("BigInt not supported")}})(yt)),yt}var yn=vn();const Sn="https://api.anam.ai",Cn="/v1",Ri={client:"js-sdk",version:"4.16.0"},Tn=3,In=250,wn=2e3,An=1e4;var bn=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};const Oi="https://api.anam.ai",St="/v1";var se;(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"})(se||(se={}));let Ct=Oi,Ni=St,de,xi=!1;const Rn=(t,e=St)=>{Ct=t,Ni=e},On=t=>{de=t},Nn=t=>{xi=t};let he={sessionId:null,organizationId:null,attemptCorrelationId:null};const be=t=>{he=Object.assign(Object.assign({},he),t)},ve=(t,e,i)=>bn(void 0,void 0,void 0,function*(){if(!xi)try{const o=Object.assign(Object.assign({},Ri),i);he.sessionId&&(o.sessionId=he.sessionId),he.organizationId&&(o.organizationId=he.organizationId),he.attemptCorrelationId&&(o.attemptCorrelationId=he.attemptCorrelationId);const c=`${Ni}/metrics/client`;let s,u={"Content-Type":"application/json"};de?.enabled&&de?.baseUrl?(s=`${de.baseUrl}${c}`,u["X-Anam-Target-Url"]=`${Ct}${c}`):s=`${Ct}${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)}}),xn=(t,e="console")=>{var i,o,c;const s={};t.forEach(d=>{s[d.type]||(s[d.type]=[]),s[d.type].push(d)});const u={issues:[]},a=((i=s["inbound-rtp"])===null||i===void 0?void 0:i.filter(d=>d.kind==="video"))||[];a.length>0&&(u.personaVideoStream=[],a.forEach(d=>{var y,g,S,T,A;const w={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:(T=d.packetsReceived)!==null&&T!==void 0?T:"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(w)}));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 T={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(T)}));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 f=[];if(a.forEach(d=>{typeof d.framesDropped=="number"&&d.framesDropped>0&&f.push(`Video: ${d.framesDropped} frames dropped`),typeof d.packetsLost=="number"&&d.packetsLost>0&&f.push(`Video: ${d.packetsLost} packets lost`),typeof d.framesPerSecond=="number"&&d.framesPerSecond<23&&f.push(`Video: Low frame rate (${d.framesPerSecond} fps)`)}),E.forEach(d=>{typeof d.packetsLost=="number"&&d.packetsLost>0&&f.push(`Audio: ${d.packetsLost} packets lost`),typeof d.jitter=="number"&&d.jitter>.1&&f.push(`Audio: High jitter (${(d.jitter*1e3).toFixed(1)}ms)`)}),u.issues=f,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 z;(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"})(z||(z={}));class V extends Error{constructor(e,i,o=500,c){super(e),this.name="ClientError",this.code=i,this.statusCode=o,this.details=c,Object.setPrototypeOf(this,V.prototype),ve(se.CLIENT_METRIC_MEASUREMENT_ERROR,i,{details:c,statusCode:o})}}function Li(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function Ln(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 q;(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"})(q||(q={}));var te;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.TOOL_CALL_STARTED_EVENT="toolCallStarted",t.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",t.TOOL_CALL_FAILED_EVENT="toolCallFailed",t.REASONING_TEXT="reasoningText",t.USER_SPEECH_STARTED="userSpeechStarted",t.USER_SPEECH_ENDED="userSpeechEnded"})(te||(te={}));var fe;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(fe||(fe={}));var tt;(function(t){t.USER="user",t.PERSONA="persona"})(tt||(tt={}));var b;(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.TOOL_CALL_STARTED="TOOL_CALL_STARTED",t.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",t.TOOL_CALL_FAILED="TOOL_CALL_FAILED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",t.USER_SPEECH_STARTED="USER_SPEECH_STARTED",t.USER_SPEECH_ENDED="USER_SPEECH_ENDED"})(b||(b={}));var F;(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_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED",t.TOOL_CALL_RESULT_READY="TOOL_CALL_RESULT_READY"})(F||(F={}));var pe;(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"})(pe||(pe={}));class Dn{constructor(e,i){this.sequenceNumber=0,this.config=e,this.signallingClient=i}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 i=e instanceof Uint8Array?e:new Uint8Array(e),o=Array.from(i,c=>String.fromCharCode(c)).join("");return btoa(o)}}var Re=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};const kn=5,Mn=5;class Un{constructor(e,i,o,c,s){var u,a,E,p,f;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}=i;if(this.heartbeatIntervalSeconds=d||kn,this.maxWsReconnectionAttempts=y||Mn,!g.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((u=this.apiGatewayConfig)===null||u===void 0)&&u.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const S=new URL(this.apiGatewayConfig.baseUrl),T=(E=this.apiGatewayConfig.wsPath)!==null&&E!==void 0?E:"/ws";S.protocol=S.protocol.replace("http","ws"),S.pathname=T,this.url=S;const A=g.protocol||"https",w=A==="http"?"ws":"wss",I=`${A}://${g.baseUrl}`,R=(p=g.signallingPath)!==null&&p!==void 0?p:"/ws",D=new URL(I);D.protocol=w==="ws"?"ws:":"wss:",g.port&&(D.port=g.port),D.pathname=R,D.searchParams.append("session_id",e),this.url.searchParams.append("target_url",D.href)}else{const T=`${g.protocol||"https"}://${g.baseUrl}`;this.url=new URL(T),this.url.protocol=g.protocol==="http"?"ws:":"wss:",g.port&&(this.url.port=g.port),this.url.pathname=(f=g.signallingPath)!==null&&f!==void 0?f:"/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 Re(this,void 0,void 0,function*(){const i={connectionDescription:e,userUid:this.sessionId},o={actionType:q.OFFER,sessionId:this.sessionId,payload:i};this.sendSignalMessage(o)})}sendIceCandidate(e){return Re(this,void 0,void 0,function*(){const i={actionType:q.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(i)})}sendSignalMessage(e){var i;if(((i=this.socket)===null||i===void 0?void 0:i.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 Re(this,void 0,void 0,function*(){const i={actionType:q.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendAgentAudioInput(e){const i={actionType:q.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)}sendAgentAudioInputEnd(){const e={actionType:q.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 Re(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(F.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(b.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Re(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(b.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(i=>{var o;((o=this.socket)===null||o===void 0?void 0:o.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(i)):e.push(i)}),this.sendingBuffer=e}onMessage(e){return Re(this,void 0,void 0,function*(){const i=JSON.parse(e.data);this.internalEventEmitter.emit(F.SIGNAL_MESSAGE_RECEIVED,i)})}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,i={actionType:q.HEARTBEAT,sessionId:this.sessionId,payload:""},o=JSON.stringify(i);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 Bn(t){return"brainType"in t||"llmId"in t}var Tt=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};class Pn{constructor(e,i,o){if(!e&&!i)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=i||null,this.baseUrl=o?.baseUrl||Sn,this.apiVersion=o?.apiVersion||Cn,this.apiGatewayConfig=o?.apiGateway||void 0,this.retryOptions=Fn(o?.retry),this.requestTimeoutMs=Math.max(0,it(o?.requestTimeoutMs,An))}buildGatewayUrlAndHeaders(e,i){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}`),a=Object.assign(Object.assign({},i),{"X-Anam-Target-Url":u.href});return{url:s,headers:a}}else return{url:`${this.baseUrl}${e}`,headers:i}}startSession(e,i){return Tt(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new V("Persona configuration must be provided when using apiKey",z.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.");const{maxAttempts:o}=this.retryOptions;let c;for(let s=1;s<=o;s++)try{return yield this.attemptStartSession(e,i)}catch(u){if(c=u,s>=o||!$n(u))throw u;yield Vn(this.computeBackoffDelay(s))}throw c})}attemptStartSession(e,i){return Tt(this,void 0,void 0,function*(){const o=this.requestTimeoutMs>0?new AbortController:void 0,c=o!==void 0?setTimeout(()=>o.abort(),this.requestTimeoutMs):void 0;try{const s=`${this.apiVersion}/engine/session`,{url:u,headers:a}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),E=yield fetch(u,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:i,clientMetadata:Ri}),signal:o?.signal}),p=yield E.json(),f=p.error;switch(E.status){case 200:case 201:return p;case 400:throw new V("Invalid request to start session",z.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:p.message});case 401:throw new V("Authentication failed when starting session",z.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:p.message});case 402:throw new V("Please sign up for a plan to start a session",z.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:p.message});case 403:throw new V("Authentication failed when starting session",z.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:p.message});case 429:throw f==="Concurrent session limit reached"?new V("Concurrency limit reached, please upgrade your plan",z.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:p.message}):f==="Spend cap reached"?new V("Spend cap reached, please upgrade your plan",z.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:p.message}):new V("Usage limit reached, please upgrade your plan",z.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:p.message});case 503:throw new V("There are no available personas, please try again later",z.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:p.message});default:throw new V("Unknown error when starting session",z.CLIENT_ERROR_CODE_SERVER_ERROR,E.status,{cause:p.message})}}catch(s){throw s instanceof V?s:new V("Failed to start session",z.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s)})}finally{c!==void 0&&clearTimeout(c)}})}computeBackoffDelay(e){const{initialBackoffMs:i,maxBackoffMs:o}=this.retryOptions,c=Math.min(o,i*Math.pow(2,e-1));return Math.floor(c/2+Math.random()*(c/2))}unsafe_getSessionToken(e){return Tt(this,void 0,void 0,function*(){if(console.warn("Using an insecure 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 i={clientLabel:"js-sdk-api-key"};Bn(e)&&(i=Object.assign(Object.assign({},i),{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(i)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}function Fn(t){const e=Math.max(1,Math.floor(it(t?.maxAttempts,Tn))),i=Math.max(0,it(t?.initialBackoffMs,In)),o=Math.max(i,it(t?.maxBackoffMs,wn));return{maxAttempts:e,initialBackoffMs:i,maxBackoffMs:o}}function it(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function $n(t){return t instanceof V?t.statusCode>=500&&t.statusCode<600:!0}function Vn(t){return new Promise(e=>setTimeout(e,t))}var Gn=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};class jn{constructor(e,i,o){this.baseUrl=e,this.sessionId=i,this.apiGatewayConfig=o}sendTalkCommand(e){return Gn(this,void 0,void 0,function*(){var i,o;try{let c,s={"Content-Type":"application/json"};const u="/talk",a=`?session_id=${this.sessionId}`;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.baseUrl)){c=`${this.apiGatewayConfig.baseUrl}${u}${a}`;const p=new URL(`${this.baseUrl}${u}${a}`);s["X-Anam-Target-Url"]=p.href}else c=`${this.baseUrl}${u}${a}`;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 Hn{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){this.listeners[e]&&this.listeners[e].forEach(o=>{o(...i)})}}class Wn{constructor(e,i){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(F.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 i={id:e.id,content:e.content,role:e.role};this.messages.push(i)}processPersonaMessage(e){const i={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},o=this.messages.findIndex(c=>c.id===i.id);if(o!==-1){const c=this.messages[o];this.messages[o]=Object.assign(Object.assign({},c),{content:c.content+i.content,interrupted:c.interrupted||i.interrupted})}else this.messages.push(i)}processWebRtcTextMessageEvent(e){const i=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(b.MESSAGE_STREAM_EVENT_RECEIVED,i),i.role){case tt.USER:this.processUserMessage(i);break;case tt.PERSONA:this.processPersonaMessage(i);break}i.endOfSpeech&&this.publicEventEmitter.emit(b.MESSAGE_HISTORY_UPDATED,this.messages)}}class zn{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){if(e===b.CONNECTION_ESTABLISHED&&ve(se.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===b.CONNECTION_CLOSED){const[o,c]=i;ve(se.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,o,c?{details:c}:void 0)}this.listeners[e]&&this.listeners[e].forEach(o=>{o(...i)})}}var K;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(K||(K={}));var It=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};class qn{constructor(e,i,o){this.state=K.UNSTARTED,this.correlationId=e,this.internalEventEmitter=i,this.signallingClient=o,this.internalEventEmitter.addListener(F.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(F.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return It(this,void 0,void 0,function*(){e.actionType===q.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=K.INTERRUPTED,this.onDeactivate())})}endMessage(){return It(this,void 0,void 0,function*(){if(this.state===K.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==K.STREAMING){console.warn("Talk stream is not in an active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=K.ENDED,this.onDeactivate()})}streamMessageChunk(e,i){return It(this,void 0,void 0,function*(){if(this.state!==K.STREAMING&&this.state!==K.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const o={content:e,startOfSpeech:this.state===K.UNSTARTED,endOfSpeech:i,correlationId:this.correlationId};this.state=i?K.ENDED:K.STREAMING,this.state===K.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(o)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===K.STREAMING||this.state===K.UNSTARTED}getState(){return this.state}}var wt=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};const Di=(t,e)=>{if(isNaN(t)||isNaN(e))return 0;const i=e-t;return i>0?i:0};class ki{constructor(e,i){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.failedCalls=Object.create(null),this.activeSessionId=null,this.publicEventEmitter=e,this.internalEventEmitter=i}setActiveSession(e){this.activeSessionId=e,this.clearPendingCalls(),this.clearFailedCalls()}clearSessionState(){this.activeSessionId=null,this.clearPendingCalls(),this.clearFailedCalls()}clearPendingCalls(){this.pendingCalls=Object.create(null)}clearFailedCalls(){this.failedCalls=Object.create(null)}registerHandler(e,i){return this.handlers[e]=i,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return wt(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;const{tool_name:i,timestamp:o}=e,c=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(o);if(this.pendingCalls[e.tool_call_id]={payload:c,timestamp:s.getTime()},!(i in this.handlers))return;const u=this.handlers[i];if(u.onStart)try{let a=yield u.onStart(c);if(e.tool_type==="client"){this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:a??void 0,errorMessage:void 0}),yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:a,timestamp:new Date().toISOString()}));return}}catch(a){const E=a instanceof Error?a.message:String(a);e.tool_type==="client"&&this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:void 0,errorMessage:`Error in handler: ${E}`}),yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${E}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return wt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:o,timestamp:c}=e;if(this.activeSessionId!==e.session_id)return;if(o in this.failedCalls){delete this.failedCalls[o];return}const s=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(o in this.pendingCalls&&delete this.pendingCalls[o],!(i in this.handlers))return;const u=this.handlers[i];if(u.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(b.TOOL_CALL_COMPLETED,s);try{yield u.onComplete(s)}catch(a){console.error(`Error in onComplete handler for tool ${i}:`,a);return}}})}processToolCallFailedEvent(e){return wt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:o,timestamp:c}=e;if(this.activeSessionId!==e.session_id)return;const s=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[o]=s,o in this.pendingCalls&&delete this.pendingCalls[o],!(i in this.handlers))return;const u=this.handlers[i];if(u.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(b.TOOL_CALL_FAILED,s);try{yield u.onFail(s)}catch(a){console.error(`Error in onFail handler for tool ${i}:`,a);return}}})}sendToolResult(e){const i={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(F.TOOL_CALL_RESULT_READY,i)}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}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const i=new Date(e.timestamp),o=this.pendingCalls[e.tool_call_id],c=o?Di(o.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:c>0?c:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const i=new Date(e.timestamp),o=this.pendingCalls[e.tool_call_id],c=o?Di(o.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:c>0?c:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var Q=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};const Yn=15e3,Kn=5e3,Jn=2;class Xn{constructor(e,i,o,c,s){var u,a,E,p;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:fe.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.toolCallManager=s,this.apiGatewayConfig=i.apiGateway;const{inputAudio:f}=i;this.inputAudioState=f.inputAudioState,i.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=i.inputAudio.userProvidedMediaStream),this.disableInputAudio=i.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(F.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(F.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(F.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(F.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(F.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(F.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=i.iceServers,this.iceTransportPolicy=i.iceTransportPolicy,this.rtcConfiguration=i.rtcConfiguration,this.signallingClient=new Un(e,i.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new jn(i.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=i.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(a=(u=i.metrics)===null||u===void 0?void 0:u.showPeerConnectionStatsReport)!==null&&a!==void 0?a:!1,this.peerConnectionStatsReportOutputFormat=(p=(E=i.metrics)===null||E===void 0?void 0:E.peerConnectionStatsReportOutputFormat)!==null&&p!==void 0?p:"console"}onInputAudioStateChange(e,i){e.isMuted!==i.isMuted&&(i.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>Q(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)}}),Kn))}sendClientSideMetrics(e){e.forEach(i=>{if(i.type==="inbound-rtp"){const o={message_type:"remote_rtp_stats",data:i};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)},Yn);this.successMetricPoller=setInterval(()=>Q(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const i=yield this.peerConnection.getStats();let o=!1,c=null;i.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(se.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,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return Q(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 i=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(),i&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(b.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}onToolCallResultReceived(e){const i={session_id:e.sessionId,message_type:"tool_result",tool_call_id:e.toolCallId,user_action_correlation_id:e.userActionCorrelationId,timestamp_user_action:e.timestampUserAction};e.result!==void 0&&(i.result=e.result),e.errorMessage&&(i.error=e.errorMessage),this.sendDataMessage(JSON.stringify(i))}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const i=document.getElementById(e);if(!i)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=i}}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 Q(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return Q(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 qn(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Dn(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return Q(this,void 0,void 0,function*(){var e,i,o;this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:Jn},this.rtcConfiguration),{iceTransportPolicy:(o=(i=(e=this.rtcConfiguration)===null||e===void 0?void 0:e.iceTransportPolicy)!==null&&i!==void 0?i:this.iceTransportPolicy)!==null&&o!==void 0?o:void 0,iceServers:this.iceServers})),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(c=>{console.error("Async microphone permission request failed:",c)}))})}onSignalMessage(e){return Q(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case q.ANSWER:const i=e.payload;yield this.peerConnection.setRemoteDescription(i),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case q.ICE_CANDIDATE:const o=e.payload,c=new RTCIceCandidate(o);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(c):this.remoteIceCandidateBuffer.push(c);break;case q.END_SESSION:const s=e.payload;this.publicEventEmitter.emit(b.CONNECTION_CLOSED,pe.SERVER_CLOSED_CONNECTION,s),this.shutdown();break;case q.WARNING:const u=e.payload;console.warn("Warning received from server: "+u),this.publicEventEmitter.emit(b.SERVER_WARNING,u);break;case q.TALK_STREAM_INTERRUPTED:const a=e.payload;this.publicEventEmitter.emit(b.TALK_STREAM_INTERRUPTED,a.correlationId);break;case q.SESSION_READY:const E=e.sessionId;this.publicEventEmitter.emit(b.SESSION_READY,E);break;case q.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}})}onSignallingClientConnected(){return Q(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 i;(i=this.peerConnection)===null||i===void 0||i.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,i;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((i=this.peerConnection)===null||i===void 0?void 0:i.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(b.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(b.CONNECTION_CLOSED,pe.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(b.CONNECTION_CLOSED,pe.WEBRTC_FAILURE);try{this.stopConnection()}catch(i){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",i)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(b.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const i=this.videoElement.requestVideoFrameCallback(()=>{var o;(o=this.videoElement)===null||o===void 0||o.cancelVideoFrameCallback(i),this.publicEventEmitter.emit(b.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ve(se.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(b.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return Q(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=i=>{var o,c,s,u;try{const a=JSON.parse(i.data);switch(a.messageType){case te.SPEECH_TEXT:this.internalEventEmitter.emit(F.WEBRTC_CHAT_MESSAGE_RECEIVED,a.data);break;case te.CLIENT_TOOL_EVENT:const E=a.data;this.internalEventEmitter.emit(F.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,E);const p=ki.WebRTCClientToolEventToClientToolEvent(E);this.publicEventEmitter.emit(b.CLIENT_TOOL_EVENT_RECEIVED,p);break;case te.TOOL_CALL_STARTED_EVENT:const f=a.data;this.publicEventEmitter.emit(b.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(f)),this.internalEventEmitter.emit(F.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,f);break;case te.TOOL_CALL_COMPLETED_EVENT:const d=a.data;this.publicEventEmitter.emit(b.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(d)),this.internalEventEmitter.emit(F.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,d);break;case te.TOOL_CALL_FAILED_EVENT:const y=a.data;this.publicEventEmitter.emit(b.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(y)),this.internalEventEmitter.emit(F.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,y);break;case te.REASONING_TEXT:this.internalEventEmitter.emit(F.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,a.data);break;case te.USER_SPEECH_STARTED:this.publicEventEmitter.emit(b.USER_SPEECH_STARTED,(c=(o=a.data)===null||o===void 0?void 0:o.user_action_correlation_id)!==null&&c!==void 0?c:"unknown");break;case te.USER_SPEECH_ENDED:this.publicEventEmitter.emit(b.USER_SPEECH_ENDED,(u=(s=a.data)===null||s===void 0?void 0:s.user_action_correlation_id)!==null&&u!==void 0?u:"unknown");break;default:break}}catch(a){console.error("Failed to parse data channel message:",a)}}})}requestMicrophonePermissionAsync(){return Q(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==fe.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.PENDING}),this.publicEventEmitter.emit(b.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:fe.GRANTED}),this.publicEventEmitter.emit(b.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:fe.DENIED});const i=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(b.MIC_PERMISSION_DENIED,i)}}})}setupAudioTrack(){return Q(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(b.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return Q(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 Q(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const i=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(i){const o=xn(i,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(i=>{i.stop()}),this.inputAudioStream=null}catch(i){console.error("StreamingClient - shutdown: error stopping input audio stream",i)}try{this.signallingClient.stop()}catch(i){console.error("StreamingClient - shutdown: error stopping signallilng",i)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(i){console.error("StreamingClient - shutdown: error closing peer connection",i)}})}}class Zn{constructor(e,i){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(F.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 i=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(b.REASONING_STREAM_EVENT_RECEIVED,i);const o={id:i.id,content:i.content,role:i.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);i.endOfThought&&this.publicEventEmitter.emit(b.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var _e=function(t,e,i,o){function c(s){return s instanceof i?s:new i(function(u){u(s)})}return new(i||(i=Promise))(function(s,u){function a(f){try{p(o.next(f))}catch(d){u(d)}}function E(f){try{p(o.throw(f))}catch(d){u(d)}}function p(f){f.done?s(f.value):c(f.value).then(a,E)}p((o=o.apply(t,e||[])).next())})};class Qn{constructor(e,i,o){var c,s,u,a,E;this.inputAudioState={isMuted:!1,permissionState:fe.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,i,o);if(p)throw new V(p,z.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=i,this.clientOptions=o,(!((c=o?.api)===null||c===void 0)&&c.baseUrl||!((s=o?.api)===null||s===void 0)&&s.apiVersion)&&Rn(o.api.baseUrl||Oi,o.api.apiVersion||St),!((a=(u=o?.api)===null||u===void 0?void 0:u.apiGateway)===null||a===void 0)&&a.enabled&&On(o.api.apiGateway),!((E=o?.metrics)===null||E===void 0)&&E.disableClientMetrics&&Nn(!0),this.publicEventEmitter=new zn,this.internalEventEmitter=new Hn,this.toolCallManager=new ki(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new Pn(e,o?.apiKey,o?.api),this.messageHistoryClient=new Wn(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Zn(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const i=e.split(".")[1],o=yn.Buffer.from(i,"base64").toString("utf8");return JSON.parse(o)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,i,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=Ln((c=o?.api)===null||c===void 0?void 0:c.apiGateway);if(u)return u;if(e){const a=this.decodeJwt(e);this.organizationId=a.accountId,be({organizationId:this.organizationId});const E=(s=a.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")&&i)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!i)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 i={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(i.voiceDetection=this.clientOptions.voiceDetection),Object.keys(i).length!==0)return i}startSession(e){return _e(this,void 0,void 0,function*(){var i,o,c,s,u,a,E,p,f,d,y,g,S,T,A,w,I;const R=this.personaConfig,D=this.buildStartSessionOptionsForClient(),N=yield this.apiClient.startSession(R,D),{sessionId:j,clientConfig:ae,engineHost:G,engineProtocol:ie,signallingEndpoint:ye}=N,{heartbeatIntervalSeconds:X,maxWsReconnectionAttempts:ne,iceServers:Nt,iceTransportPolicy:nt}=ae;this.sessionId=j,this.toolCallManager.setActiveSession(j),be({sessionId:this.sessionId});const rt=(u=(o=(i=this.clientOptions)===null||i===void 0?void 0:i.iceServers)!==null&&o!==void 0?o:(s=(c=this.clientOptions)===null||c===void 0?void 0:c.rtcConfiguration)===null||s===void 0?void 0:s.iceServers)!==null&&u!==void 0?u:Nt;try{this.streamingClient=new Xn(j,{engine:{baseUrl:`${ie}://${G}`},signalling:{heartbeatIntervalSeconds:X,maxWsReconnectionAttempts:ne,url:{baseUrl:G,protocol:ie,signallingPath:ye}},iceServers:rt,iceTransportPolicy:nt,rtcConfiguration:(a=this.clientOptions)===null||a===void 0?void 0:a.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((E=this.clientOptions)===null||E===void 0)&&E.disableInputAudio?void 0:e,audioDeviceId:(p=this.clientOptions)===null||p===void 0?void 0:p.audioDeviceId,disableInputAudio:(f=this.clientOptions)===null||f===void 0?void 0:f.disableInputAudio},apiGateway:(y=(d=this.clientOptions)===null||d===void 0?void 0:d.api)===null||y===void 0?void 0:y.apiGateway,metrics:{showPeerConnectionStatsReport:(T=(S=(g=this.clientOptions)===null||g===void 0?void 0:g.metrics)===null||S===void 0?void 0:S.showPeerConnectionStatsReport)!==null&&T!==void 0?T:!1,peerConnectionStatsReportOutputFormat:(I=(w=(A=this.clientOptions)===null||A===void 0?void 0:A.metrics)===null||w===void 0?void 0:w.peerConnectionStatsReportOutputFormat)!==null&&I!==void 0?I:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager)}catch(Fe){throw this.toolCallManager.clearSessionState(),be({sessionId:null}),new V("Failed to initialize streaming client",z.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:Fe instanceof Error?Fe.message:String(Fe),sessionId:j})}return j})}startSessionIfNeeded(e){return _e(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new V("Session ID or streaming client is not available after starting session",z.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return _e(this,void 0,void 0,function*(){var i;if(this._isStreaming)throw new Error("Already streaming");const o=Li();return be({attemptCorrelationId:o,sessionId:null}),ve(se.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((i=this.clientOptions)===null||i===void 0)&&i.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 a=!1,E=!1;this.publicEventEmitter.addListener(b.VIDEO_STREAM_STARTED,p=>{u.push(p),a=!0,E&&c(u)}),this.publicEventEmitter.addListener(b.AUDIO_STREAM_STARTED,p=>{u.push(p),E=!0,a&&c(u)}),(s=this.streamingClient)===null||s===void 0||s.startConnection()})})}streamToVideoAndAudioElements(e,i,o){return _e(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,i){return _e(this,void 0,void 0,function*(){var o;const c=Li();be({attemptCorrelationId:c,sessionId:null}),ve(se.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio&&i&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(i)}catch(s){throw s instanceof V?s:new V("Failed to start session",z.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 _e(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 i=this.getActiveSessionId();if(!i)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:i,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 i=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(i)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const i=this.getActiveSessionId();if(!i)throw new Error("Failed to add context: no active session");const o=JSON.stringify({message_type:"context",session_id:i,content:e});this.sendDataMessage(o)}stopStreaming(){return _e(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(b.CONNECTION_CLOSED,pe.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,be({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,i;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&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,i;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&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return _e(this,void 0,void 0,function*(){var i;if(!((i=this.clientOptions)===null||i===void 0)&&i.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,i){this.publicEventEmitter.addListener(e,i)}removeListener(e,i){this.publicEventEmitter.removeListener(e,i)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,i){return this.toolCallManager.registerHandler(e,i)}}const er=(t,e)=>new Qn(t,void 0,e),J={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",TOOL_CALL_STARTED:"anam-agent:tool-call-started",TOOL_CALL_COMPLETED:"anam-agent:tool-call-completed",TOOL_CALL_FAILED:"anam-agent:tool-call-failed"},tr="https://api.anam.ai";function Mi(t){return/^[a-zA-Z0-9_-]{1,128}$/.test(t)}function Ui(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}function ir(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 nr(){return{client:Y(null),connectionStatus:Y("idle"),isStreaming:Y(!1),isMuted:Y(!1),messages:Y([]),error:Y(null),sessionId:Y(null),avatarThumbnailUrl:Y(null),avatarVideoUrl:Y(null),personaName:Y(null),serverConfig:Y(null),isConfigured:Y(!1),isReady:Y(!1),generation:0,prevMessageCount:0,dispatch:null}}async function rr(t,e,i){if(t.isReady.value=!1,!Mi(e)){console.error("[AnamWidget] Invalid agent ID format:",e);return}try{const o=await fetch(`${i}/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 or(t,e,i,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 a;if(c)a=c;else{if(!Mi(e))throw new Error("Invalid agent ID format");const f=await fetch(`${i}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:e})});if(s!==t.generation)return;if(u=f.status,!f.ok){const y=await f.json().catch(()=>({}));throw new Error(y.error||`HTTP ${f.status}`)}a=(await f.json()).sessionToken}if(s!==t.generation)return;const E=er(a,{api:i?{baseUrl:i}:void 0,metrics:{disableClientMetrics:!0}});E.addListener(b.CONNECTION_ESTABLISHED,()=>{s===t.generation&&(t.connectionStatus.value="connected")}),E.addListener(b.VIDEO_STREAM_STARTED,()=>{s===t.generation&&(t.isStreaming.value=!0)}),E.addListener(b.AUDIO_STREAM_STARTED,()=>{}),E.addListener(b.MESSAGE_HISTORY_UPDATED,f=>{if(s===t.generation){for(let d=t.prevMessageCount;d<f.length;d++){const y=f[d];t.dispatch?.(J.MESSAGE_RECEIVED,{role:y.role==="persona"?"agent":"user",content:y.content})}t.prevMessageCount=f.length,t.messages.value=[...f]}}),E.addListener(b.TOOL_CALL_STARTED,f=>{s===t.generation&&t.dispatch?.(J.TOOL_CALL_STARTED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,arguments:f.arguments})}),E.addListener(b.TOOL_CALL_COMPLETED,f=>{s===t.generation&&t.dispatch?.(J.TOOL_CALL_COMPLETED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,result:f.result,executionTime:f.executionTime,documentsAccessed:f.documentsAccessed})}),E.addListener(b.TOOL_CALL_FAILED,f=>{s===t.generation&&t.dispatch?.(J.TOOL_CALL_FAILED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,errorMessage:f.errorMessage,executionTime:f.executionTime})}),E.addListener(b.CONNECTION_CLOSED,(f,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?.(J.SESSION_ENDED,{sessionId:y??"",reason:d??f})}),E.addListener(b.SESSION_READY,f=>{s===t.generation&&(t.sessionId.value=f,t.dispatch?.(J.SESSION_STARTED,{sessionId:f}))});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 f=p.find(d=>d.getVideoTracks().length>0);f&&(o.srcObject=f)}}catch(a){if(s!==t.generation)return;console.error("[AnamWidget] Failed to start session:",a);const E=ir(a,u);t.error.value=E,t.connectionStatus.value="error",t.client.value=null,t.dispatch?.(J.ERROR,{code:u?`HTTP_${u}`:"SESSION_ERROR",message:E})}}async function sr(t){const e=t.sessionId.value,i=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,i&&t.dispatch?.(J.SESSION_ENDED,{sessionId:e??"",reason:"USER_ENDED"})}function ar(t,e){!t.client.value||t.connectionStatus.value!=="connected"||(t.client.value.sendUserMessage(e),t.dispatch?.(J.MESSAGE_SENT,{content:e}))}function lr(t){t.client.value&&(t.isMuted.value?(t.client.value.unmuteInputAudio(),t.isMuted.value=!1,t.dispatch?.(J.MIC_UNMUTED,{})):(t.client.value.muteInputAudio(),t.isMuted.value=!0,t.dispatch?.(J.MIC_MUTED,{})))}function cr(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 ur(t,e,i,o){const c=Me();c.current||(c.current=nr());const s=c.current;s.dispatch=o??null;const u=t||(i?Ui(i).personaId:void 0),a=!!u||!!i;s.isConfigured.value!==a&&(s.isConfigured.value=a);const E=e||tr;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){rr(s,u,E);return}if(i){const f=Ui(i).widgetConfig;f&&(typeof f.personaName=="string"&&f.personaName&&(s.personaName.value=f.personaName),typeof f.avatarImageUrl=="string"&&f.avatarImageUrl&&(s.avatarThumbnailUrl.value=f.avatarImageUrl),typeof f.avatarVideoUrl=="string"&&f.avatarVideoUrl&&(s.avatarVideoUrl.value=f.avatarVideoUrl),f.removeWatermark===!0&&(s.serverConfig.value={removeWatermark:!0})),s.isReady.value=!0;return}s.isReady.value=!0},startSession:p=>!u&&!i?(s.error.value="No agent ID or session token configured",Promise.resolve()):or(s,u||"",E,p,i),stopSession:()=>sr(s),sendMessage:p=>ar(s,p),toggleMute:()=>lr(s),cleanup:()=>cr(s)}}function dr(t,e,i){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}const hr='@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 fr extends Ce{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("[AnamWidget] Render error:",e)}render(){return this.state.hasError?C("div",{class:"anam-overlay-error",children:C("div",{class:"anam-overlay-error-text",children:"Widget failed to load"})}):this.props.children}}function At(t,e){const i={...t};for(const o of Object.keys(e)){const c=e[o];c!==void 0&&(c!==null&&typeof c=="object"&&!Array.isArray(c)&&typeof i[o]=="object"&&i[o]!==null&&!Array.isArray(i[o])?i[o]=At(i[o],c):i[o]=c)}return i}function bt(t){if(t!==void 0)return t==="true"}function pr(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const i=bt(t["ui-mute-button"]);i!==void 0&&(e.showMuteButton=i);const o=bt(t["ui-text-input"]);o!==void 0&&(e.showTextInput=o);const c=bt(t["ui-captions"]);return c!==void 0&&(e.showCaptions=c),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const _r=()=>C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round",children:C("path",{d:"M18 6L6 18M6 6l12 12"})}),Er=()=>C("svg",{width:"24",height:"24",viewBox:"0 0 640 640",fill:"currentColor",children:C("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"})}),mr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),C("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),gr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),C("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),C("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),vr=()=>C("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),C("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),Rt=()=>C("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[C("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),C("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function yr({config:t,session:e,videoRef:i,avatarSrc:o,avatarVideoSrc:c,displayCta:s,onCollapse:u,onStop:a}){const E=Me(null),[p,f]=ze(""),[d,y]=ze(null),[g,S]=ze(!1),T=Me(null),A=e.connectionStatus.value==="connected",w=e.connectionStatus.value==="connecting",I=e.connectionStatus.value==="error",R=e.isStreaming.value,D=!w&&!A&&!I,N=Ye(async()=>{i.current&&await e.startSession(i.current)},[e.startSession]),j=Ye(()=>{if(!p.trim())return;const G=p.trim();e.sendMessage(G),f(""),E.current?.focus(),T.current&&clearTimeout(T.current),S(!1),y(G),T.current=window.setTimeout(()=>{S(!0),T.current=window.setTimeout(()=>{y(null),S(!1)},400)},2600)},[p]),ae=Ye(G=>{G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),j())},[j]);return qe(()=>()=>{T.current&&clearTimeout(T.current)},[]),C("div",{class:"anam-sheet",children:[C("video",{ref:i,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":R?void 0:"true"}),D&&(e.isConfigured.value?C("div",{class:"anam-overlay-idle",children:[c?C("video",{src:c,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:G=>{G.target.style.display="none"}}):null,o?C("img",{src:o,alt:"Avatar",class:c?"anam-preview-fallback":void 0}):C(Rt,{}),C("button",{class:"anam-cta-pill",onClick:N,children:[C(Er,{}),s]})]}):C("div",{class:"anam-overlay-unconfigured",children:[C(Rt,{}),C("span",{children:"Agent not configured"})]})),w&&C("div",{class:"anam-overlay-loading",children:[C("span",{class:"anam-spinner"}),C("span",{children:"Starting your conversation..."})]}),I&&C("div",{class:"anam-overlay-error",children:[C("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),C("button",{class:"anam-retry-btn",onClick:N,children:"Try Again"})]}),(u||a&&(A||w||R))&&C("button",{class:"anam-close-btn",onClick:u||a,"aria-label":u?"Close":"End call",children:C(_r,{})}),(A||R)&&C(ce,{children:[d&&C("div",{class:`anam-toast ${g?"anam-toast-out":""}`,children:d}),C("div",{class:"anam-control-bar",children:[t.showMuteButton&&C("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?C(gr,{}):C(mr,{})}),t.showTextInput&&C("div",{class:"anam-ctl-input-wrap",children:[C("input",{ref:E,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:p,onInput:G=>f(G.target.value),onKeyDown:ae,disabled:!A}),C("button",{class:"anam-ctl-send",onClick:j,disabled:!A||!p.trim(),"aria-label":"Send message",children:C(vr,{})})]})]})]}),!t.removeWatermark&&C("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:C("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[C("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"}),C("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),C("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"}),C("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 Sr(t){return C(ce,{children:[C("style",{children:hr}),C(fr,{children:C(Cr,{...t})})]})}function Cr(t){const e=Me(null),i=Me(null),o=Ye((R,D)=>{const N=i.current?.getRootNode();N&&N instanceof ShadowRoot&&dr(N.host,R,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=ur(c,t["api-base-url"],t["session-token"],o);qe(()=>()=>{s.cleanup()},[]);const u=Ie(()=>pr(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["call-to-action"]]),a=Ie(()=>{const R=s.serverConfig.value;return At(At({...vt},R??{}),u)},[s.serverConfig.value,u]),E=Ti(a.layout==="floating"?a.initialState:"expanded");qe(()=>{a.layout==="inline"?E.value="expanded":E.value=a.initialState},[a.layout,a.initialState]),qe(()=>{s.fetchWidgetConfig()},[c,t["api-base-url"],t["session-token"]]);const p=t["avatar-url"]||s.avatarThumbnailUrl.value||null,f=t["avatar-video-url"]||s.avatarVideoUrl.value||null,y=t["agent-name"]||s.personaName.value,g=a.callToAction===vt.callToAction&&y?`Talk to ${y}`:a.callToAction,S=Ie(()=>{if(a.layout==="inline")return"";const R=En(a.position);return Object.entries(R).map(([D,N])=>`${D}: ${N}`).join("; ")},[a.layout,a.position]),T=a.layout==="floating",A=()=>{E.value="expanded",o(J.EXPANDED,{})},w=async()=>{s.connectionStatus.value!=="idle"&&await s.stopSession(),E.value="minimized",o(J.COLLAPSED,{})},I=T?E.value==="expanded":!0;return s.isReady.value?C("div",{ref:i,class:"anam-widget","data-layout":a.layout,"data-state":E.value,style:S,children:[T&&E.value==="minimized"&&C("button",{class:"anam-trigger",onClick:A,"aria-label":g,children:p?C("img",{src:p,alt:"Avatar"}):C(Rt,{})}),I&&C(yr,{config:a,session:s,videoRef:e,avatarSrc:p,avatarVideoSrc:f,displayCta:g,onCollapse:T?w:null,onStop:T?null:()=>s.stopSession()})]}):null}const Tr=["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 Ot(t="anam-agent"){Zi(Sr,t,[...Tr],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Ot()):Ot()),le.DefaultConfig=vt,le.WidgetEventNames=J,le.registerWidget=Ot,Object.defineProperty(le,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(ue,de){typeof exports=="object"&&typeof module<"u"?de(exports):typeof define=="function"&&define.amd?define(["exports"],de):(ue=typeof globalThis<"u"?globalThis:ue||self,de(ue.AnamAgentWidget={}))})(this,(function(ue){"use strict";var de,N,jt,Gt,ye,Ht,zt,qt,Yt,ht,ft,pt,Be={},Kt=[],dn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Xe=Array.isArray;function ae(t,e){for(var i in e)t[i]=e[i];return t}function _t(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function we(t,e,i){var n,a,s,d={};for(s in e)s=="key"?n=e[s]:s=="ref"?a=e[s]:d[s]=e[s];if(arguments.length>2&&(d.children=arguments.length>3?de.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)d[s]===void 0&&(d[s]=t.defaultProps[s]);return Fe(t,d,n,a,null)}function Fe(t,e,i,n,a){var s={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++jt,__i:-1,__u:0};return a==null&&N.vnode!=null&&N.vnode(s),s}function he(t){return t.children}function Re(t,e){this.props=t,this.context=e}function Ae(t,e){if(e==null)return t.__?Ae(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?Ae(t):null}function Jt(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return Jt(t)}}function Xt(t){(!t.__d&&(t.__d=!0)&&ye.push(t)&&!Ze.__r++||Ht!=N.debounceRendering)&&((Ht=N.debounceRendering)||zt)(Ze)}function Ze(){for(var t,e,i,n,a,s,d,l=1;ye.length;)ye.length>l&&ye.sort(qt),t=ye.shift(),l=ye.length,t.__d&&(i=void 0,n=void 0,a=(n=(e=t).__v).__e,s=[],d=[],e.__P&&((i=ae({},n)).__v=n.__v+1,N.vnode&&N.vnode(i),mt(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[a]:null,s,a??Ae(n),!!(32&n.__u),d),i.__v=n.__v,i.__.__k[i.__i]=i,ii(s,i,d),n.__e=n.__=null,i.__e!=a&&Jt(i)));Ze.__r=0}function Zt(t,e,i,n,a,s,d,l,m,p,f){var u,y,E,S,T,I,w,b=n&&n.__k||Kt,O=e.length;for(m=un(i,e,b,m,O),u=0;u<O;u++)(E=i.__k[u])!=null&&(y=E.__i==-1?Be:b[E.__i]||Be,E.__i=u,I=mt(t,E,y,a,s,d,l,m,p,f),S=E.__e,E.ref&&y.ref!=E.ref&&(y.ref&&Et(y.ref,null,E),f.push(E.ref,E.__c||S,E)),T==null&&S!=null&&(T=S),(w=!!(4&E.__u))||y.__k===E.__k?m=Qt(E,m,t,w):typeof E.type=="function"&&I!==void 0?m=I:S&&(m=S.nextSibling),E.__u&=-7);return i.__e=T,m}function un(t,e,i,n,a){var s,d,l,m,p,f=i.length,u=f,y=0;for(t.__k=new Array(a),s=0;s<a;s++)(d=e[s])!=null&&typeof d!="boolean"&&typeof d!="function"?(typeof d=="string"||typeof d=="number"||typeof d=="bigint"||d.constructor==String?d=t.__k[s]=Fe(null,d,null,null,null):Xe(d)?d=t.__k[s]=Fe(he,{children:d},null,null,null):d.constructor===void 0&&d.__b>0?d=t.__k[s]=Fe(d.type,d.props,d.key,d.ref?d.ref:null,d.__v):t.__k[s]=d,m=s+y,d.__=t,d.__b=t.__b+1,l=null,(p=d.__i=hn(d,i,m,u))!=-1&&(u--,(l=i[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(a>f?y--:a<f&&y++),typeof d.type!="function"&&(d.__u|=4)):p!=m&&(p==m-1?y--:p==m+1?y++:(p>m?y--:y++,d.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<f;s++)(l=i[s])!=null&&(2&l.__u)==0&&(l.__e==n&&(n=Ae(l)),ri(l,l));return n}function Qt(t,e,i,n){var a,s;if(typeof t.type=="function"){for(a=t.__k,s=0;a&&s<a.length;s++)a[s]&&(a[s].__=t,e=Qt(a[s],e,i,n));return e}t.__e!=e&&(n&&(e&&t.type&&!e.parentNode&&(e=Ae(t)),i.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function hn(t,e,i,n){var a,s,d,l=t.key,m=t.type,p=e[i],f=p!=null&&(2&p.__u)==0;if(p===null&&l==null||f&&l==p.key&&m==p.type)return i;if(n>(f?1:0)){for(a=i-1,s=i+1;a>=0||s<e.length;)if((p=e[d=a>=0?a--:s++])!=null&&(2&p.__u)==0&&l==p.key&&m==p.type)return d}return-1}function ei(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||dn.test(e)?i:i+"px"}function Qe(t,e,i,n,a){var s,d;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||ei(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||ei(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Yt,"$1")),d=e.toLowerCase(),e=d in t||e=="onFocusOut"||e=="onFocusIn"?d.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=i,i?n?i.u=n.u:(i.u=ht,t.addEventListener(e,s?pt:ft,s)):t.removeEventListener(e,s?pt:ft,s);else{if(a=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function ti(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=ht++;else if(e.t<i.u)return;return i(N.event?N.event(e):e)}}}function mt(t,e,i,n,a,s,d,l,m,p){var f,u,y,E,S,T,I,w,b,O,k,R,ee,G,oe,te,se,W=e.type;if(e.constructor!==void 0)return null;128&i.__u&&(m=!!(32&i.__u),s=[l=e.__e=i.__e]),(f=N.__b)&&f(e);e:if(typeof W=="function")try{if(w=e.props,b="prototype"in W&&W.prototype.render,O=(f=W.contextType)&&n[f.__c],k=f?O?O.props.value:f.__:n,i.__c?I=(u=e.__c=i.__c).__=u.__E:(b?e.__c=u=new W(w,k):(e.__c=u=new Re(w,k),u.constructor=W,u.render=pn),O&&O.sub(u),u.state||(u.state={}),u.__n=n,y=u.__d=!0,u.__h=[],u._sb=[]),b&&u.__s==null&&(u.__s=u.state),b&&W.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=ae({},u.__s)),ae(u.__s,W.getDerivedStateFromProps(w,u.__s))),E=u.props,S=u.state,u.__v=e,y)b&&W.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),b&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(b&&W.getDerivedStateFromProps==null&&w!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(w,k),e.__v==i.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(w,u.__s,k)===!1){for(e.__v!=i.__v&&(u.props=w,u.state=u.__s,u.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(Q){Q&&(Q.__=e)}),R=0;R<u._sb.length;R++)u.__h.push(u._sb[R]);u._sb=[],u.__h.length&&d.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(w,u.__s,k),b&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,S,T)})}if(u.context=k,u.props=w,u.__P=t,u.__e=!1,ee=N.__r,G=0,b){for(u.state=u.__s,u.__d=!1,ee&&ee(e),f=u.render(u.props,u.state,u.context),oe=0;oe<u._sb.length;oe++)u.__h.push(u._sb[oe]);u._sb=[]}else do u.__d=!1,ee&&ee(e),f=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++G<25);u.state=u.__s,u.getChildContext!=null&&(n=ae(ae({},n),u.getChildContext())),b&&!y&&u.getSnapshotBeforeUpdate!=null&&(T=u.getSnapshotBeforeUpdate(E,S)),te=f,f!=null&&f.type===he&&f.key==null&&(te=ni(f.props.children)),l=Zt(t,Xe(te)?te:[te],e,i,n,a,s,d,l,m,p),u.base=e.__e,e.__u&=-161,u.__h.length&&d.push(u),I&&(u.__E=u.__=null)}catch(Q){if(e.__v=null,m||s!=null)if(Q.then){for(e.__u|=m?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--;)_t(s[se]);gt(e)}else e.__e=i.__e,e.__k=i.__k,Q.then||gt(e);N.__e(Q,e,i)}else s==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):l=e.__e=fn(i.__e,e,i,n,a,s,d,m,p);return(f=N.diffed)&&f(e),128&e.__u?void 0:l}function gt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(gt)}function ii(t,e,i){for(var n=0;n<i.length;n++)Et(i[n],i[++n],i[++n]);N.__c&&N.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){N.__e(s,a.__v)}})}function ni(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Xe(t)?t.map(ni):ae({},t)}function fn(t,e,i,n,a,s,d,l,m){var p,f,u,y,E,S,T,I=i.props||Be,w=e.props,b=e.type;if(b=="svg"?a="http://www.w3.org/2000/svg":b=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(p=0;p<s.length;p++)if((E=s[p])&&"setAttribute"in E==!!b&&(b?E.localName==b:E.nodeType==3)){t=E,s[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(w);t=document.createElementNS(a,b,w.is&&w),l&&(N.__m&&N.__m(e,s),l=!1),s=null}if(b==null)I===w||l&&t.data==w||(t.data=w);else{if(s=s&&de.call(t.childNodes),!l&&s!=null)for(I={},p=0;p<t.attributes.length;p++)I[(E=t.attributes[p]).name]=E.value;for(p in I)if(E=I[p],p!="children"){if(p=="dangerouslySetInnerHTML")u=E;else if(!(p in w)){if(p=="value"&&"defaultValue"in w||p=="checked"&&"defaultChecked"in w)continue;Qe(t,p,null,E,a)}}for(p in w)E=w[p],p=="children"?y=E:p=="dangerouslySetInnerHTML"?f=E:p=="value"?S=E:p=="checked"?T=E:l&&typeof E!="function"||I[p]===E||Qe(t,p,E,I[p],a);if(f)l||u&&(f.__html==u.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(u&&(t.innerHTML=""),Zt(e.type=="template"?t.content:t,Xe(y)?y:[y],e,i,n,b=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,d,s?s[0]:i.__k&&Ae(i,0),l,m),s!=null)for(p=s.length;p--;)_t(s[p]);l||(p="value",b=="progress"&&S==null?t.removeAttribute("value"):S!=null&&(S!==t[p]||b=="progress"&&!S||b=="option"&&S!=I[p])&&Qe(t,p,S,I[p],a),p="checked",T!=null&&T!=t[p]&&Qe(t,p,T,I[p],a))}return t}function Et(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(a){N.__e(a,i)}}function ri(t,e,i){var n,a;if(N.unmount&&N.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Et(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){N.__e(s,e)}n.base=n.__P=null}if(n=t.__k)for(a=0;a<n.length;a++)n[a]&&ri(n[a],e,i||typeof t.type!="function");i||_t(t.__e),t.__c=t.__=t.__e=void 0}function pn(t,e,i){return this.constructor(t,i)}function et(t,e,i){var n,a,s,d;e==document&&(e=document.documentElement),N.__&&N.__(t,e),a=(n=typeof i=="function")?null:i&&i.__k||e.__k,s=[],d=[],mt(e,t=(!n&&i||e).__k=we(he,null,[t]),a||Be,Be,e.namespaceURI,!n&&i?[i]:a?null:e.firstChild?de.call(e.childNodes):null,s,!n&&i?i:a?a.__e:e.firstChild,n,d),ii(s,t,d)}function oi(t,e){et(t,e,oi)}function si(t,e,i){var n,a,s,d,l=ae({},t.props);for(s in t.type&&t.type.defaultProps&&(d=t.type.defaultProps),e)s=="key"?n=e[s]:s=="ref"?a=e[s]:l[s]=e[s]===void 0&&d!=null?d[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?de.call(arguments,2):i),Fe(t.type,l,n||t.key,a||t.ref,null)}de=Kt.slice,N={__e:function(t,e,i,n){for(var a,s,d;e=e.__;)if((a=e.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(t)),d=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(t,n||{}),d=a.__d),d)return a.__E=a}catch(l){t=l}throw t}},jt=0,Gt=function(t){return t!=null&&t.constructor===void 0},Re.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ae({},this.state),typeof t=="function"&&(t=t(ae({},i),this.props)),t&&ae(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Xt(this))},Re.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Xt(this))},Re.prototype.render=he,ye=[],zt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,qt=function(t,e){return t.__v.__b-e.__v.__b},Ze.__r=0,Yt=/(PointerCapture)$|Capture$/i,ht=0,ft=ti(!1),pt=ti(!0);function tt(){return tt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},tt.apply(this,arguments)}function ai(t,e){if(t==null)return{};var i,n,a={},s=Object.keys(t);for(n=0;n<s.length;n++)e.indexOf(i=s[n])>=0||(a[i]=t[i]);return a}var _n=["context","children"],mn=["useFragment"];function gn(t,e,i,n){function a(){var s,d=Reflect.construct(HTMLElement,[],a);return d._vdomComponent=t,n&&n.shadow?(d._root=d.attachShadow({mode:n.mode||"open",serializable:(s=n.serializable)!=null&&s}),n.adoptedStyleSheets&&(d._root.adoptedStyleSheets=n.adoptedStyleSheets)):d._root=d,d}return(a.prototype=Object.create(HTMLElement.prototype)).constructor=a,a.prototype.connectedCallback=function(){vn.call(this,n)},a.prototype.attributeChangedCallback=Cn,a.prototype.disconnectedCallback=Sn,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),a.observedAttributes=i,t.formAssociated&&(a.formAssociated=!0),i.forEach(function(s){Object.defineProperty(a.prototype,s,{get:function(){return this._vdom?this._vdom.props[s]:this._props[s]},set:function(d){this._vdom?this.attributeChangedCallback(s,null,d):(this._props||(this._props={}),this._props[s]=d);var l=typeof d;d!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(s,d)}})}),customElements.define(e||t.tagName||t.displayName||t.name,a),a}function En(t){this.getChildContext=function(){return t.context};var e=t.children,i=ai(t,_n);return si(e,i)}function vn(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=we(En,tt({},this._props,{context:e.detail.context}),di(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?oi:et)(this._vdom,this._root)}function li(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function Cn(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[li(t)]=i,this._vdom=si(this._vdom,n),et(this._vdom,this._root)}}function Sn(){et(this._vdom=null,this._root)}function ci(t,e){var i=this,n=t.useFragment,a=ai(t,mn);return we(n?he:"slot",tt({},a,{ref:function(s){s?(i.ref=s,i._listener||(i._listener=function(d){d.stopPropagation(),d.detail.context=e},s.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function di(t,e,i){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var n=[],a={},s=0,d=t.attributes,l=t.childNodes;for(s=d.length;s--;)d[s].name!=="slot"&&(a[d[s].name]=d[s].value,a[li(d[s].name)]=d[s].value);for(s=l.length;s--;){var m=di(l[s],null,i),p=l[s].slot;p?a[p]=we(ci,{name:p},m):n[s]=m}var f=!(!i||!i.shadow),u=e?we(ci,{useFragment:!f},n):n;return!f&&e&&(t.innerHTML=""),we(e||t.nodeName.toLowerCase(),a,u)}var yn=0;function C(t,e,i,n,a,s){e||(e={});var d,l,m=e;if("ref"in m)for(l in m={},e)l=="ref"?d=e[l]:m[l]=e[l];var p={type:t,props:m,key:i,ref:d,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--yn,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(d=t.defaultProps))for(l in d)m[l]===void 0&&(m[l]=d[l]);return N.vnode&&N.vnode(p),p}var $e,F,vt,ui,Ve=0,hi=[],V=N,fi=V.__b,pi=V.__r,_i=V.diffed,mi=V.__c,gi=V.unmount,Ei=V.__;function Ct(t,e){V.__h&&V.__h(F,t,Ve||e),Ve=0;var i=F.__H||(F.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function St(t){return Ve=1,Tn(Si,t)}function Tn(t,e,i){var n=Ct($e++,2);if(n.t=t,!n.__c&&(n.__=[Si(void 0,e),function(l){var m=n.__N?n.__N[0]:n.__[0],p=n.t(m,l);m!==p&&(n.__N=[p,n.__[1]],n.__c.setState({}))}],n.__c=F,!F.__f)){var a=function(l,m,p){if(!n.__c.__H)return!0;var f=n.__c.__H.__.filter(function(y){return!!y.__c});if(f.every(function(y){return!y.__N}))return!s||s.call(this,l,m,p);var u=n.__c.props!==l;return f.forEach(function(y){if(y.__N){var E=y.__[0];y.__=y.__N,y.__N=void 0,E!==y.__[0]&&(u=!0)}}),s&&s.call(this,l,m,p)||u};F.__f=!0;var s=F.shouldComponentUpdate,d=F.componentWillUpdate;F.componentWillUpdate=function(l,m,p){if(this.__e){var f=s;s=void 0,a(l,m,p),s=f}d&&d.call(this,l,m,p)},F.shouldComponentUpdate=a}return n.__N||n.__}function Oe(t,e){var i=Ct($e++,3);!V.__s&&Ci(i.__H,e)&&(i.__=t,i.u=e,F.__H.__h.push(i))}function We(t){return Ve=5,xe(function(){return{current:t}},[])}function xe(t,e){var i=Ct($e++,7);return Ci(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function je(t,e){return Ve=8,xe(function(){return t},e)}function In(){for(var t;t=hi.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(it),t.__H.__h.forEach(yt),t.__H.__h=[]}catch(e){t.__H.__h=[],V.__e(e,t.__v)}}V.__b=function(t){F=null,fi&&fi(t)},V.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ei&&Ei(t,e)},V.__r=function(t){pi&&pi(t),$e=0;var e=(F=t.__c).__H;e&&(vt===F?(e.__h=[],F.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(it),e.__h.forEach(yt),e.__h=[],$e=0)),vt=F},V.diffed=function(t){_i&&_i(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(hi.push(e)!==1&&ui===V.requestAnimationFrame||((ui=V.requestAnimationFrame)||bn)(In)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),vt=F=null},V.__c=function(t,e){e.some(function(i){try{i.__h.forEach(it),i.__h=i.__h.filter(function(n){return!n.__||yt(n)})}catch(n){e.some(function(a){a.__h&&(a.__h=[])}),e=[],V.__e(n,i.__v)}}),mi&&mi(t,e)},V.unmount=function(t){gi&&gi(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{it(n)}catch(a){e=a}}),i.__H=void 0,e&&V.__e(e,i.__v))};var vi=typeof requestAnimationFrame=="function";function bn(t){var e,i=function(){clearTimeout(n),vi&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);vi&&(e=requestAnimationFrame(i))}function it(t){var e=F,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),F=e}function yt(t){var e=F;t.__c=t.__(),F=e}function Ci(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Si(t,e){return typeof e=="function"?e(t):e}var wn=Symbol.for("preact-signals");function nt(){if(fe>1)fe--;else{for(var t,e=!1;Ge!==void 0;){var i=Ge;for(Ge=void 0,Tt++;i!==void 0;){var n=i.o;if(i.o=void 0,i.f&=-3,!(8&i.f)&&Ii(i))try{i.c()}catch(a){e||(t=a,e=!0)}i=n}}if(Tt=0,fe--,e)throw t}}function Rn(t){if(fe>0)return t();fe++;try{return t()}finally{nt()}}var M=void 0;function yi(t){var e=M;M=void 0;try{return t()}finally{M=e}}var Ge=void 0,fe=0,Tt=0,rt=0;function Ti(t){if(M!==void 0){var e=t.n;if(e===void 0||e.t!==M)return e={i:0,S:t,p:M.s,n:void 0,t:M,e:void 0,x:void 0,r:e},M.s!==void 0&&(M.s.n=e),M.s=e,t.n=e,32&M.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=M.s,e.n=void 0,M.s.n=e,M.s=e),e}}function z(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}z.prototype.brand=wn,z.prototype.h=function(){return!0},z.prototype.S=function(t){var e=this,i=this.t;i!==t&&t.e===void 0&&(t.x=i,this.t=t,i!==void 0?i.e=t:yi(function(){var n;(n=e.W)==null||n.call(e)}))},z.prototype.U=function(t){var e=this;if(this.t!==void 0){var i=t.e,n=t.x;i!==void 0&&(i.x=n,t.e=void 0),n!==void 0&&(n.e=i,t.x=void 0),t===this.t&&(this.t=n,n===void 0&&yi(function(){var a;(a=e.Z)==null||a.call(e)}))}},z.prototype.subscribe=function(t){var e=this;return He(function(){var i=e.value,n=M;M=void 0;try{t(i)}finally{M=n}},{name:"sub"})},z.prototype.valueOf=function(){return this.value},z.prototype.toString=function(){return this.value+""},z.prototype.toJSON=function(){return this.value},z.prototype.peek=function(){var t=M;M=void 0;try{return this.value}finally{M=t}},Object.defineProperty(z.prototype,"value",{get:function(){var t=Ti(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Tt>100)throw new Error("Cycle detected");this.v=t,this.i++,rt++,fe++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{nt()}}}});function q(t,e){return new z(t,e)}function Ii(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 bi(t){for(var e=t.s;e!==void 0;e=e.n){var i=e.S.n;if(i!==void 0&&(e.r=i),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function wi(t){for(var e=t.s,i=void 0;e!==void 0;){var n=e.p;e.i===-1?(e.S.U(e),n!==void 0&&(n.n=e.n),e.n!==void 0&&(e.n.p=n)):i=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=n}t.s=i}function Te(t,e){z.call(this,void 0),this.x=t,this.s=void 0,this.g=rt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}Te.prototype=new z,Te.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===rt))return!0;if(this.g=rt,this.f|=1,this.i>0&&!Ii(this))return this.f&=-2,!0;var t=M;try{bi(this),M=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(i){this.v=i,this.f|=16,this.i++}return M=t,wi(this),this.f&=-2,!0},Te.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)}z.prototype.S.call(this,t)},Te.prototype.U=function(t){if(this.t!==void 0&&(z.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)}},Te.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(Te.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Ti(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function Ri(t,e){return new Te(t,e)}function Ai(t){var e=t.u;if(t.u=void 0,typeof e=="function"){fe++;var i=M;M=void 0;try{e()}catch(n){throw t.f&=-2,t.f|=8,It(t),n}finally{M=i,nt()}}}function It(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,Ai(t)}function An(t){if(M!==this)throw new Error("Out-of-order effect");wi(this),M=t,this.f&=-2,8&this.f&&It(this),nt()}function Ne(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ne.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()}},Ne.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Ai(this),bi(this),fe++;var t=M;return M=this,An.bind(this,t)},Ne.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ge,Ge=this)},Ne.prototype.d=function(){this.f|=8,1&this.f||It(this)},Ne.prototype.dispose=function(){this.d()};function He(t,e){var i=new Ne(t,e);try{i.c()}catch(a){throw i.d(),a}var n=i.d.bind(i);return n[Symbol.dispose]=n,n}var Oi,bt,On=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,xi=[];He(function(){Oi=this.N})();function Me(t,e){N[t]=e.bind(null,N[t]||function(){})}function ot(t){bt&&bt(),bt=t&&t.S()}function Ni(t){var e=this,i=t.data,n=Mi(i);n.value=i;var a=xe(function(){for(var l=e,m=e.__v;m=m.__;)if(m.__c){m.__c.__$f|=4;break}var p=Ri(function(){var E=n.value.value;return E===0?0:E===!0?"":E||""}),f=Ri(function(){return!Array.isArray(p.value)&&!Gt(p.value)}),u=He(function(){if(this.N=ki,f.value){var E=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=E)}}),y=e.__$u.d;return e.__$u.d=function(){u(),y.call(this)},[f,p]},[]),s=a[0],d=a[1];return s.value?d.peek():d.value}Ni.displayName="ReactiveTextNode",Object.defineProperties(z.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ni},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Me("__b",function(t,e){if(typeof e.type=="string"){var i,n=e.props;for(var a in n)if(a!=="children"){var s=n[a];s instanceof z&&(i||(e.__np=i={}),i[a]=s,n[a]=s.peek())}}t(e)}),Me("__r",function(t,e){if(e.type!==he){ot();var i,n=e.__c;n&&(n.__$f&=-2,(i=n.__$u)===void 0&&(n.__$u=i=(function(a,s){var d;return He(function(){d=this},{name:s}),d.c=a,d})(function(){var a;On&&((a=i.y)==null||a.call(i)),n.__$f|=1,n.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),ot(i)}t(e)}),Me("__e",function(t,e,i,n){ot(),t(e,i,n)}),Me("diffed",function(t,e){ot();var i;if(typeof e.type=="string"&&(i=e.__e)){var n=e.__np,a=e.props;if(n){var s=i.U;if(s)for(var d in s){var l=s[d];l!==void 0&&!(d in n)&&(l.d(),s[d]=void 0)}else s={},i.U=s;for(var m in n){var p=s[m],f=n[m];p===void 0?(p=xn(i,m,f,a),s[m]=p):p.o(f,a)}}}t(e)});function xn(t,e,i,n){var a=e in t&&t.ownerSVGElement===void 0,s=q(i);return{o:function(d,l){s.value=d,n=l},d:He(function(){this.N=ki;var d=s.value.value;n[e]!==d&&(n[e]=d,a?t[e]=d:d!=null&&(d!==!1||e[4]==="-")?t.setAttribute(e,d):t.removeAttribute(e))})}}Me("unmount",function(t,e){if(typeof e.type=="string"){var i=e.__e;if(i){var n=i.U;if(n){i.U=void 0;for(var a in n){var s=n[a];s&&s.d()}}}}else{var d=e.__c;if(d){var l=d.__$u;l&&(d.__$u=void 0,l.d())}}t(e)}),Me("__h",function(t,e,i,n){(n<3||n===9)&&(e.__$f|=2),t(e,i,n)}),Re.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var i=this.__$u,n=i&&i.s!==void 0;for(var a in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(n||s||4&this.__$f)||1&this.__$f)return!0}else if(!(n||4&this.__$f)||3&this.__$f)return!0;for(var d in t)if(d!=="__source"&&t[d]!==this.props[d])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Mi(t,e){return St(function(){return q(t,e)})[0]}var Nn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function Mn(){Rn(function(){for(var t;t=xi.shift();)Oi.call(t)})}function ki(){xi.push(this)===1&&(N.requestAnimationFrame||Nn)(Mn)}const wt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,showTranscript:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},st={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}},kn=new Set(["top","right","bottom","left","margin","margin-top","margin-right","margin-bottom","margin-left"]);function Ln(t){if(st[t])return st[t];const e=t.match(/^\[(.+)\]$/);if(!e)return st["bottom-right"];const i={};for(const n of e[1].split(",")){const a=n.trim(),s=a.lastIndexOf("-");if(s<=0)continue;const d=a.slice(0,s);if(!kn.has(d))continue;const l=a.slice(s+1);/^[\w.%-]+$/.test(l)&&(i[d]=/^\d+$/.test(l)?`${l}px`:l)}return Object.keys(i).length>0?i:st["bottom-right"]}var Rt={},ze={},Li;function Dn(){if(Li)return ze;Li=1,ze.byteLength=l,ze.toByteArray=p,ze.fromByteArray=y;for(var t=[],e=[],i=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=n.length;a<s;++a)t[a]=n[a],e[n.charCodeAt(a)]=a;e[45]=62,e[95]=63;function d(E){var S=E.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var T=E.indexOf("=");T===-1&&(T=S);var I=T===S?0:4-T%4;return[T,I]}function l(E){var S=d(E),T=S[0],I=S[1];return(T+I)*3/4-I}function m(E,S,T){return(S+T)*3/4-T}function p(E){var S,T=d(E),I=T[0],w=T[1],b=new i(m(E,I,w)),O=0,k=w>0?I-4:I,R;for(R=0;R<k;R+=4)S=e[E.charCodeAt(R)]<<18|e[E.charCodeAt(R+1)]<<12|e[E.charCodeAt(R+2)]<<6|e[E.charCodeAt(R+3)],b[O++]=S>>16&255,b[O++]=S>>8&255,b[O++]=S&255;return w===2&&(S=e[E.charCodeAt(R)]<<2|e[E.charCodeAt(R+1)]>>4,b[O++]=S&255),w===1&&(S=e[E.charCodeAt(R)]<<10|e[E.charCodeAt(R+1)]<<4|e[E.charCodeAt(R+2)]>>2,b[O++]=S>>8&255,b[O++]=S&255),b}function f(E){return t[E>>18&63]+t[E>>12&63]+t[E>>6&63]+t[E&63]}function u(E,S,T){for(var I,w=[],b=S;b<T;b+=3)I=(E[b]<<16&16711680)+(E[b+1]<<8&65280)+(E[b+2]&255),w.push(f(I));return w.join("")}function y(E){for(var S,T=E.length,I=T%3,w=[],b=16383,O=0,k=T-I;O<k;O+=b)w.push(u(E,O,O+b>k?k:O+b));return I===1?(S=E[T-1],w.push(t[S>>2]+t[S<<4&63]+"==")):I===2&&(S=(E[T-2]<<8)+E[T-1],w.push(t[S>>10]+t[S>>4&63]+t[S<<2&63]+"=")),w.join("")}return ze}var at={};var Di;function Un(){return Di||(Di=1,at.read=function(t,e,i,n,a){var s,d,l=a*8-n-1,m=(1<<l)-1,p=m>>1,f=-7,u=i?a-1:0,y=i?-1:1,E=t[e+u];for(u+=y,s=E&(1<<-f)-1,E>>=-f,f+=l;f>0;s=s*256+t[e+u],u+=y,f-=8);for(d=s&(1<<-f)-1,s>>=-f,f+=n;f>0;d=d*256+t[e+u],u+=y,f-=8);if(s===0)s=1-p;else{if(s===m)return d?NaN:(E?-1:1)*(1/0);d=d+Math.pow(2,n),s=s-p}return(E?-1:1)*d*Math.pow(2,s-n)},at.write=function(t,e,i,n,a,s){var d,l,m,p=s*8-a-1,f=(1<<p)-1,u=f>>1,y=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,E=n?0:s-1,S=n?1:-1,T=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,d=f):(d=Math.floor(Math.log(e)/Math.LN2),e*(m=Math.pow(2,-d))<1&&(d--,m*=2),d+u>=1?e+=y/m:e+=y*Math.pow(2,1-u),e*m>=2&&(d++,m/=2),d+u>=f?(l=0,d=f):d+u>=1?(l=(e*m-1)*Math.pow(2,a),d=d+u):(l=e*Math.pow(2,u-1)*Math.pow(2,a),d=0));a>=8;t[i+E]=l&255,E+=S,l/=256,a-=8);for(d=d<<a|l,p+=a;p>0;t[i+E]=d&255,E+=S,d/=256,p-=8);t[i+E-S]|=T*128}),at}var Ui;function Pn(){return Ui||(Ui=1,(function(t){const e=Dn(),i=Un(),n=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 a=2147483647;t.kMaxLength=a,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 c=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(c,r),c.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 d(c){if(c>a)throw new RangeError('The value "'+c+'" is invalid for option "size"');const r=new Uint8Array(c);return Object.setPrototypeOf(r,l.prototype),r}function l(c,r,o){if(typeof c=="number"){if(typeof r=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(c)}return m(c,r,o)}l.poolSize=8192;function m(c,r,o){if(typeof c=="string")return y(c,r);if(ArrayBuffer.isView(c))return S(c);if(c==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof c);if(ce(c,ArrayBuffer)||c&&ce(c.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ce(c,SharedArrayBuffer)||c&&ce(c.buffer,SharedArrayBuffer)))return T(c,r,o);if(typeof c=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=c.valueOf&&c.valueOf();if(h!=null&&h!==c)return l.from(h,r,o);const _=I(c);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof c[Symbol.toPrimitive]=="function")return l.from(c[Symbol.toPrimitive]("string"),r,o);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof c)}l.from=function(c,r,o){return m(c,r,o)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(c){if(typeof c!="number")throw new TypeError('"size" argument must be of type number');if(c<0)throw new RangeError('The value "'+c+'" is invalid for option "size"')}function f(c,r,o){return p(c),c<=0?d(c):r!==void 0?typeof o=="string"?d(c).fill(r,o):d(c).fill(r):d(c)}l.alloc=function(c,r,o){return f(c,r,o)};function u(c){return p(c),d(c<0?0:w(c)|0)}l.allocUnsafe=function(c){return u(c)},l.allocUnsafeSlow=function(c){return u(c)};function y(c,r){if((typeof r!="string"||r==="")&&(r="utf8"),!l.isEncoding(r))throw new TypeError("Unknown encoding: "+r);const o=O(c,r)|0;let h=d(o);const _=h.write(c,r);return _!==o&&(h=h.slice(0,_)),h}function E(c){const r=c.length<0?0:w(c.length)|0,o=d(r);for(let h=0;h<r;h+=1)o[h]=c[h]&255;return o}function S(c){if(ce(c,Uint8Array)){const r=new Uint8Array(c);return T(r.buffer,r.byteOffset,r.byteLength)}return E(c)}function T(c,r,o){if(r<0||c.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(c.byteLength<r+(o||0))throw new RangeError('"length" is outside of buffer bounds');let h;return r===void 0&&o===void 0?h=new Uint8Array(c):o===void 0?h=new Uint8Array(c,r):h=new Uint8Array(c,r,o),Object.setPrototypeOf(h,l.prototype),h}function I(c){if(l.isBuffer(c)){const r=w(c.length)|0,o=d(r);return o.length===0||c.copy(o,0,0,r),o}if(c.length!==void 0)return typeof c.length!="number"||Wt(c.length)?d(0):E(c);if(c.type==="Buffer"&&Array.isArray(c.data))return E(c.data)}function w(c){if(c>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return c|0}function b(c){return+c!=c&&(c=0),l.alloc(+c)}l.isBuffer=function(r){return r!=null&&r._isBuffer===!0&&r!==l.prototype},l.compare=function(r,o){if(ce(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),ce(o,Uint8Array)&&(o=l.from(o,o.offset,o.byteLength)),!l.isBuffer(r)||!l.isBuffer(o))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(r===o)return 0;let h=r.length,_=o.length;for(let g=0,v=Math.min(h,_);g<v;++g)if(r[g]!==o[g]){h=r[g],_=o[g];break}return h<_?-1:_<h?1:0},l.isEncoding=function(r){switch(String(r).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(r,o){if(!Array.isArray(r))throw new TypeError('"list" argument must be an Array of Buffers');if(r.length===0)return l.alloc(0);let h;if(o===void 0)for(o=0,h=0;h<r.length;++h)o+=r[h].length;const _=l.allocUnsafe(o);let g=0;for(h=0;h<r.length;++h){let v=r[h];if(ce(v,Uint8Array))g+v.length>_.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(_,g)):Uint8Array.prototype.set.call(_,v,g);else if(l.isBuffer(v))v.copy(_,g);else throw new TypeError('"list" argument must be an Array of Buffers');g+=v.length}return _};function O(c,r){if(l.isBuffer(c))return c.length;if(ArrayBuffer.isView(c)||ce(c,ArrayBuffer))return c.byteLength;if(typeof c!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof c);const o=c.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&o===0)return 0;let _=!1;for(;;)switch(r){case"ascii":case"latin1":case"binary":return o;case"utf8":case"utf-8":return Vt(c).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return o*2;case"hex":return o>>>1;case"base64":return cn(c).length;default:if(_)return h?-1:Vt(c).length;r=(""+r).toLowerCase(),_=!0}}l.byteLength=O;function k(c,r,o){let h=!1;if((r===void 0||r<0)&&(r=0),r>this.length||((o===void 0||o>this.length)&&(o=this.length),o<=0)||(o>>>=0,r>>>=0,o<=r))return"";for(c||(c="utf8");;)switch(c){case"hex":return j(this,r,o);case"utf8":case"utf-8":return be(this,r,o);case"ascii":return ne(this,r,o);case"latin1":case"binary":return dt(this,r,o);case"base64":return Ie(this,r,o);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return en(this,r,o);default:if(h)throw new TypeError("Unknown encoding: "+c);c=(c+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function R(c,r,o){const h=c[r];c[r]=c[o],c[o]=h}l.prototype.swap16=function(){const r=this.length;if(r%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;o<r;o+=2)R(this,o,o+1);return this},l.prototype.swap32=function(){const r=this.length;if(r%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let o=0;o<r;o+=4)R(this,o,o+3),R(this,o+1,o+2);return this},l.prototype.swap64=function(){const r=this.length;if(r%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let o=0;o<r;o+=8)R(this,o,o+7),R(this,o+1,o+6),R(this,o+2,o+5),R(this,o+3,o+4);return this},l.prototype.toString=function(){const r=this.length;return r===0?"":arguments.length===0?be(this,0,r):k.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(r){if(!l.isBuffer(r))throw new TypeError("Argument must be a Buffer");return this===r?!0:l.compare(this,r)===0},l.prototype.inspect=function(){let r="";const o=t.INSPECT_MAX_BYTES;return r=this.toString("hex",0,o).replace(/(.{2})/g,"$1 ").trim(),this.length>o&&(r+=" ... "),"<Buffer "+r+">"},n&&(l.prototype[n]=l.prototype.inspect),l.prototype.compare=function(r,o,h,_,g){if(ce(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(r))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof r);if(o===void 0&&(o=0),h===void 0&&(h=r?r.length:0),_===void 0&&(_=0),g===void 0&&(g=this.length),o<0||h>r.length||_<0||g>this.length)throw new RangeError("out of range index");if(_>=g&&o>=h)return 0;if(_>=g)return-1;if(o>=h)return 1;if(o>>>=0,h>>>=0,_>>>=0,g>>>=0,this===r)return 0;let v=g-_,x=h-o;const P=Math.min(v,x),D=this.slice(_,g),B=r.slice(o,h);for(let L=0;L<P;++L)if(D[L]!==B[L]){v=D[L],x=B[L];break}return v<x?-1:x<v?1:0};function ee(c,r,o,h,_){if(c.length===0)return-1;if(typeof o=="string"?(h=o,o=0):o>2147483647?o=2147483647:o<-2147483648&&(o=-2147483648),o=+o,Wt(o)&&(o=_?0:c.length-1),o<0&&(o=c.length+o),o>=c.length){if(_)return-1;o=c.length-1}else if(o<0)if(_)o=0;else return-1;if(typeof r=="string"&&(r=l.from(r,h)),l.isBuffer(r))return r.length===0?-1:G(c,r,o,h,_);if(typeof r=="number")return r=r&255,typeof Uint8Array.prototype.indexOf=="function"?_?Uint8Array.prototype.indexOf.call(c,r,o):Uint8Array.prototype.lastIndexOf.call(c,r,o):G(c,[r],o,h,_);throw new TypeError("val must be string, number or Buffer")}function G(c,r,o,h,_){let g=1,v=c.length,x=r.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(c.length<2||r.length<2)return-1;g=2,v/=2,x/=2,o/=2}function P(B,L){return g===1?B[L]:B.readUInt16BE(L*g)}let D;if(_){let B=-1;for(D=o;D<v;D++)if(P(c,D)===P(r,B===-1?0:D-B)){if(B===-1&&(B=D),D-B+1===x)return B*g}else B!==-1&&(D-=D-B),B=-1}else for(o+x>v&&(o=v-x),D=o;D>=0;D--){let B=!0;for(let L=0;L<x;L++)if(P(c,D+L)!==P(r,L)){B=!1;break}if(B)return D}return-1}l.prototype.includes=function(r,o,h){return this.indexOf(r,o,h)!==-1},l.prototype.indexOf=function(r,o,h){return ee(this,r,o,h,!0)},l.prototype.lastIndexOf=function(r,o,h){return ee(this,r,o,h,!1)};function oe(c,r,o,h){o=Number(o)||0;const _=c.length-o;h?(h=Number(h),h>_&&(h=_)):h=_;const g=r.length;h>g/2&&(h=g/2);let v;for(v=0;v<h;++v){const x=parseInt(r.substr(v*2,2),16);if(Wt(x))return v;c[o+v]=x}return v}function te(c,r,o,h){return ut(Vt(r,c.length-o),c,o,h)}function se(c,r,o,h){return ut(io(r),c,o,h)}function W(c,r,o,h){return ut(cn(r),c,o,h)}function Q(c,r,o,h){return ut(no(r,c.length-o),c,o,h)}l.prototype.write=function(r,o,h,_){if(o===void 0)_="utf8",h=this.length,o=0;else if(h===void 0&&typeof o=="string")_=o,h=this.length,o=0;else if(isFinite(o))o=o>>>0,isFinite(h)?(h=h>>>0,_===void 0&&(_="utf8")):(_=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const g=this.length-o;if((h===void 0||h>g)&&(h=g),r.length>0&&(h<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let v=!1;for(;;)switch(_){case"hex":return oe(this,r,o,h);case"utf8":case"utf-8":return te(this,r,o,h);case"ascii":case"latin1":case"binary":return se(this,r,o,h);case"base64":return W(this,r,o,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Q(this,r,o,h);default:if(v)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ie(c,r,o){return r===0&&o===c.length?e.fromByteArray(c):e.fromByteArray(c.slice(r,o))}function be(c,r,o){o=Math.min(c.length,o);const h=[];let _=r;for(;_<o;){const g=c[_];let v=null,x=g>239?4:g>223?3:g>191?2:1;if(_+x<=o){let P,D,B,L;switch(x){case 1:g<128&&(v=g);break;case 2:P=c[_+1],(P&192)===128&&(L=(g&31)<<6|P&63,L>127&&(v=L));break;case 3:P=c[_+1],D=c[_+2],(P&192)===128&&(D&192)===128&&(L=(g&15)<<12|(P&63)<<6|D&63,L>2047&&(L<55296||L>57343)&&(v=L));break;case 4:P=c[_+1],D=c[_+2],B=c[_+3],(P&192)===128&&(D&192)===128&&(B&192)===128&&(L=(g&15)<<18|(P&63)<<12|(D&63)<<6|B&63,L>65535&&L<1114112&&(v=L))}}v===null?(v=65533,x=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),_+=x}return Ke(h)}const Ce=4096;function Ke(c){const r=c.length;if(r<=Ce)return String.fromCharCode.apply(String,c);let o="",h=0;for(;h<r;)o+=String.fromCharCode.apply(String,c.slice(h,h+=Ce));return o}function ne(c,r,o){let h="";o=Math.min(c.length,o);for(let _=r;_<o;++_)h+=String.fromCharCode(c[_]&127);return h}function dt(c,r,o){let h="";o=Math.min(c.length,o);for(let _=r;_<o;++_)h+=String.fromCharCode(c[_]);return h}function j(c,r,o){const h=c.length;(!r||r<0)&&(r=0),(!o||o<0||o>h)&&(o=h);let _="";for(let g=r;g<o;++g)_+=ro[c[g]];return _}function en(c,r,o){const h=c.slice(r,o);let _="";for(let g=0;g<h.length-1;g+=2)_+=String.fromCharCode(h[g]+h[g+1]*256);return _}l.prototype.slice=function(r,o){const h=this.length;r=~~r,o=o===void 0?h:~~o,r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),o<0?(o+=h,o<0&&(o=0)):o>h&&(o=h),o<r&&(o=r);const _=this.subarray(r,o);return Object.setPrototypeOf(_,l.prototype),_};function H(c,r,o){if(c%1!==0||c<0)throw new RangeError("offset is not uint");if(c+r>o)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(r,o,h){r=r>>>0,o=o>>>0,h||H(r,o,this.length);let _=this[r],g=1,v=0;for(;++v<o&&(g*=256);)_+=this[r+v]*g;return _},l.prototype.readUintBE=l.prototype.readUIntBE=function(r,o,h){r=r>>>0,o=o>>>0,h||H(r,o,this.length);let _=this[r+--o],g=1;for(;o>0&&(g*=256);)_+=this[r+--o]*g;return _},l.prototype.readUint8=l.prototype.readUInt8=function(r,o){return r=r>>>0,o||H(r,1,this.length),this[r]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(r,o){return r=r>>>0,o||H(r,2,this.length),this[r]|this[r+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(r,o){return r=r>>>0,o||H(r,2,this.length),this[r]<<8|this[r+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(r,o){return r=r>>>0,o||H(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+this[r+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(r,o){return r=r>>>0,o||H(r,4,this.length),this[r]*16777216+(this[r+1]<<16|this[r+2]<<8|this[r+3])},l.prototype.readBigUInt64LE=Se(function(r){r=r>>>0,Pe(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=o+this[++r]*2**8+this[++r]*2**16+this[++r]*2**24,g=this[++r]+this[++r]*2**8+this[++r]*2**16+h*2**24;return BigInt(_)+(BigInt(g)<<BigInt(32))}),l.prototype.readBigUInt64BE=Se(function(r){r=r>>>0,Pe(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=o*2**24+this[++r]*2**16+this[++r]*2**8+this[++r],g=this[++r]*2**24+this[++r]*2**16+this[++r]*2**8+h;return(BigInt(_)<<BigInt(32))+BigInt(g)}),l.prototype.readIntLE=function(r,o,h){r=r>>>0,o=o>>>0,h||H(r,o,this.length);let _=this[r],g=1,v=0;for(;++v<o&&(g*=256);)_+=this[r+v]*g;return g*=128,_>=g&&(_-=Math.pow(2,8*o)),_},l.prototype.readIntBE=function(r,o,h){r=r>>>0,o=o>>>0,h||H(r,o,this.length);let _=o,g=1,v=this[r+--_];for(;_>0&&(g*=256);)v+=this[r+--_]*g;return g*=128,v>=g&&(v-=Math.pow(2,8*o)),v},l.prototype.readInt8=function(r,o){return r=r>>>0,o||H(r,1,this.length),this[r]&128?(255-this[r]+1)*-1:this[r]},l.prototype.readInt16LE=function(r,o){r=r>>>0,o||H(r,2,this.length);const h=this[r]|this[r+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(r,o){r=r>>>0,o||H(r,2,this.length);const h=this[r+1]|this[r]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(r,o){return r=r>>>0,o||H(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},l.prototype.readInt32BE=function(r,o){return r=r>>>0,o||H(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},l.prototype.readBigInt64LE=Se(function(r){r=r>>>0,Pe(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=this[r+4]+this[r+5]*2**8+this[r+6]*2**16+(h<<24);return(BigInt(_)<<BigInt(32))+BigInt(o+this[++r]*2**8+this[++r]*2**16+this[++r]*2**24)}),l.prototype.readBigInt64BE=Se(function(r){r=r>>>0,Pe(r,"offset");const o=this[r],h=this[r+7];(o===void 0||h===void 0)&&Je(r,this.length-8);const _=(o<<24)+this[++r]*2**16+this[++r]*2**8+this[++r];return(BigInt(_)<<BigInt(32))+BigInt(this[++r]*2**24+this[++r]*2**16+this[++r]*2**8+h)}),l.prototype.readFloatLE=function(r,o){return r=r>>>0,o||H(r,4,this.length),i.read(this,r,!0,23,4)},l.prototype.readFloatBE=function(r,o){return r=r>>>0,o||H(r,4,this.length),i.read(this,r,!1,23,4)},l.prototype.readDoubleLE=function(r,o){return r=r>>>0,o||H(r,8,this.length),i.read(this,r,!0,52,8)},l.prototype.readDoubleBE=function(r,o){return r=r>>>0,o||H(r,8,this.length),i.read(this,r,!1,52,8)};function ie(c,r,o,h,_,g){if(!l.isBuffer(c))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>_||r<g)throw new RangeError('"value" argument is out of bounds');if(o+h>c.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(r,o,h,_){if(r=+r,o=o>>>0,h=h>>>0,!_){const x=Math.pow(2,8*h)-1;ie(this,r,o,h,x,0)}let g=1,v=0;for(this[o]=r&255;++v<h&&(g*=256);)this[o+v]=r/g&255;return o+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(r,o,h,_){if(r=+r,o=o>>>0,h=h>>>0,!_){const x=Math.pow(2,8*h)-1;ie(this,r,o,h,x,0)}let g=h-1,v=1;for(this[o+g]=r&255;--g>=0&&(v*=256);)this[o+g]=r/v&255;return o+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,1,255,0),this[o]=r&255,o+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,65535,0),this[o]=r&255,this[o+1]=r>>>8,o+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,65535,0),this[o]=r>>>8,this[o+1]=r&255,o+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,4294967295,0),this[o+3]=r>>>24,this[o+2]=r>>>16,this[o+1]=r>>>8,this[o]=r&255,o+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,4294967295,0),this[o]=r>>>24,this[o+1]=r>>>16,this[o+2]=r>>>8,this[o+3]=r&255,o+4};function tn(c,r,o,h,_){ln(r,h,_,c,o,7);let g=Number(r&BigInt(4294967295));c[o++]=g,g=g>>8,c[o++]=g,g=g>>8,c[o++]=g,g=g>>8,c[o++]=g;let v=Number(r>>BigInt(32)&BigInt(4294967295));return c[o++]=v,v=v>>8,c[o++]=v,v=v>>8,c[o++]=v,v=v>>8,c[o++]=v,o}function nn(c,r,o,h,_){ln(r,h,_,c,o,7);let g=Number(r&BigInt(4294967295));c[o+7]=g,g=g>>8,c[o+6]=g,g=g>>8,c[o+5]=g,g=g>>8,c[o+4]=g;let v=Number(r>>BigInt(32)&BigInt(4294967295));return c[o+3]=v,v=v>>8,c[o+2]=v,v=v>>8,c[o+1]=v,v=v>>8,c[o]=v,o+8}l.prototype.writeBigUInt64LE=Se(function(r,o=0){return tn(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Se(function(r,o=0){return nn(this,r,o,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(r,o,h,_){if(r=+r,o=o>>>0,!_){const P=Math.pow(2,8*h-1);ie(this,r,o,h,P-1,-P)}let g=0,v=1,x=0;for(this[o]=r&255;++g<h&&(v*=256);)r<0&&x===0&&this[o+g-1]!==0&&(x=1),this[o+g]=(r/v>>0)-x&255;return o+h},l.prototype.writeIntBE=function(r,o,h,_){if(r=+r,o=o>>>0,!_){const P=Math.pow(2,8*h-1);ie(this,r,o,h,P-1,-P)}let g=h-1,v=1,x=0;for(this[o+g]=r&255;--g>=0&&(v*=256);)r<0&&x===0&&this[o+g+1]!==0&&(x=1),this[o+g]=(r/v>>0)-x&255;return o+h},l.prototype.writeInt8=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,1,127,-128),r<0&&(r=255+r+1),this[o]=r&255,o+1},l.prototype.writeInt16LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,32767,-32768),this[o]=r&255,this[o+1]=r>>>8,o+2},l.prototype.writeInt16BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,2,32767,-32768),this[o]=r>>>8,this[o+1]=r&255,o+2},l.prototype.writeInt32LE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,2147483647,-2147483648),this[o]=r&255,this[o+1]=r>>>8,this[o+2]=r>>>16,this[o+3]=r>>>24,o+4},l.prototype.writeInt32BE=function(r,o,h){return r=+r,o=o>>>0,h||ie(this,r,o,4,2147483647,-2147483648),r<0&&(r=4294967295+r+1),this[o]=r>>>24,this[o+1]=r>>>16,this[o+2]=r>>>8,this[o+3]=r&255,o+4},l.prototype.writeBigInt64LE=Se(function(r,o=0){return tn(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Se(function(r,o=0){return nn(this,r,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function rn(c,r,o,h,_,g){if(o+h>c.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("Index out of range")}function on(c,r,o,h,_){return r=+r,o=o>>>0,_||rn(c,r,o,4),i.write(c,r,o,h,23,4),o+4}l.prototype.writeFloatLE=function(r,o,h){return on(this,r,o,!0,h)},l.prototype.writeFloatBE=function(r,o,h){return on(this,r,o,!1,h)};function sn(c,r,o,h,_){return r=+r,o=o>>>0,_||rn(c,r,o,8),i.write(c,r,o,h,52,8),o+8}l.prototype.writeDoubleLE=function(r,o,h){return sn(this,r,o,!0,h)},l.prototype.writeDoubleBE=function(r,o,h){return sn(this,r,o,!1,h)},l.prototype.copy=function(r,o,h,_){if(!l.isBuffer(r))throw new TypeError("argument should be a Buffer");if(h||(h=0),!_&&_!==0&&(_=this.length),o>=r.length&&(o=r.length),o||(o=0),_>0&&_<h&&(_=h),_===h||r.length===0||this.length===0)return 0;if(o<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),r.length-o<_-h&&(_=r.length-o+h);const g=_-h;return this===r&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(o,h,_):Uint8Array.prototype.set.call(r,this.subarray(h,_),o),g},l.prototype.fill=function(r,o,h,_){if(typeof r=="string"){if(typeof o=="string"?(_=o,o=0,h=this.length):typeof h=="string"&&(_=h,h=this.length),_!==void 0&&typeof _!="string")throw new TypeError("encoding must be a string");if(typeof _=="string"&&!l.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(r.length===1){const v=r.charCodeAt(0);(_==="utf8"&&v<128||_==="latin1")&&(r=v)}}else typeof r=="number"?r=r&255:typeof r=="boolean"&&(r=Number(r));if(o<0||this.length<o||this.length<h)throw new RangeError("Out of range index");if(h<=o)return this;o=o>>>0,h=h===void 0?this.length:h>>>0,r||(r=0);let g;if(typeof r=="number")for(g=o;g<h;++g)this[g]=r;else{const v=l.isBuffer(r)?r:l.from(r,_),x=v.length;if(x===0)throw new TypeError('The value "'+r+'" is invalid for argument "value"');for(g=0;g<h-o;++g)this[g+o]=v[g%x]}return this};const Ue={};function $t(c,r,o){Ue[c]=class extends o{constructor(){super(),Object.defineProperty(this,"message",{value:r.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${c}]`,this.stack,delete this.name}get code(){return c}set code(_){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:_,writable:!0})}toString(){return`${this.name} [${c}]: ${this.message}`}}}$t("ERR_BUFFER_OUT_OF_BOUNDS",function(c){return c?`${c} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$t("ERR_INVALID_ARG_TYPE",function(c,r){return`The "${c}" argument must be of type number. Received type ${typeof r}`},TypeError),$t("ERR_OUT_OF_RANGE",function(c,r,o){let h=`The value of "${c}" is out of range.`,_=o;return Number.isInteger(o)&&Math.abs(o)>2**32?_=an(String(o)):typeof o=="bigint"&&(_=String(o),(o>BigInt(2)**BigInt(32)||o<-(BigInt(2)**BigInt(32)))&&(_=an(_)),_+="n"),h+=` It must be ${r}. Received ${_}`,h},RangeError);function an(c){let r="",o=c.length;const h=c[0]==="-"?1:0;for(;o>=h+4;o-=3)r=`_${c.slice(o-3,o)}${r}`;return`${c.slice(0,o)}${r}`}function Qr(c,r,o){Pe(r,"offset"),(c[r]===void 0||c[r+o]===void 0)&&Je(r,c.length-(o+1))}function ln(c,r,o,h,_,g){if(c>o||c<r){const v=typeof r=="bigint"?"n":"";let x;throw r===0||r===BigInt(0)?x=`>= 0${v} and < 2${v} ** ${(g+1)*8}${v}`:x=`>= -(2${v} ** ${(g+1)*8-1}${v}) and < 2 ** ${(g+1)*8-1}${v}`,new Ue.ERR_OUT_OF_RANGE("value",x,c)}Qr(h,_,g)}function Pe(c,r){if(typeof c!="number")throw new Ue.ERR_INVALID_ARG_TYPE(r,"number",c)}function Je(c,r,o){throw Math.floor(c)!==c?(Pe(c,o),new Ue.ERR_OUT_OF_RANGE("offset","an integer",c)):r<0?new Ue.ERR_BUFFER_OUT_OF_BOUNDS:new Ue.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${r}`,c)}const eo=/[^+/0-9A-Za-z-_]/g;function to(c){if(c=c.split("=")[0],c=c.trim().replace(eo,""),c.length<2)return"";for(;c.length%4!==0;)c=c+"=";return c}function Vt(c,r){r=r||1/0;let o;const h=c.length;let _=null;const g=[];for(let v=0;v<h;++v){if(o=c.charCodeAt(v),o>55295&&o<57344){if(!_){if(o>56319){(r-=3)>-1&&g.push(239,191,189);continue}else if(v+1===h){(r-=3)>-1&&g.push(239,191,189);continue}_=o;continue}if(o<56320){(r-=3)>-1&&g.push(239,191,189),_=o;continue}o=(_-55296<<10|o-56320)+65536}else _&&(r-=3)>-1&&g.push(239,191,189);if(_=null,o<128){if((r-=1)<0)break;g.push(o)}else if(o<2048){if((r-=2)<0)break;g.push(o>>6|192,o&63|128)}else if(o<65536){if((r-=3)<0)break;g.push(o>>12|224,o>>6&63|128,o&63|128)}else if(o<1114112){if((r-=4)<0)break;g.push(o>>18|240,o>>12&63|128,o>>6&63|128,o&63|128)}else throw new Error("Invalid code point")}return g}function io(c){const r=[];for(let o=0;o<c.length;++o)r.push(c.charCodeAt(o)&255);return r}function no(c,r){let o,h,_;const g=[];for(let v=0;v<c.length&&!((r-=2)<0);++v)o=c.charCodeAt(v),h=o>>8,_=o%256,g.push(_),g.push(h);return g}function cn(c){return e.toByteArray(to(c))}function ut(c,r,o,h){let _;for(_=0;_<h&&!(_+o>=r.length||_>=c.length);++_)r[_+o]=c[_];return _}function ce(c,r){return c instanceof r||c!=null&&c.constructor!=null&&c.constructor.name!=null&&c.constructor.name===r.name}function Wt(c){return c!==c}const ro=(function(){const c="0123456789abcdef",r=new Array(256);for(let o=0;o<16;++o){const h=o*16;for(let _=0;_<16;++_)r[h+_]=c[o]+c[_]}return r})();function Se(c){return typeof BigInt>"u"?oo:c}function oo(){throw new Error("BigInt not supported")}})(Rt)),Rt}var Bn=Pn();const Fn="https://api.anam.ai",$n="/v1",Pi={client:"js-sdk",version:"4.20.0"},Vn=3,Wn=250,jn=2e3,Gn=1e4;var Bi=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const Fi="https://api.anam.ai",At="/v1";var le;(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_CONNECTION_MILESTONE="client_connection_milestone",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES="client_connection_milestones",t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success",t.CLIENT_METRIC_MEASUREMENT_ICE_RESTART="client_ice_restart"})(le||(le={}));const $i=50;let Ot=Fi,Vi=At,pe,Wi=!1;const Hn=(t,e=At)=>{Ot=t,Vi=e},zn=t=>{pe=t},qn=t=>{Wi=t};let _e={sessionId:null,organizationId:null,attemptCorrelationId:null};const qe=t=>{_e=Object.assign(Object.assign({},_e),t)},ke=(t,e,i)=>Bi(void 0,void 0,void 0,function*(){yield ji([{name:t,value:e,tags:i}])}),ji=t=>Bi(void 0,void 0,void 0,function*(){if(!(Wi||t.length===0))try{const e=`${Vi}/metrics/client`;let i;const n={"Content-Type":"application/json"};pe?.enabled&&pe?.baseUrl?(i=`${pe.baseUrl}${e}`,n["X-Anam-Target-Url"]=`${Ot}${e}`):i=`${Ot}${e}`;const a=t.map(s=>{var d;return Object.assign(Object.assign({},s),{clientTimestamp:(d=s.clientTimestamp)!==null&&d!==void 0?d:new Date().toISOString(),tags:Yn(s.tags)})});for(let s=0;s<a.length;s+=$i){const d=a.slice(s,s+$i),l=d.length===1?d[0]:{metrics:d};yield fetch(i,{method:"POST",headers:n,body:JSON.stringify(l)})}}catch(e){console.error("Failed to send client metric:",e)}}),Yn=t=>{const e=Object.assign(Object.assign({},Pi),t);return _e.sessionId&&e.sessionId===void 0&&(e.sessionId=_e.sessionId),_e.organizationId&&e.organizationId===void 0&&(e.organizationId=_e.organizationId),_e.attemptCorrelationId&&e.attemptCorrelationId===void 0&&(e.attemptCorrelationId=_e.attemptCorrelationId),e},Kn=(t,e="console")=>{var i,n,a;const s={};t.forEach(u=>{s[u.type]||(s[u.type]=[]),s[u.type].push(u)});const d={issues:[]},l=((i=s["inbound-rtp"])===null||i===void 0?void 0:i.filter(u=>u.kind==="video"))||[];l.length>0&&(d.personaVideoStream=[],l.forEach(u=>{var y,E,S,T,I;const w={framesReceived:(y=u.framesReceived)!==null&&y!==void 0?y:"unknown",framesDropped:(E=u.framesDropped)!==null&&E!==void 0?E:"unknown",framesPerSecond:(S=u.framesPerSecond)!==null&&S!==void 0?S:"unknown",packetsReceived:(T=u.packetsReceived)!==null&&T!==void 0?T:"unknown",packetsLost:(I=u.packetsLost)!==null&&I!==void 0?I:"unknown",resolution:u.frameWidth&&u.frameHeight?`${u.frameWidth}x${u.frameHeight}`:void 0,jitter:u.jitter!==void 0?u.jitter:void 0};d.personaVideoStream.push(w)}));const m=((n=s["inbound-rtp"])===null||n===void 0?void 0:n.filter(u=>u.kind==="audio"))||[];m.length>0&&(d.personaAudioStream=[],m.forEach(u=>{var y,E,S;const T={packetsReceived:(y=u.packetsReceived)!==null&&y!==void 0?y:"unknown",packetsLost:(E=u.packetsLost)!==null&&E!==void 0?E:"unknown",audioLevel:(S=u.audioLevel)!==null&&S!==void 0?S:"unknown",jitter:u.jitter!==void 0?u.jitter:void 0,totalAudioEnergy:u.totalAudioEnergy!==void 0?u.totalAudioEnergy:void 0};d.personaAudioStream.push(T)}));const p=((a=s["outbound-rtp"])===null||a===void 0?void 0:a.filter(u=>u.kind==="audio"))||[];p.length>0&&(d.userAudioInput=[],p.forEach(u=>{var y,E;const S={packetsSent:(y=u.packetsSent)!==null&&y!==void 0?y:"unknown",retransmittedPackets:(E=u.retransmittedPacketsSent)!==null&&E!==void 0?E:void 0,avgPacketSendDelay:u.totalPacketSendDelay!==void 0?u.totalPacketSendDelay/(u.packetsSent||1)*1e3:void 0};d.userAudioInput.push(S)})),s.codec&&(d.codecs=[],s.codec.forEach(u=>{const y={status:u.payloadType?"Active":"Available",mimeType:u.mimeType||"Unknown",payloadType:u.payloadType||"N/A",clockRate:u.clockRate||void 0,channels:u.channels||void 0};d.codecs.push(y)})),s.transport&&(d.transportLayer=[],s.transport.forEach(u=>{const y={dtlsState:u.dtlsState||"unknown",iceState:u.iceState||"unknown",bytesSent:u.bytesSent||void 0,bytesReceived:u.bytesReceived||void 0};d.transportLayer.push(y)}));const f=[];if(l.forEach(u=>{typeof u.framesDropped=="number"&&u.framesDropped>0&&f.push(`Video: ${u.framesDropped} frames dropped`),typeof u.packetsLost=="number"&&u.packetsLost>0&&f.push(`Video: ${u.packetsLost} packets lost`),typeof u.framesPerSecond=="number"&&u.framesPerSecond<23&&f.push(`Video: Low frame rate (${u.framesPerSecond} fps)`)}),m.forEach(u=>{typeof u.packetsLost=="number"&&u.packetsLost>0&&f.push(`Audio: ${u.packetsLost} packets lost`),typeof u.jitter=="number"&&u.jitter>.1&&f.push(`Audio: High jitter (${(u.jitter*1e3).toFixed(1)}ms)`)}),d.issues=f,e==="json")return d;console.group("📊 WebRTC Session Statistics Report"),d.personaVideoStream&&d.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),d.personaVideoStream.forEach(u=>{console.log(`Frames Received: ${u.framesReceived}`),console.log(`Frames Dropped: ${u.framesDropped}`),console.log(`Frames Per Second: ${u.framesPerSecond}`),console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),u.resolution&&console.log(`Resolution: ${u.resolution}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`)}),console.groupEnd()),d.personaAudioStream&&d.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),d.personaAudioStream.forEach(u=>{console.log(`Packets Received: ${typeof u.packetsReceived=="number"?u.packetsReceived.toLocaleString():u.packetsReceived}`),console.log(`Packets Lost: ${u.packetsLost}`),console.log(`Audio Level: ${u.audioLevel}`),u.jitter!==void 0&&console.log(`Jitter: ${u.jitter.toFixed(5)}ms`),u.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${u.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),d.userAudioInput&&d.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),d.userAudioInput.forEach(u=>{console.log(`Packets Sent: ${typeof u.packetsSent=="number"?u.packetsSent.toLocaleString():u.packetsSent}`),u.retransmittedPackets&&console.log(`Retransmitted Packets: ${u.retransmittedPackets}`),u.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${u.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),d.codecs&&d.codecs.length>0&&(console.group("🔧 Codecs Used"),d.codecs.forEach(u=>{console.log(`${u.status} ${u.mimeType} - Payload Type: ${u.payloadType}`),u.clockRate&&console.log(` Clock Rate: ${u.clockRate}Hz`),u.channels&&console.log(` Channels: ${u.channels}`)}),console.groupEnd()),d.transportLayer&&d.transportLayer.length>0&&(console.group("🚚 Transport Layer"),d.transportLayer.forEach(u=>{console.log(`DTLS State: ${u.dtlsState}`),console.log(`ICE State: ${u.iceState}`),(u.bytesReceived||u.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(u.bytesSent||0).toLocaleString()}, Received: ${(u.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),d.issues.length>0?(console.group("⚠️ Potential Issues Detected"),d.issues.forEach(u=>console.warn(u)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var Y;(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"})(Y||(Y={}));class $ extends Error{constructor(e,i,n=500,a){super(e),this.name="ClientError",this.code=i,this.statusCode=n,this.details=a,Object.setPrototypeOf(this,$.prototype),ke(le.CLIENT_METRIC_MEASUREMENT_ERROR,i,{details:a,statusCode:n})}}function Jn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}const Gi=0,Xn=5e3;class Zn{constructor(e={}){var i,n,a,s;this.milestones=[],this.context={sessionId:null,organizationId:null,attemptCorrelationId:null},this.published=!1,this.sessionSuccessful=!1,this.now=(i=e.now)!==null&&i!==void 0?i:Qn,this.attemptStartedAtMs=this.now(),this.sampleRatio=er((n=e.connectionMilestoneSampleRatio)!==null&&n!==void 0?n:Gi),this.slowConnectionThresholdMs=Math.max(0,Hi(e.slowConnectionThresholdMs,Xn)),this.sampled=((a=e.random)!==null&&a!==void 0?a:Math.random)()<this.sampleRatio,this.updateContext((s=e.context)!==null&&s!==void 0?s:{}),this.record("client_session_attempt")}updateContext(e){this.context=Object.assign(Object.assign({},this.context),e)}record(e,i){if(this.published)return;const n=zi(i),a={name:e,elapsedMs:this.elapsedMs(),clientTimestamp:new Date().toISOString()};Object.keys(n).length>0&&(a.tags=n),this.milestones.push(a)}recordSessionSuccess(e){this.sessionSuccessful||(this.sessionSuccessful=!0,this.record("client_session_success",e),this.publishIfNeeded(),this.finalize())}finalize(){this.published=!0,this.milestones.length=0}publishFailure(e){this.sessionSuccessful||this.published||(this.record("connection_attempt_failed",e),this.publish("failed",e))}publishIfNeeded(){if(!this.published){if(this.elapsedMs()>=this.slowConnectionThresholdMs){this.publish("slow");return}this.sampled&&this.publish("sampled")}}publish(e,i){if(this.published||this.milestones.length===0)return;this.published=!0;const n=qi(Object.assign(Object.assign(Object.assign({},i),this.context),{publishReason:e,attemptDurationMs:this.elapsedMs(),milestoneCount:this.milestones.length,connectionMilestoneSampleRatio:this.sampleRatio,slowConnectionThresholdMs:this.slowConnectionThresholdMs,wasSampled:this.sampled?1:0})),a=[{name:le.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONES,value:"1",tags:n},...this.milestones.map((s,d)=>({name:le.CLIENT_METRIC_MEASUREMENT_CONNECTION_MILESTONE,value:s.elapsedMs,clientTimestamp:s.clientTimestamp,tags:qi(Object.assign(Object.assign(Object.assign({},this.context),{publishReason:e,milestone:s.name,sequence:d}),s.tags))}))];ji(a)}elapsedMs(){return Math.max(0,Math.round(this.now()-this.attemptStartedAtMs))}}const Qn=()=>typeof performance<"u"?performance.now():Date.now(),er=t=>{const e=Hi(t,Gi);return Math.min(1,Math.max(0,e))},Hi=(t,e)=>typeof t=="number"&&Number.isFinite(t)?t:e,zi=t=>{if(!t)return{};const e={};return Object.entries(t).forEach(([i,n])=>{n!=null&&(typeof n=="number"&&!Number.isFinite(n)||(e[i]=n))}),e},qi=t=>{const e={};return Object.entries(zi(t)).forEach(([i,n])=>{e[i]=typeof n=="boolean"?String(n):n}),e};function tr(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 K;(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"})(K||(K={}));var re;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.TOOL_CALL_STARTED_EVENT="toolCallStarted",t.TOOL_CALL_COMPLETED_EVENT="toolCallCompleted",t.TOOL_CALL_FAILED_EVENT="toolCallFailed",t.REASONING_TEXT="reasoningText",t.USER_SPEECH_STARTED="userSpeechStarted",t.USER_SPEECH_ENDED="userSpeechEnded",t.DIRECTOR_NOTE_CUE_APPLIED="directorNoteCueApplied"})(re||(re={}));var me;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(me||(me={}));var ge;(function(t){t.USER="user",t.PERSONA="persona"})(ge||(ge={}));var A;(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.TOOL_CALL_STARTED="TOOL_CALL_STARTED",t.TOOL_CALL_COMPLETED="TOOL_CALL_COMPLETED",t.TOOL_CALL_FAILED="TOOL_CALL_FAILED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED",t.USER_SPEECH_STARTED="USER_SPEECH_STARTED",t.USER_SPEECH_ENDED="USER_SPEECH_ENDED",t.DIRECTOR_NOTE_CUE_APPLIED="DIRECTOR_NOTE_CUE_APPLIED"})(A||(A={}));var U;(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_TOOL_CALL_STARTED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED",t.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED="WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED",t.TOOL_CALL_RESULT_READY="TOOL_CALL_RESULT_READY"})(U||(U={}));var Ee;(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"})(Ee||(Ee={}));class ir{constructor(e,i){this.sequenceNumber=0,this.config=e,this.signallingClient=i}sendAudioChunk(e){const n={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(n)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const i=e instanceof Uint8Array?e:new Uint8Array(e),n=Array.from(i,a=>String.fromCharCode(a)).join("");return btoa(n)}}var Le=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const nr=5,rr=5,or=24;class sr{constructor(e,i,n,a,s,d){var l,m,p,f,u;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.permanentlyClosed=!1,this.iceRestartReconnectInProgress=!1,this.heartBeatIntervalRef=null,this.reconnectTimer=null,this.publicEventEmitter=n,this.internalEventEmitter=a,this.apiGatewayConfig=s,this.connectionMilestones=d,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:y,maxWsReconnectionAttempts:E,url:S}=i;if(this.heartbeatIntervalSeconds=y||nr,this.maxWsReconnectionAttempts=E||rr,!S.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.enabled&&(!((m=this.apiGatewayConfig)===null||m===void 0)&&m.baseUrl)){const T=new URL(this.apiGatewayConfig.baseUrl),I=(p=this.apiGatewayConfig.wsPath)!==null&&p!==void 0?p:"/ws";T.protocol=T.protocol.replace("http","ws"),T.pathname=I,this.url=T;const w=S.protocol||"https",b=w==="http"?"ws":"wss",O=`${w}://${S.baseUrl}`,k=(f=S.signallingPath)!==null&&f!==void 0?f:"/ws",R=new URL(O);R.protocol=b==="ws"?"ws:":"wss:",S.port&&(R.port=S.port),R.pathname=k,R.searchParams.append("session_id",e),this.url.searchParams.append("target_url",R.href)}else{const I=`${S.protocol||"https"}://${S.baseUrl}`;this.url=new URL(I),this.url.protocol=S.protocol==="http"?"ws:":"wss:",S.port&&(this.url.port=S.port),this.url.pathname=(u=S.signallingPath)!==null&&u!==void 0?u:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){var e;this.clearReconnectTimer(),(e=this.connectionMilestones)===null||e===void 0||e.record("websocket_connecting",{attemptNumber:this.wsConnectionAttempts+1});const i=new WebSocket(this.url.href);return this.socket=i,i.onopen=()=>{this.onOpen(i)},i.onclose=n=>{this.onClose(i,n)},i.onerror=n=>{this.onError(i,n)},i}reconnectForIceRestart(){if(!this.isPermanentlyClosed()){if(this.clearReconnectTimer(),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}catch(e){console.warn("SignallingClient - reconnectForIceRestart: error closing stale socket",e)}this.socket=null}this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.wsConnectionAttempts=0,this.iceRestartReconnectInProgress=!0,this.connect()}}endIceRestartReconnect(){this.iceRestartReconnectInProgress=!1}isConnected(){var e;return((e=this.socket)===null||e===void 0?void 0:e.readyState)===WebSocket.OPEN}isPermanentlyClosed(){return this.permanentlyClosed||this.stopSignal}sendOffer(e){return Le(this,void 0,void 0,function*(){const i={connectionDescription:e,userUid:this.sessionId},n={actionType:K.OFFER,sessionId:this.sessionId,payload:i};this.sendSignalMessage(n)})}sendIceCandidate(e){return Le(this,void 0,void 0,function*(){const i={actionType:K.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(i)})}sendSignalMessage(e){var i;if(((i=this.socket)===null||i===void 0?void 0:i.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(n){console.error("SignallingClient - sendSignalMessage: error sending message",n)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Le(this,void 0,void 0,function*(){const i={actionType:K.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)})}sendAgentAudioInput(e){const i={actionType:K.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(i)}sendAgentAudioInputEnd(){const e={actionType:K.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.clearReconnectTimer(),this.iceRestartReconnectInProgress=!1,this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(e){return Le(this,void 0,void 0,function*(){var i;if(this.socket===e)try{(i=this.connectionMilestones)===null||i===void 0||i.record("websocket_open",{attemptNumber:this.wsConnectionAttempts+1}),this.wsConnectionAttempts=0,this.flushSendingBuffer(),e.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(U.WEB_SOCKET_OPEN)}catch(n){console.error("SignallingClient - onOpen: error in onOpen",n),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.permanentlyClosed=!0}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}onClose(e,i){return Le(this,void 0,void 0,function*(){var n,a,s;if(this.socket!==e||((n=this.connectionMilestones)===null||n===void 0||n.record("websocket_closed",{attemptNumber:this.wsConnectionAttempts+1,closeCode:i?.code,wasClean:i?.wasClean}),this.wsConnectionAttempts+=1,this.stopSignal))return;const d=this.getMaxReconnectionAttempts();if(this.wsConnectionAttempts<=d){const l=100*this.wsConnectionAttempts;(a=this.connectionMilestones)===null||a===void 0||a.record("websocket_retry_scheduled",{attemptNumber:this.wsConnectionAttempts+1,delayMs:l}),this.socket=null,this.clearReconnectTimer(),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},l)}else this.clearReconnectTimer(),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure({failureStage:"websocket",closeCode:i?.code}),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SIGNALLING_CLIENT_CONNECTION_FAILURE),this.iceRestartReconnectInProgress=!1,this.permanentlyClosed=!0})}getMaxReconnectionAttempts(){return this.iceRestartReconnectInProgress?Math.max(this.maxWsReconnectionAttempts,or):this.maxWsReconnectionAttempts}onError(e,i){var n;this.stopSignal||this.socket!==e||((n=this.connectionMilestones)===null||n===void 0||n.record("websocket_error",{eventType:i.type}),console.error("SignallingClient - onError: ",i))}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(i=>{var n;((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(i)):e.push(i)}),this.sendingBuffer=e}onMessage(e){return Le(this,void 0,void 0,function*(){const i=JSON.parse(e.data);this.internalEventEmitter.emit(U.SIGNAL_MESSAGE_RECEIVED,i)})}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,i={actionType:K.HEARTBEAT,sessionId:this.sessionId,payload:""},n=JSON.stringify(i);this.heartBeatIntervalRef=setInterval(()=>{var a;this.stopSignal||((a=this.socket)===null||a===void 0?void 0:a.readyState)===WebSocket.OPEN&&this.socket.send(n)},e)}}function ar(t){return"brainType"in t||"llmId"in t}var xt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class lr{constructor(e,i,n){if(!e&&!i)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=i||null,this.baseUrl=n?.baseUrl||Fn,this.apiVersion=n?.apiVersion||$n,this.apiGatewayConfig=n?.apiGateway||void 0,this.retryOptions=cr(n?.retry),this.requestTimeoutMs=Math.max(0,lt(n?.requestTimeoutMs,Gn))}buildGatewayUrlAndHeaders(e,i){var n,a;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((a=this.apiGatewayConfig)===null||a===void 0)&&a.baseUrl)){const s=`${this.apiGatewayConfig.baseUrl}${e}`,d=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},i),{"X-Anam-Target-Url":d.href});return{url:s,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:i}}startSession(e,i){return xt(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",Y.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.");const{maxAttempts:n}=this.retryOptions;let a;for(let s=1;s<=n;s++)try{return yield this.attemptStartSession(e,i)}catch(d){if(a=d,s>=n||!dr(d))throw d;yield ur(this.computeBackoffDelay(s))}throw a})}attemptStartSession(e,i){return xt(this,void 0,void 0,function*(){const n=this.requestTimeoutMs>0?new AbortController:void 0,a=n!==void 0?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{const s=`${this.apiVersion}/engine/session`,{url:d,headers:l}=this.buildGatewayUrlAndHeaders(s,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),m=yield fetch(d,{method:"POST",headers:l,body:JSON.stringify({personaConfig:e,sessionOptions:i,clientMetadata:Pi}),signal:n?.signal}),p=yield m.json(),f=p.error;switch(m.status){case 200:case 201:return p;case 400:throw new $("Invalid request to start session",Y.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:p.message});case 401:throw new $("Authentication failed when starting session",Y.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:p.message});case 402:throw new $("Please sign up for a plan to start a session",Y.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:p.message});case 403:throw new $("Authentication failed when starting session",Y.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:p.message});case 429:throw f==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",Y.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:p.message}):f==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",Y.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:p.message}):new $("Usage limit reached, please upgrade your plan",Y.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:p.message});case 503:throw new $("There are no available personas, please try again later",Y.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:p.message});default:throw new $("Unknown error when starting session",Y.CLIENT_ERROR_CODE_SERVER_ERROR,m.status,{cause:p.message})}}catch(s){throw s instanceof $?s:new $("Failed to start session",Y.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s)})}finally{a!==void 0&&clearTimeout(a)}})}computeBackoffDelay(e){const{initialBackoffMs:i,maxBackoffMs:n}=this.retryOptions,a=Math.min(n,i*Math.pow(2,e-1));return Math.floor(a/2+Math.random()*(a/2))}unsafe_getSessionToken(e){return xt(this,void 0,void 0,function*(){if(console.warn("Using an insecure 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 i={clientLabel:"js-sdk-api-key"};ar(e)&&(i=Object.assign(Object.assign({},i),{personaConfig:e}));try{const n=`${this.apiVersion}/auth/session-token`,{url:a,headers:s}=this.buildGatewayUrlAndHeaders(n,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(a,{method:"POST",headers:s,body:JSON.stringify(i)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}function cr(t){const e=Math.max(1,Math.floor(lt(t?.maxAttempts,Vn))),i=Math.max(0,lt(t?.initialBackoffMs,Wn)),n=Math.max(i,lt(t?.maxBackoffMs,jn));return{maxAttempts:e,initialBackoffMs:i,maxBackoffMs:n}}function lt(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function dr(t){return t instanceof $?t.statusCode>=500&&t.statusCode<600:!0}function ur(t){return new Promise(e=>setTimeout(e,t))}var hr=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class fr{constructor(e,i,n){this.baseUrl=e,this.sessionId=i,this.apiGatewayConfig=n}sendTalkCommand(e){return hr(this,void 0,void 0,function*(){var i,n;try{let a,s={"Content-Type":"application/json"};const d="/talk",l=`?session_id=${this.sessionId}`;if(!((i=this.apiGatewayConfig)===null||i===void 0)&&i.enabled&&(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.baseUrl)){a=`${this.apiGatewayConfig.baseUrl}${d}${l}`;const p=new URL(`${this.baseUrl}${d}${l}`);s["X-Anam-Target-Url"]=p.href}else a=`${this.baseUrl}${d}${l}`;const m=yield fetch(a,{method:"POST",headers:s,body:JSON.stringify({content:e})});if(!m.ok)throw new Error(`Failed to send talk command: ${m.status} ${m.statusText}`)}catch(a){throw console.error(a),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class pr{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){this.listeners[e]&&this.listeners[e].forEach(n=>{n(...i)})}}class _r{constructor(e,i){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(U.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return Object.assign({id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted},e.cue_tag?{cueTag:e.cue_tag}:{})}processUserMessage(e){const i={id:e.id,content:e.content,role:e.role};this.messages.push(i)}processPersonaMessage(e){const i={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},n=this.messages.findIndex(a=>a.id===i.id);if(n!==-1){const a=this.messages[n];this.messages[n]=Object.assign(Object.assign({},a),{content:a.content+i.content,interrupted:a.interrupted||i.interrupted})}else this.messages.push(i)}processWebRtcTextMessageEvent(e){const i=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(A.MESSAGE_STREAM_EVENT_RECEIVED,i),i.role){case ge.USER:this.processUserMessage(i);break;case ge.PERSONA:this.processPersonaMessage(i);break}i.endOfSpeech&&this.publicEventEmitter.emit(A.MESSAGE_HISTORY_UPDATED,this.messages)}}class mr{constructor(){this.listeners={}}addListener(e,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(i)}removeListener(e,i){this.listeners[e]&&this.listeners[e].delete(i)}emit(e,...i){if(e===A.CONNECTION_ESTABLISHED&&ke(le.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===A.CONNECTION_CLOSED){const[n,a]=i;ke(le.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,n,a?{details:a}:void 0)}this.listeners[e]&&this.listeners[e].forEach(n=>{n(...i)})}}var Z;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(Z||(Z={}));var Nt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class gr{constructor(e,i,n){this.state=Z.UNSTARTED,this.correlationId=e,this.internalEventEmitter=i,this.signallingClient=n,this.internalEventEmitter.addListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return Nt(this,void 0,void 0,function*(){e.actionType===K.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=Z.INTERRUPTED,this.onDeactivate())})}endMessage(){return Nt(this,void 0,void 0,function*(){if(this.state===Z.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==Z.STREAMING){console.warn("Talk stream is not in an active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=Z.ENDED,this.onDeactivate()})}streamMessageChunk(e,i){return Nt(this,void 0,void 0,function*(){if(this.state!==Z.STREAMING&&this.state!==Z.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const n={content:e,startOfSpeech:this.state===Z.UNSTARTED,endOfSpeech:i,correlationId:this.correlationId};this.state=i?Z.ENDED:Z.STREAMING,this.state===Z.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(n)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===Z.STREAMING||this.state===Z.UNSTARTED}getState(){return this.state}}var Mt=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const Yi=(t,e)=>{if(isNaN(t)||isNaN(e))return 0;const i=e-t;return i>0?i:0};class Ki{constructor(e,i){this.handlers=Object.create(null),this.pendingCalls=Object.create(null),this.failedCalls=Object.create(null),this.activeSessionId=null,this.publicEventEmitter=e,this.internalEventEmitter=i}setActiveSession(e){this.activeSessionId=e,this.clearPendingCalls(),this.clearFailedCalls()}clearSessionState(){this.activeSessionId=null,this.clearPendingCalls(),this.clearFailedCalls()}clearPendingCalls(){this.pendingCalls=Object.create(null)}clearFailedCalls(){this.failedCalls=Object.create(null)}registerHandler(e,i){return this.handlers[e]=i,()=>{delete this.handlers[e]}}processToolCallStartedEvent(e){return Mt(this,void 0,void 0,function*(){if(this.activeSessionId!==e.session_id)return;const{tool_name:i,timestamp:n}=e,a=this.WebRTCToolCallStartedEventToToolCallStartedPayload(e),s=new Date(n);if(this.pendingCalls[e.tool_call_id]={payload:a,timestamp:s.getTime()},!(i in this.handlers))return;const d=this.handlers[i];if(d.onStart)try{let l=yield d.onStart(a);if(e.tool_type==="client"){this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:l??void 0,errorMessage:void 0}),yield this.processToolCallCompletedEvent(Object.assign(Object.assign({},e),{result:l,timestamp:new Date().toISOString()}));return}}catch(l){const m=l instanceof Error?l.message:String(l);e.tool_type==="client"&&this.sendToolResult({sessionId:e.session_id,toolCallId:e.tool_call_id,userActionCorrelationId:e.user_action_correlation_id,timestampUserAction:e.timestamp_user_action,result:void 0,errorMessage:`Error in handler: ${m}`}),yield this.processToolCallFailedEvent(Object.assign(Object.assign({},e),{error_message:`Error in onStart handler: ${m}`,timestamp:new Date().toISOString()}));return}})}processToolCallCompletedEvent(e){return Mt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:n,timestamp:a}=e;if(this.activeSessionId!==e.session_id)return;if(n in this.failedCalls){delete this.failedCalls[n];return}const s=this.webRTCToolCallCompletedEventToToolCallCompletedPayload(e);if(n in this.pendingCalls&&delete this.pendingCalls[n],!(i in this.handlers))return;const d=this.handlers[i];if(d.onComplete){e.tool_type==="client"&&this.publicEventEmitter.emit(A.TOOL_CALL_COMPLETED,s);try{yield d.onComplete(s)}catch(l){console.error(`Error in onComplete handler for tool ${i}:`,l);return}}})}processToolCallFailedEvent(e){return Mt(this,void 0,void 0,function*(){const{tool_name:i,tool_call_id:n,timestamp:a}=e;if(this.activeSessionId!==e.session_id)return;const s=this.webRTCToolCallFailedEventToToolCallFailedPayload(e);if(this.failedCalls[n]=s,n in this.pendingCalls&&delete this.pendingCalls[n],!(i in this.handlers))return;const d=this.handlers[i];if(d.onFail){e.tool_type==="client"&&this.publicEventEmitter.emit(A.TOOL_CALL_FAILED,s);try{yield d.onFail(s)}catch(l){console.error(`Error in onFail handler for tool ${i}:`,l);return}}})}sendToolResult(e){const i={sessionId:e.sessionId,toolCallId:e.toolCallId,result:e.result,errorMessage:e.errorMessage,userActionCorrelationId:e.userActionCorrelationId,timestampUserAction:e.timestampUserAction};this.internalEventEmitter.emit(U.TOOL_CALL_RESULT_READY,i)}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}}static WebRTCToolCallStartedEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.tool_name,eventData:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}WebRTCToolCallStartedEventToToolCallStartedPayload(e){return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,arguments:e.arguments,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallCompletedEventToToolCallCompletedPayload(e){const i=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],a=n?Yi(n.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,result:e.result,executionTime:a>0?a:0,timestamp:e.timestamp,documentsAccessed:e.documents_accessed,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}webRTCToolCallFailedEventToToolCallFailedPayload(e){const i=new Date(e.timestamp),n=this.pendingCalls[e.tool_call_id],a=n?Yi(n.timestamp,i.getTime()):0;return{eventUid:e.event_uid,sessionId:e.session_id,toolCallId:e.tool_call_id,toolName:e.tool_name,toolType:e.tool_type,toolSubtype:e.tool_subtype,errorMessage:e.error_message,executionTime:a>0?a:0,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}var J=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};const kt=15e3,Er=5e3,Ji=2,vr=3,Cr=2e3,Lt=3e3,Sr=5e3;class yr{constructor(e,i,n,a,s,d){var l,m,p,f;this.peerConnection=null,this.connectionEstablishedEmitted=!1,this.iceRestartInProgress=!1,this.iceRestartAttempts=0,this.iceRestartAwaitedAnswer=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.iceRestartStopped=!1,this.iceDisconnectedGraceTimer=null,this.iceRestartWatchdogTimer=null,this.pendingWsOpenListener=null,this.pendingWsOpenTimeout=null,this.pendingWsOpenReject=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.iceRestartCandidateBuffer=null,this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:me.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1,this.publicEventEmitter=n,this.internalEventEmitter=a,this.toolCallManager=s,this.connectionMilestones=d,this.apiGatewayConfig=i.apiGateway;const{inputAudio:u}=i;this.inputAudioState=u.inputAudioState,i.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=i.inputAudio.userProvidedMediaStream),this.disableInputAudio=i.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(U.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(U.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,this.toolCallManager.processToolCallStartedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,this.toolCallManager.processToolCallCompletedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,this.toolCallManager.processToolCallFailedEvent.bind(this.toolCallManager)),this.internalEventEmitter.addListener(U.TOOL_CALL_RESULT_READY,this.onToolCallResultReceived.bind(this)),this.iceServers=i.iceServers,this.iceTransportPolicy=i.iceTransportPolicy,this.rtcConfiguration=i.rtcConfiguration,this.signallingClient=new sr(e,i.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig,this.connectionMilestones),this.engineApiRestClient=new fr(i.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=i.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(m=(l=i.metrics)===null||l===void 0?void 0:l.showPeerConnectionStatsReport)!==null&&m!==void 0?m:!1,this.peerConnectionStatsReportOutputFormat=(f=(p=i.metrics)===null||p===void 0?void 0:p.peerConnectionStatsReportOutputFormat)!==null&&f!==void 0?f:"console"}onInputAudioStateChange(e,i){e.isMuted!==i.isMuted&&(i.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(i=>{i.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>J(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)}}),Er))}sendClientSideMetrics(e){e.forEach(i=>{if(i.type==="inbound-rtp"){const n={message_type:"remote_rtp_stats",data:i};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(n))}})}recordSessionSuccess(e){var i,n;this.successMetricFired||(this.successMetricFired=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_video_frame",{detectionMethod:e}),(n=this.connectionMilestones)===null||n===void 0||n.recordSessionSuccess({detectionMethod:e}),ke(le.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:e}))}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{var i,n;this.successMetricPoller&&((i=this.connectionMilestones)===null||i===void 0||i.record("first_video_frame_timeout",{timeoutMs:kt}),(n=this.connectionMilestones)===null||n===void 0||n.publishFailure({failureStage:"first_video_frame",timeoutMs:kt}),console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},kt);this.successMetricPoller=setInterval(()=>J(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const i=yield this.peerConnection.getStats();let n=!1,a=null;i.forEach(s=>{s.type==="inbound-rtp"&&s.kind==="video"&&(s.framesDecoded!==void 0&&s.framesDecoded>0?(n=!0,a="framesDecoded"):s.framesReceived!==void 0&&s.framesReceived>0?(n=!0,a="framesReceived"):s.bytesReceived>0&&s.packetsReceived>0&&s.bytesReceived>1e5&&(n=!0,a="bytesReceived"))}),n&&!this.successMetricFired&&(this.recordSessionSuccess(a??"unknown"),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,i=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=i,this.onInputAudioStateChange(e,i),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return J(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 i=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(a=>{a.stop()});const n={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:n}),this.audioDeviceId=e,yield this.setupAudioTrack(),i&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(A.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(n){throw console.error("Failed to change audio input device:",n),new Error(`StreamingClient - changeAudioInputDevice: ${n instanceof Error?n.message:String(n)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}onToolCallResultReceived(e){const i={session_id:e.sessionId,message_type:"tool_result",tool_call_id:e.toolCallId,user_action_correlation_id:e.userActionCorrelationId,timestamp_user_action:e.timestampUserAction};e.result!==void 0&&(i.result=e.result),e.errorMessage&&(i.error=e.errorMessage),this.sendDataMessage(JSON.stringify(i))}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const i=document.getElementById(e);if(!i)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=i}}startConnection(){var e;try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.resetAttemptScopedMilestoneState(),(e=this.connectionMilestones)===null||e===void 0||e.record("connection_start_requested"),this.signallingClient.connect()}catch(i){console.error("StreamingClient - startConnection: error",i),this.handleWebrtcFailure(i)}}resetAttemptScopedMilestoneState(){this.firstLocalIceCandidateSent=!1,this.firstRemoteIceCandidateReceived=!1,this.firstRemoteIceCandidateApplied=!1,this.connectionEstablishedMilestoneRecorded=!1}stopConnection(){return J(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return J(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 gr(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new ir(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return J(this,void 0,void 0,function*(){var e,i,n,a,s,d,l,m,p,f;(e=this.connectionMilestones)===null||e===void 0||e.record("peer_connection_creating"),this.peerConnection=new RTCPeerConnection(Object.assign(Object.assign({iceCandidatePoolSize:Ji},this.rtcConfiguration),{iceTransportPolicy:(a=(n=(i=this.rtcConfiguration)===null||i===void 0?void 0:i.iceTransportPolicy)!==null&&n!==void 0?n:this.iceTransportPolicy)!==null&&a!==void 0?a:void 0,iceServers:this.iceServers})),(s=this.connectionMilestones)===null||s===void 0||s.record("peer_connection_created",{iceCandidatePoolSize:Ji,iceServerCount:this.iceServers.length,iceTransportPolicy:(m=(l=(d=this.rtcConfiguration)===null||d===void 0?void 0:d.iceTransportPolicy)!==null&&l!==void 0?l:this.iceTransportPolicy)!==null&&m!==void 0?m:"all"}),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?((p=this.connectionMilestones)===null||p===void 0||p.record("microphone_permission_skipped",{reason:"input_audio_disabled"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?((f=this.connectionMilestones)===null||f===void 0||f.record("input_audio_stream_provided",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),yield this.setupAudioTrack()):this.requestMicrophonePermissionAsync().catch(u=>{console.error("Async microphone permission request failed:",u)}))})}onSignalMessage(e){return J(this,void 0,void 0,function*(){var i,n,a,s;if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case K.ANSWER:{(i=this.connectionMilestones)===null||i===void 0||i.record("answer_received");const f=e.payload;if(this.peerConnection.signalingState!=="have-local-offer")break;try{yield this.peerConnection.setRemoteDescription(f)}catch(u){console.error("StreamingClient - setRemoteDescription(answer) failed",u),!this.connectionEstablishedEmitted&&!this.isAwaitingRestartAnswer()&&this.handleWebrtcFailure(u);break}(n=this.connectionMilestones)===null||n===void 0||n.record("remote_description_set"),this.connectionReceivedAnswer=!0,this.onAnswerAccepted(),yield this.flushRemoteIceCandidateBuffer();break}case K.ICE_CANDIDATE:{const f=e.payload,u=new RTCIceCandidate(f);this.firstRemoteIceCandidateReceived||(this.firstRemoteIceCandidateReceived=!0,(a=this.connectionMilestones)===null||a===void 0||a.record("first_remote_ice_candidate_received",Dt(u))),this.connectionReceivedAnswer?yield this.addRemoteIceCandidate(u):this.remoteIceCandidateBuffer.push(u);break}case K.END_SESSION:const d=e.payload;this.sendIceRestartMetric("aborted"),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure({failureStage:"server_closed_connection"}),this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.SERVER_CLOSED_CONNECTION,d),this.shutdown();break;case K.WARNING:const l=e.payload;console.warn("Warning received from server: "+l),this.publicEventEmitter.emit(A.SERVER_WARNING,l);break;case K.TALK_STREAM_INTERRUPTED:const m=e.payload;this.publicEventEmitter.emit(A.TALK_STREAM_INTERRUPTED,m.correlationId);break;case K.SESSION_READY:const p=e.sessionId;this.publicEventEmitter.emit(A.SESSION_READY,p);break;case K.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your @anam-ai/js-sdk version up to date?",e)}})}onSignallingClientConnected(){return J(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(){return J(this,void 0,void 0,function*(){const e=[...this.remoteIceCandidateBuffer];this.remoteIceCandidateBuffer=[];for(const i of e)yield this.addRemoteIceCandidate(i)})}addRemoteIceCandidate(e){return J(this,void 0,void 0,function*(){if(this.peerConnection)try{yield this.peerConnection.addIceCandidate(e),this.recordFirstRemoteIceCandidateApplied(e)}catch(i){console.warn("StreamingClient - addRemoteIceCandidate: failed to add remote ICE candidate",i)}})}recordFirstRemoteIceCandidateApplied(e){var i;this.firstRemoteIceCandidateApplied||(this.firstRemoteIceCandidateApplied=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_remote_ice_candidate_applied",Dt(e)))}onIceCandidate(e){var i,n;if(e.candidate){if(this.firstLocalIceCandidateSent||(this.firstLocalIceCandidateSent=!0,(i=this.connectionMilestones)===null||i===void 0||i.record("first_local_ice_candidate_sent",Dt(e.candidate))),this.iceRestartCandidateBuffer){this.iceRestartCandidateBuffer.push(e.candidate);return}this.signallingClient.sendIceCandidate(e.candidate)}else(n=this.connectionMilestones)===null||n===void 0||n.record("ice_gathering_complete")}onIceConnectionStateChange(){var e,i,n;const a=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;switch(a&&((i=this.connectionMilestones)===null||i===void 0||i.record("ice_connection_state_changed",{iceConnectionState:a})),a){case"connected":case"completed":this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog(),this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.iceRestartAttempts=0,this.signallingClient.endIceRestartReconnect(),this.connectionEstablishedMilestoneRecorded||(this.connectionEstablishedMilestoneRecorded=!0,(n=this.connectionMilestones)===null||n===void 0||n.record("client_connection_established",{iceConnectionState:a})),this.connectionEstablishedEmitted||(this.connectionEstablishedEmitted=!0,this.publicEventEmitter.emit(A.CONNECTION_ESTABLISHED)),this.startStatsCollection();break;case"disconnected":this.scheduleIceRestartAfterGrace();break;case"failed":this.clearIceDisconnectedGraceTimer(),this.restartIce();break}}clearIceDisconnectedGraceTimer(){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null)}clearIceRestartWatchdog(){this.iceRestartWatchdogTimer&&(clearTimeout(this.iceRestartWatchdogTimer),this.iceRestartWatchdogTimer=null)}sendIceRestartMetric(e){var i;if(this.iceRestartEpisodeStartMs===null)return;const n=Math.round(performance.now()-this.iceRestartEpisodeStartMs),a=(i=this.iceRestartEpisodeTrigger)!==null&&i!==void 0?i:"unknown";this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,ke(le.CLIENT_METRIC_MEASUREMENT_ICE_RESTART,n,{outcome:e,attempts:this.iceRestartAttempts,trigger:a})}isAwaitingRestartAnswer(){return this.iceRestartInProgress||this.iceRestartAwaitedAnswer||this.iceRestartWatchdogTimer!==null}onAnswerAccepted(){var e;const i=this.isAwaitingRestartAnswer();if(this.clearIceRestartWatchdog(),this.iceRestartAwaitedAnswer=!1,!i)return;this.iceRestartInProgress=!1;const n=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;(n==="disconnected"||n==="failed")&&this.scheduleIceRestartAfterGrace()}clearPendingWsOpenWait(){this.pendingWsOpenTimeout&&(clearTimeout(this.pendingWsOpenTimeout),this.pendingWsOpenTimeout=null),this.pendingWsOpenListener&&(this.internalEventEmitter.removeListener(U.WEB_SOCKET_OPEN,this.pendingWsOpenListener),this.pendingWsOpenListener=null),this.pendingWsOpenReject=null}cancelIceRestart(){this.clearIceDisconnectedGraceTimer(),this.clearIceRestartWatchdog();const e=this.pendingWsOpenReject;this.clearPendingWsOpenWait(),e&&e(new Error("ice restart cancelled")),this.iceRestartCandidateBuffer=null,this.iceRestartInProgress=!1,this.iceRestartEpisodeStartMs=null,this.iceRestartEpisodeTrigger=null,this.signallingClient.endIceRestartReconnect()}flushIceRestartCandidateBuffer(){const e=this.iceRestartCandidateBuffer;if(this.iceRestartCandidateBuffer=null,!!e)for(const i of e)this.signallingClient.sendIceCandidate(i)}scheduleIceRestartAfterGrace(){this.iceRestartStopped||this.iceRestartInProgress||this.iceDisconnectedGraceTimer||(this.iceDisconnectedGraceTimer=setTimeout(()=>{var e;if(this.iceDisconnectedGraceTimer=null,this.iceRestartStopped)return;const i=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;(i==="disconnected"||i==="failed")&&this.restartIce()},Cr))}ensureSignallingConnected(){return this.signallingClient.isConnected()?Promise.resolve():this.signallingClient.isPermanentlyClosed()?Promise.reject(new Error("signalling permanently closed")):new Promise((e,i)=>{this.pendingWsOpenReject=i,this.pendingWsOpenTimeout=setTimeout(()=>{this.clearPendingWsOpenWait(),i(new Error("timed out waiting for signalling WebSocket"))},Sr);const n=()=>{this.clearPendingWsOpenWait(),e()};this.pendingWsOpenListener=n,this.internalEventEmitter.addListener(U.WEB_SOCKET_OPEN,n)})}restartIce(){return J(this,void 0,void 0,function*(){var e,i;if(!(!this.peerConnection||this.iceRestartInProgress||this.iceRestartStopped)){if(this.signallingClient.isPermanentlyClosed()){this.sendIceRestartMetric("aborted"),this.cancelIceRestart();return}if(this.iceRestartAttempts>=vr){console.error("StreamingClient - restartIce: exhausted attempts"),(e=this.connectionMilestones)===null||e===void 0||e.publishFailure({failureStage:"ice_connection",iceConnectionState:(i=this.peerConnection)===null||i===void 0?void 0:i.iceConnectionState}),this.sendIceRestartMetric("exhausted"),this.cancelIceRestart(),this.handleWebrtcFailure("The connection to our servers was lost. Please try again.");return}this.iceRestartAttempts===0&&(this.iceRestartEpisodeStartMs=performance.now(),this.iceRestartEpisodeTrigger=this.peerConnection.iceConnectionState),this.iceRestartInProgress=!0,this.iceRestartAttempts+=1;try{if(this.peerConnection.signalingState!=="stable"&&(yield this.peerConnection.setLocalDescription({type:"rollback"})),this.iceRestartAttempts===1&&this.signallingClient.reconnectForIceRestart(),yield this.ensureSignallingConnected(),this.iceRestartStopped)return;const n=this.peerConnection.iceConnectionState;if(n==="connected"||n==="completed"){this.iceRestartInProgress=!1,this.sendIceRestartMetric("recovered"),this.signallingClient.endIceRestartReconnect();return}this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[];const a=yield this.peerConnection.createOffer({iceRestart:!0});if(this.iceRestartCandidateBuffer=[],yield this.peerConnection.setLocalDescription(a),!this.peerConnection.localDescription)throw new Error("null local description after ICE restart offer");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),this.flushIceRestartCandidateBuffer(),this.iceRestartAwaitedAnswer=!1,this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),Lt)}catch(n){if(this.iceRestartCandidateBuffer=null,console.error("StreamingClient - restartIce: error",n),this.iceRestartInProgress=!1,this.iceRestartStopped){this.cancelIceRestart();return}if(this.signallingClient.isPermanentlyClosed()){this.sendIceRestartMetric("aborted"),this.cancelIceRestart();return}this.clearIceRestartWatchdog(),this.iceRestartWatchdogTimer=setTimeout(()=>{this.iceRestartWatchdogTimer=null,this.restartIce()},Lt)}}})}onIceRestartWatchdog(){var e;if(this.iceRestartWatchdogTimer=null,this.iceRestartInProgress=!1,this.iceRestartStopped)return;const i=(e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState;if(!(i==="connected"||i==="completed")){if(!this.connectionReceivedAnswer&&!this.iceRestartAwaitedAnswer){this.iceRestartAwaitedAnswer=!0,this.iceRestartInProgress=!0,this.iceRestartWatchdogTimer=setTimeout(()=>this.onIceRestartWatchdog(),Lt);return}this.restartIce()}}onConnectionStateChange(){var e,i,n,a,s;const d=(e=this.peerConnection)===null||e===void 0?void 0:e.connectionState;if(d&&((i=this.connectionMilestones)===null||i===void 0||i.record("webrtc_connection_state_changed",{connectionState:d})),d==="failed"){const l=(n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState;!this.iceRestartStopped&&(l==="disconnected"||l==="failed")||(a=this.connectionMilestones)===null||a===void 0||a.publishFailure({failureStage:"webrtc_connection",connectionState:d})}((s=this.peerConnection)===null||s===void 0?void 0:s.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){var i,n;(i=this.connectionMilestones)===null||i===void 0||i.record("webrtc_failure",Ye(e)),(n=this.connectionMilestones)===null||n===void 0||n.publishFailure(Object.assign({failureStage:"webrtc"},Ye(e))),console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.WEBRTC_FAILURE);try{this.stopConnection()}catch(a){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",a)}}onTrackEventHandler(e){var i,n;if(e.track.kind==="video"){if((i=this.connectionMilestones)===null||i===void 0||i.record("video_track_received"),this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(A.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const a=this.videoElement.requestVideoFrameCallback(()=>{var s;(s=this.videoElement)===null||s===void 0||s.cancelVideoFrameCallback(a),this.publicEventEmitter.emit(A.VIDEO_PLAY_STARTED),this.recordSessionSuccess("videoElement")})}}else e.track.kind==="audio"&&((n=this.connectionMilestones)===null||n===void 0||n.record("audio_track_received"),this.audioStream=e.streams[0],this.publicEventEmitter.emit(A.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return J(this,void 0,void 0,function*(){var e;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 i=this.peerConnection.createDataChannel("session",{ordered:!0});(e=this.connectionMilestones)===null||e===void 0||e.record("data_channel_created"),i.onopen=()=>{var n;this.dataChannel=i??null,(n=this.connectionMilestones)===null||n===void 0||n.record("data_channel_open")},i.onclose=()=>{var n;(n=this.connectionMilestones)===null||n===void 0||n.record("data_channel_closed")},i.onmessage=n=>{var a,s,d,l,m,p;try{const f=JSON.parse(n.data);switch(f.messageType){case re.SPEECH_TEXT:this.internalEventEmitter.emit(U.WEBRTC_CHAT_MESSAGE_RECEIVED,f.data);break;case re.CLIENT_TOOL_EVENT:const u=f.data;this.internalEventEmitter.emit(U.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,u);const y=Ki.WebRTCClientToolEventToClientToolEvent(u);this.publicEventEmitter.emit(A.CLIENT_TOOL_EVENT_RECEIVED,y);break;case re.TOOL_CALL_STARTED_EVENT:const E=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_STARTED,this.toolCallManager.WebRTCToolCallStartedEventToToolCallStartedPayload(E)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_STARTED_EVENT_RECEIVED,E);break;case re.TOOL_CALL_COMPLETED_EVENT:const S=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_COMPLETED,this.toolCallManager.webRTCToolCallCompletedEventToToolCallCompletedPayload(S)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_COMPLETED_EVENT_RECEIVED,S);break;case re.TOOL_CALL_FAILED_EVENT:const T=f.data;this.publicEventEmitter.emit(A.TOOL_CALL_FAILED,this.toolCallManager.webRTCToolCallFailedEventToToolCallFailedPayload(T)),this.internalEventEmitter.emit(U.WEBRTC_TOOL_CALL_FAILED_EVENT_RECEIVED,T);break;case re.REASONING_TEXT:this.internalEventEmitter.emit(U.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,f.data);break;case re.USER_SPEECH_STARTED:this.publicEventEmitter.emit(A.USER_SPEECH_STARTED,(s=(a=f.data)===null||a===void 0?void 0:a.user_action_correlation_id)!==null&&s!==void 0?s:"unknown");break;case re.USER_SPEECH_ENDED:this.publicEventEmitter.emit(A.USER_SPEECH_ENDED,(l=(d=f.data)===null||d===void 0?void 0:d.user_action_correlation_id)!==null&&l!==void 0?l:"unknown");break;case re.DIRECTOR_NOTE_CUE_APPLIED:const I=f.data;this.publicEventEmitter.emit(A.DIRECTOR_NOTE_CUE_APPLIED,{cueTag:(m=I?.cue_tag)!==null&&m!==void 0?m:"unknown",correlationId:(p=I?.user_action_correlation_id)!==null&&p!==void 0?p:"unknown"});break;default:break}}catch(f){console.error("Failed to parse data channel message:",f)}}})}requestMicrophonePermissionAsync(){return J(this,void 0,void 0,function*(){var e,i,n;if(this.inputAudioState.permissionState!==me.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.PENDING}),(e=this.connectionMilestones)===null||e===void 0||e.record("microphone_permission_pending"),this.publicEventEmitter.emit(A.MIC_PERMISSION_PENDING);try{const a={echoCancellation:!0};this.audioDeviceId&&(a.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:a}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.GRANTED}),(i=this.connectionMilestones)===null||i===void 0||i.record("microphone_permission_granted"),this.publicEventEmitter.emit(A.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(a){console.error("Failed to get microphone permission:",a),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:me.DENIED}),(n=this.connectionMilestones)===null||n===void 0||n.record("microphone_permission_denied",Object.assign({},Ye(a)));const s=a instanceof Error?a.message:String(a);this.publicEventEmitter.emit(A.MIC_PERMISSION_DENIED,s)}}})}setupAudioTrack(){return J(this,void 0,void 0,function*(){var e;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 i=this.inputAudioStream.getAudioTracks()[0],a=this.peerConnection.getSenders().find(s=>{var d;return((d=s.track)===null||d===void 0?void 0:d.kind)==="audio"||s.track===null&&s.dtmf!==null});if(a)try{yield a.replaceTrack(i)}catch(s){console.error("Failed to replace audio track:",s),this.peerConnection.addTrack(i,this.inputAudioStream)}else this.peerConnection.addTrack(i,this.inputAudioStream);(e=this.connectionMilestones)===null||e===void 0||e.record("input_audio_stream_started",{audioTrackCount:this.inputAudioStream.getAudioTracks().length}),this.publicEventEmitter.emit(A.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return J(this,void 0,void 0,function*(){var e,i,n,a,s,d;if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{(e=this.connectionMilestones)===null||e===void 0||e.record("offer_creation_started");const l=yield this.peerConnection.createOffer();(i=this.connectionMilestones)===null||i===void 0||i.record("offer_creation_completed"),yield this.peerConnection.setLocalDescription(l),(n=this.connectionMilestones)===null||n===void 0||n.record("local_description_set")}catch(l){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",l),(a=this.connectionMilestones)===null||a===void 0||a.record("offer_creation_failed",Object.assign({},Ye(l))),(s=this.connectionMilestones)===null||s===void 0||s.publishFailure(Object.assign({failureStage:"offer_creation"},Ye(l)))}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription),(d=this.connectionMilestones)===null||d===void 0||d.record("offer_sent")})}shutdown(){return J(this,void 0,void 0,function*(){var e;if(this.iceRestartStopped=!0,this.cancelIceRestart(),this.showPeerConnectionStatsReport){const i=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(i){const n=Kn(i,this.peerConnectionStatsReportOutputFormat);n&&console.log(n,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(i=>{i.stop()}),this.inputAudioStream=null}catch(i){console.error("StreamingClient - shutdown: error stopping input audio stream",i)}try{this.signallingClient.stop()}catch(i){console.error("StreamingClient - shutdown: error stopping signallilng",i)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(i){console.error("StreamingClient - shutdown: error closing peer connection",i)}})}}const Dt=t=>{const e=t;return Ut({candidateType:e.type,protocol:e.protocol,relayProtocol:e.relayProtocol,tcpType:e.tcpType,component:e.component})},Ye=t=>{if(t instanceof Error)return Ut({errorName:t.name});if(typeof t=="object"&&t!==null){const e=t;return Ut({errorName:typeof e.name=="string"?e.name:void 0,errorCode:typeof e.code=="string"||typeof e.code=="number"?e.code:void 0})}return{}},Ut=t=>{const e={};return Object.entries(t).forEach(([i,n])=>{n!==void 0&&(e[i]=n)}),e};class Tr{constructor(e,i){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=i,this.internalEventEmitter.addListener(U.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 i=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(A.REASONING_STREAM_EVENT_RECEIVED,i);const n={id:i.id,content:i.content,role:i.role},a=this.reasoning_messages.findIndex(s=>s.id===n.id);if(a!==-1){const s=this.reasoning_messages[a];s.content+=n.content,this.reasoning_messages[a]=s}else this.reasoning_messages.push(n);i.endOfThought&&this.publicEventEmitter.emit(A.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var ve=function(t,e,i,n){function a(s){return s instanceof i?s:new i(function(d){d(s)})}return new(i||(i=Promise))(function(s,d){function l(f){try{p(n.next(f))}catch(u){d(u)}}function m(f){try{p(n.throw(f))}catch(u){d(u)}}function p(f){f.done?s(f.value):a(f.value).then(l,m)}p((n=n.apply(t,e||[])).next())})};class Ir{constructor(e,i,n){var a,s,d,l,m;this.inputAudioState={isMuted:!1,permissionState:me.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,i,n);if(p)throw new $(p,Y.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=i,this.clientOptions=n,(!((a=n?.api)===null||a===void 0)&&a.baseUrl||!((s=n?.api)===null||s===void 0)&&s.apiVersion)&&Hn(n.api.baseUrl||Fi,n.api.apiVersion||At),!((l=(d=n?.api)===null||d===void 0?void 0:d.apiGateway)===null||l===void 0)&&l.enabled&&zn(n.api.apiGateway),!((m=n?.metrics)===null||m===void 0)&&m.disableClientMetrics&&qn(!0),this.publicEventEmitter=new mr,this.internalEventEmitter=new pr,this.toolCallManager=new Ki(this.publicEventEmitter,this.internalEventEmitter),this.apiClient=new lr(e,n?.apiKey,n?.api),this.messageHistoryClient=new _r(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Tr(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const i=e.split(".")[1],n=Bn.Buffer.from(i,"base64").toString("utf8");return JSON.parse(n)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,i,n){var a,s;if(!e&&!n?.apiKey)return"Either sessionToken or apiKey must be provided";if(n?.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const d=tr((a=n?.api)===null||a===void 0?void 0:a.apiGateway);if(d)return d;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,qe({organizationId:this.organizationId});const m=(s=l.type)===null||s===void 0?void 0:s.toLowerCase();if(m==="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((m==="ephemeral"||m==="stateful")&&i)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!i)return"Missing persona config. Persona configuration must be provided when using apiKey";if(n?.voiceDetection){if(n.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(n.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof n.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(n.voiceDetection.endOfSpeechSensitivity<0||n.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const i={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(i.voiceDetection=this.clientOptions.voiceDetection),Object.keys(i).length!==0)return i}startConnectionAttempt(){var e,i,n,a;const s=Jn();qe({attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId});const d=new Zn({context:{attemptCorrelationId:s,sessionId:null,organizationId:this.organizationId},connectionMilestoneSampleRatio:(i=(e=this.clientOptions)===null||e===void 0?void 0:e.metrics)===null||i===void 0?void 0:i.connectionMilestoneSampleRatio,slowConnectionThresholdMs:(a=(n=this.clientOptions)===null||n===void 0?void 0:n.metrics)===null||a===void 0?void 0:a.slowConnectionThresholdMs});return ke(le.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),d}startSession(e,i){return ve(this,void 0,void 0,function*(){var n,a,s,d,l,m,p,f,u,y,E,S,T,I,w,b,O;const k=this.personaConfig,R=this.buildStartSessionOptionsForClient();i?.record("start_session_request_started");let ee;try{ee=yield this.apiClient.startSession(k,R),i?.record("start_session_request_completed")}catch(ne){throw i?.record("start_session_request_failed",Object.assign({},De(ne))),i?.publishFailure(Object.assign({failureStage:"start_session_request"},De(ne))),ne}const{sessionId:G,clientConfig:oe,engineHost:te,engineProtocol:se,signallingEndpoint:W}=ee,{heartbeatIntervalSeconds:Q,maxWsReconnectionAttempts:Ie,iceServers:be,iceTransportPolicy:Ce}=oe;this.sessionId=G,this.toolCallManager.setActiveSession(G),qe({sessionId:this.sessionId}),i?.updateContext({sessionId:this.sessionId,organizationId:this.organizationId});const Ke=(l=(a=(n=this.clientOptions)===null||n===void 0?void 0:n.iceServers)!==null&&a!==void 0?a:(d=(s=this.clientOptions)===null||s===void 0?void 0:s.rtcConfiguration)===null||d===void 0?void 0:d.iceServers)!==null&&l!==void 0?l:be;try{this.streamingClient=new yr(G,{engine:{baseUrl:`${se}://${te}`},signalling:{heartbeatIntervalSeconds:Q,maxWsReconnectionAttempts:Ie,url:{baseUrl:te,protocol:se,signallingPath:W}},iceServers:Ke,iceTransportPolicy:Ce,rtcConfiguration:(m=this.clientOptions)===null||m===void 0?void 0:m.rtcConfiguration,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((p=this.clientOptions)===null||p===void 0)&&p.disableInputAudio?void 0:e,audioDeviceId:(f=this.clientOptions)===null||f===void 0?void 0:f.audioDeviceId,disableInputAudio:(u=this.clientOptions)===null||u===void 0?void 0:u.disableInputAudio},apiGateway:(E=(y=this.clientOptions)===null||y===void 0?void 0:y.api)===null||E===void 0?void 0:E.apiGateway,metrics:{showPeerConnectionStatsReport:(I=(T=(S=this.clientOptions)===null||S===void 0?void 0:S.metrics)===null||T===void 0?void 0:T.showPeerConnectionStatsReport)!==null&&I!==void 0?I:!1,peerConnectionStatsReportOutputFormat:(O=(b=(w=this.clientOptions)===null||w===void 0?void 0:w.metrics)===null||b===void 0?void 0:b.peerConnectionStatsReportOutputFormat)!==null&&O!==void 0?O:"console"}},this.publicEventEmitter,this.internalEventEmitter,this.toolCallManager,i)}catch(ne){throw i?.publishFailure(Object.assign({failureStage:"streaming_client_initialization"},De(ne))),this.toolCallManager.clearSessionState(),qe({sessionId:null}),new $("Failed to initialize streaming client",Y.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:ne instanceof Error?ne.message:String(ne),sessionId:G})}return G})}startSessionIfNeeded(e,i){return ve(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e,i),!this.sessionId||!this.streamingClient))throw i?.publishFailure({failureStage:"start_session_validation"}),new $("Session ID or streaming client is not available after starting session",Y.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return ve(this,void 0,void 0,function*(){var i;if(this._isStreaming)throw new Error("Already streaming");const n=this.startConnectionAttempt();!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio&&e&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(e,n)}catch(a){throw n.publishFailure(Object.assign({failureStage:"start_session"},De(a))),a}return this._isStreaming=!0,new Promise(a=>{var s;const d=[];let l=!1,m=!1;this.publicEventEmitter.addListener(A.VIDEO_STREAM_STARTED,p=>{d.push(p),l=!0,m&&a(d)}),this.publicEventEmitter.addListener(A.AUDIO_STREAM_STARTED,p=>{d.push(p),m=!0,l&&a(d)}),(s=this.streamingClient)===null||s===void 0||s.startConnection()})})}streamToVideoAndAudioElements(e,i,n){return ve(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,n)})}streamToVideoElement(e,i){return ve(this,void 0,void 0,function*(){var n;const a=this.startConnectionAttempt();!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&i&&console.warn("AnamClient: Input audio is disabled. User-provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(i,a)}catch(s){throw a.publishFailure(Object.assign({failureStage:"start_session"},De(s))),s instanceof $?s:new $("Failed to start session",Y.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:s instanceof Error?s.message:String(s),sessionId:this.sessionId})}if(this._isStreaming)throw a.publishFailure({failureStage:"already_streaming"}),new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw a.publishFailure({failureStage:"streaming_client_missing"}),new Error("Failed to stream: streaming client is not available");try{this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()}catch(s){throw a.publishFailure(Object.assign({failureStage:"start_connection"},De(s))),s}})}talk(e){return ve(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 i=this.getActiveSessionId();if(!i)throw new Error("Failed to send user message: no active session");const n=new Date().toISOString().replace("Z",""),a=JSON.stringify({content:e,timestamp:n,session_id:i,message_type:"speech"});this.sendDataMessage(a)}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 i=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(i)}addContext(e){if(!this._isStreaming)throw new Error("Failed to add context: not currently streaming");const i=this.getActiveSessionId();if(!i)throw new Error("Failed to add context: no active session");const n=JSON.stringify({message_type:"context",session_id:i,content:e});this.sendDataMessage(n)}stopStreaming(){return ve(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(A.CONNECTION_CLOSED,Ee.NORMAL),this.toolCallManager.clearSessionState(),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,qe({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,i;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&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,i;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&&!(!((i=this.clientOptions)===null||i===void 0)&&i.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return ve(this,void 0,void 0,function*(){var i;if(!((i=this.clientOptions)===null||i===void 0)&&i.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,i){this.publicEventEmitter.addListener(e,i)}removeListener(e,i){this.publicEventEmitter.removeListener(e,i)}getActiveSessionId(){return this.sessionId}registerToolCallHandler(e,i){return this.toolCallManager.registerHandler(e,i)}}const De=t=>t instanceof $?{errorName:t.name,errorCode:t.code,httpStatusCode:t.statusCode}:t instanceof Error?{errorName:t.name}:{},br=(t,e)=>new Ir(t,void 0,e),X={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",TRANSCRIPT_OPENED:"anam-agent:transcript-opened",TRANSCRIPT_CLOSED:"anam-agent:transcript-closed",ERROR:"anam-agent:error",MIC_MUTED:"anam-agent:mic-muted",MIC_UNMUTED:"anam-agent:mic-unmuted",TOOL_CALL_STARTED:"anam-agent:tool-call-started",TOOL_CALL_COMPLETED:"anam-agent:tool-call-completed",TOOL_CALL_FAILED:"anam-agent:tool-call-failed"},wr="https://api.anam.ai";function Xi(t){return/^[a-zA-Z0-9_-]{1,128}$/.test(t)}function Zi(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}function Rr(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 Ar(){return{client:q(null),connectionStatus:q("idle"),isStreaming:q(!1),isMuted:q(!1),messages:q([]),messageTimes:new Map,pendingSent:[],messageSeq:new Map,seqCounter:0,localIdCounter:0,caption:q(null),captionTimer:null,sentCaption:q(null),sentCaptionTimer:null,error:q(null),sessionId:q(null),avatarThumbnailUrl:q(null),avatarVideoUrl:q(null),personaName:q(null),serverConfig:q(null),isConfigured:q(!1),isReady:q(!1),generation:0,prevMessageCount:0,dispatch:null}}function Or(t,e){for(const n of e){if(t.messageSeq.has(n.id))continue;const a=n.role===ge.USER?t.pendingSent.findIndex(s=>s.content===n.content):-1;if(a>=0){const s=t.pendingSent[a];t.messageSeq.set(n.id,t.messageSeq.get(s.id));const d=t.messageTimes.get(s.id);d&&t.messageTimes.set(n.id,d),t.pendingSent.splice(a,1)}else t.messageSeq.set(n.id,t.seqCounter++)}const i=[...e,...t.pendingSent];return i.sort((n,a)=>t.messageSeq.get(n.id)-t.messageSeq.get(a.id)),i}async function xr(t,e,i){if(t.isReady.value=!1,!Xi(e)){console.error("[AnamWidget] Invalid agent ID format:",e);return}try{const n=await fetch(`${i}/v1/personas/${e}/widget`);if(!n.ok){const s=n.status===404?"Agent not found. Check your agent ID.":n.status===401||n.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 a=await n.json();t.avatarThumbnailUrl.value=a.persona?.avatarImageUrl||null,t.avatarVideoUrl.value=a.persona?.avatarVideoUrl||null,t.personaName.value=a.persona?.name||null,t.serverConfig.value=a.widgetConfig||null,t.isReady.value=!0}catch(n){console.error("[AnamWidget] Failed to load widget config:",n)}}async function Nr(t,e,i,n,a){if(t.connectionStatus.value==="connecting"||t.connectionStatus.value==="connected")return;const s=++t.generation;t.connectionStatus.value="connecting",t.error.value=null;let d;try{let l;if(a)l=a;else{if(!Xi(e))throw new Error("Invalid agent ID format");const f=await fetch(`${i}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:e})});if(s!==t.generation)return;if(d=f.status,!f.ok){const y=await f.json().catch(()=>({}));throw new Error(y.error||`HTTP ${f.status}`)}l=(await f.json()).sessionToken}if(s!==t.generation)return;const m=br(l,{api:i?{baseUrl:i}:void 0,metrics:{disableClientMetrics:!0}});m.addListener(A.CONNECTION_ESTABLISHED,()=>{s===t.generation&&(t.connectionStatus.value="connected")}),m.addListener(A.VIDEO_STREAM_STARTED,()=>{s===t.generation&&(t.isStreaming.value=!0)}),m.addListener(A.AUDIO_STREAM_STARTED,()=>{}),m.addListener(A.MESSAGE_HISTORY_UPDATED,f=>{if(s!==t.generation)return;for(let E=t.prevMessageCount;E<f.length;E++){const S=f[E];t.dispatch?.(X.MESSAGE_RECEIVED,{role:S.role==="persona"?"agent":"user",content:S.content})}t.prevMessageCount=f.length;const u=Or(t,f),y=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});for(const E of u)t.messageTimes.has(E.id)||t.messageTimes.set(E.id,y);t.messages.value=u}),m.addListener(A.MESSAGE_STREAM_EVENT_RECEIVED,f=>{if(s!==t.generation)return;t.captionTimer&&(clearTimeout(t.captionTimer),t.captionTimer=null);const u=t.caption.value,y=f.role===ge.PERSONA&&u?.id===f.id?u.content+f.content:f.content;t.caption.value={id:f.id,role:f.role,content:y,at:Date.now()},f.endOfSpeech&&(t.captionTimer=window.setTimeout(()=>{t.caption.value=null,t.captionTimer=null},4e3))}),m.addListener(A.TOOL_CALL_STARTED,f=>{s===t.generation&&t.dispatch?.(X.TOOL_CALL_STARTED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,arguments:f.arguments})}),m.addListener(A.TOOL_CALL_COMPLETED,f=>{s===t.generation&&t.dispatch?.(X.TOOL_CALL_COMPLETED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,result:f.result,executionTime:f.executionTime,documentsAccessed:f.documentsAccessed})}),m.addListener(A.TOOL_CALL_FAILED,f=>{s===t.generation&&t.dispatch?.(X.TOOL_CALL_FAILED,{toolName:f.toolName,toolCallId:f.toolCallId,toolType:f.toolType,toolSubtype:f.toolSubtype,errorMessage:f.errorMessage,executionTime:f.executionTime})}),m.addListener(A.CONNECTION_CLOSED,(f,u)=>{if(s!==t.generation)return;const y=t.sessionId.value;t.connectionStatus.value="idle",t.isStreaming.value=!1,t.sessionId.value=null,t.dispatch?.(X.SESSION_ENDED,{sessionId:y??"",reason:u??f})}),m.addListener(A.SESSION_READY,f=>{s===t.generation&&(t.sessionId.value=f,t.dispatch?.(X.SESSION_STARTED,{sessionId:f}))});const p=await m.stream();if(s!==t.generation){try{await m.stopStreaming()}catch{}return}if(t.client.value=m,n&&p.length>0){const f=p.find(u=>u.getVideoTracks().length>0);f&&(n.srcObject=f)}}catch(l){if(s!==t.generation)return;console.error("[AnamWidget] Failed to start session:",l);const m=Rr(l,d);t.error.value=m,t.connectionStatus.value="error",t.client.value=null,t.dispatch?.(X.ERROR,{code:d?`HTTP_${d}`:"SESSION_ERROR",message:m})}}async function Mr(t){const e=t.sessionId.value,i=t.connectionStatus.value!=="idle";if(t.generation++,t.client.value)try{await t.client.value.stopStreaming()}catch(n){console.error("[AnamWidget] Failed to stop session:",n)}t.client.value=null,t.connectionStatus.value="idle",t.isStreaming.value=!1,t.isMuted.value=!1,t.messages.value=[],t.messageTimes.clear(),t.pendingSent=[],t.messageSeq.clear(),t.captionTimer&&clearTimeout(t.captionTimer),t.captionTimer=null,t.caption.value=null,t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaptionTimer=null,t.sentCaption.value=null,t.sessionId.value=null,t.prevMessageCount=0,i&&t.dispatch?.(X.SESSION_ENDED,{sessionId:e??"",reason:"USER_ENDED"})}function kr(t,e){if(!t.client.value||t.connectionStatus.value!=="connected")return;t.client.value.sendUserMessage(e);const i={id:`local-${t.localIdCounter++}`,content:e,role:ge.USER};t.messageSeq.set(i.id,t.seqCounter++),t.messageTimes.set(i.id,new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),t.pendingSent.push(i),t.messages.value=[...t.messages.value,i],t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaption.value={id:i.id,role:ge.USER,content:e,at:Date.now()},t.sentCaptionTimer=window.setTimeout(()=>{t.sentCaption.value=null,t.sentCaptionTimer=null},4e3),t.dispatch?.(X.MESSAGE_SENT,{content:e})}function Lr(t){t.client.value&&(t.isMuted.value?(t.client.value.unmuteInputAudio(),t.isMuted.value=!1,t.dispatch?.(X.MIC_UNMUTED,{})):(t.client.value.muteInputAudio(),t.isMuted.value=!0,t.dispatch?.(X.MIC_MUTED,{})))}function Dr(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.messageTimes.clear(),t.pendingSent=[],t.messageSeq.clear(),t.captionTimer&&clearTimeout(t.captionTimer),t.captionTimer=null,t.caption.value=null,t.sentCaptionTimer&&clearTimeout(t.sentCaptionTimer),t.sentCaptionTimer=null,t.sentCaption.value=null,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 Ur(t,e,i,n){const a=We();a.current||(a.current=Ar());const s=a.current;s.dispatch=n??null;const d=t||(i?Zi(i).personaId:void 0),l=!!d||!!i;s.isConfigured.value!==l&&(s.isConfigured.value=l);const m=e||wr;return{connectionStatus:s.connectionStatus,isStreaming:s.isStreaming,isMuted:s.isMuted,messages:s.messages,messageTimes:s.messageTimes,caption:s.caption,sentCaption:s.sentCaption,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(d){xr(s,d,m);return}if(i){const f=Zi(i).widgetConfig;f&&(typeof f.personaName=="string"&&f.personaName&&(s.personaName.value=f.personaName),typeof f.avatarImageUrl=="string"&&f.avatarImageUrl&&(s.avatarThumbnailUrl.value=f.avatarImageUrl),typeof f.avatarVideoUrl=="string"&&f.avatarVideoUrl&&(s.avatarVideoUrl.value=f.avatarVideoUrl),f.removeWatermark===!0&&(s.serverConfig.value={removeWatermark:!0})),s.isReady.value=!0;return}s.isReady.value=!0},startSession:p=>!d&&!i?(s.error.value="No agent ID or session token configured",Promise.resolve()):Nr(s,d||"",m,p,i),stopSession:()=>Mr(s),sendMessage:p=>kr(s,p),toggleMute:()=>Lr(s),cleanup:()=>Dr(s)}}function Pr(t,e,i){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:i}))}const Br='@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);max-height:var(--anam-sheet-height);border-radius:8px;flex-direction:column;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;display:flex;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-sheet[data-orientation=portrait]{flex-direction:row;align-items:stretch;width:auto}.anam-widget[data-layout=inline] .anam-sheet{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-region{aspect-ratio:3/2;background:#000;flex:none;width:100%;position:relative;overflow:hidden}.anam-sheet[data-orientation=portrait] .anam-video-region{aspect-ratio:2/3;width:auto;height:min(540px,var(--anam-sheet-height))}.anam-sheet[data-orientation=landscape] .anam-video-region{z-index:1;box-shadow:0 4px 10px #00000029}.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-overlay-idle .anam-scrim{z-index:1}.anam-cta-pill{z-index:2;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;justify-content:center;align-items:center;gap:10px;padding:12px 26px;font-family:inherit;font-size:17px;font-weight:600;transition:all .2s;display:flex;position:absolute;bottom:20px;left:50%;transform:translate(-50%);box-shadow:0 16px 38px #0000002e}.anam-cta-pill:hover{background:#ffffff29;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{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s;box-shadow:0 16px 38px #0000002e}.anam-overlay-error .anam-retry-btn:hover{background:#ffffff29}.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;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:background .15s,color .15s;display:flex;position:absolute;top:12px;right:12px;box-shadow:0 16px 38px #0000002e}.anam-close-btn:hover{color:#ffffffeb;background:#ffffff24}.anam-scrim{z-index:8;pointer-events:none;background:linear-gradient(#0000,#00000040 40%,#0000008c);height:42%;position:absolute;bottom:0;left:0;right:0}.anam-captions{z-index:9;pointer-events:none;color:#fffffff2;letter-spacing:-.01em;text-shadow:0 1px 4px #00000073;-webkit-line-clamp:3;-webkit-box-orient:vertical;font-size:15px;line-height:1.4;display:-webkit-box;position:absolute;bottom:72px;left:18px;right:18px;overflow:hidden}.anam-captions-agent{text-align:left}.anam-captions-user{text-align:right}.anam-control-bar{z-index:10;background:0 0;justify-content:center;align-items:center;gap:10px;padding:0;display:flex;position:absolute;bottom:14px;left:14px;right:14px}.anam-ctl-btn{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s,color .15s;display:flex;box-shadow:0 16px 38px #0000002e}.anam-ctl-btn:hover{color:#ffffffeb;background:#ffffff24}.anam-ctl-btn:disabled{opacity:.38;cursor:not-allowed}.anam-ctl-input-wrap{flex:1;align-items:center;min-width:0;display:flex;position:relative}.anam-ctl-input{box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffeb;background:#ffffff1a;border:1.4px solid #ffffff38;border-radius:999px;outline:none;width:100%;height:44px;padding:0 54px 0 18px;font-family:inherit;font-size:15px;transition:background .15s,border-color .15s;box-shadow:0 18px 42px #0000002e}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff24;border-color:#ffffff47}.anam-ctl-input:disabled{opacity:.38;cursor:not-allowed}.anam-ctl-send{color:#fff6;cursor:pointer;background:0 0;border:none;border-radius:999px;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:color .15s;display:flex;position:absolute;right:8px}.anam-ctl-send:not(:disabled){color:#ffffffbd}.anam-ctl-send:not(:disabled):hover{color:#ffffffeb}.anam-ctl-send:disabled{cursor:not-allowed;opacity:.38}@media(max-width:640px){.anam-control-bar{gap:8px}.anam-ctl-input{padding:0 50px 0 14px;font-size:16px}}.anam-transcript-pane{background:#f7f5f2;flex-direction:column;flex:none;height:0;transition:height .35s cubic-bezier(.32,.72,.33,1);display:flex;overflow:hidden}.anam-sheet[data-transcript=open] .anam-transcript-pane{height:min(320px,45dvh)}.anam-transcript-toggle svg{transition:transform .3s}.anam-sheet[data-transcript=open] .anam-transcript-toggle svg{transform:rotate(180deg)}.anam-transcript-rail{background:#f7f5f2;border-right:1px solid #eae5dd;flex:none;width:0;transition:width .35s cubic-bezier(.32,.72,.33,1);overflow:hidden}.anam-sheet[data-transcript=open] .anam-transcript-rail{width:300px}.anam-transcript-rail-inner{flex-direction:column;width:300px;height:100%;display:flex}.anam-transcript-head{border-bottom:1px solid #eae5dd;flex:none;justify-content:space-between;align-items:center;padding:14px 14px 10px 18px;display:flex}.anam-transcript-title{letter-spacing:.14em;text-transform:uppercase;color:#8a8378;font-size:10px;font-weight:700}.anam-transcript-collapse{color:#9a9285;cursor:pointer;background:0 0;border:none;padding:4px;transition:color .15s;display:flex}.anam-transcript-collapse:hover{color:#4a4239}.anam-transcript-tab{z-index:10;box-sizing:border-box;-webkit-backdrop-filter:blur(18px);color:#ffffffbd;cursor:pointer;background:#ffffff1a;border:1.4px solid #ffffff38;border-left:none;border-radius:0 10px 10px 0;justify-content:center;align-items:center;width:24px;height:84px;padding:0;transition:background .15s;display:flex;position:absolute;top:50%;left:0;transform:translateY(-50%);box-shadow:0 16px 38px #0000002e}.anam-transcript-tab:hover{color:#ffffffeb;background:#ffffff24}.anam-transcript-rows{overscroll-behavior:contain;flex:1;min-height:0;padding:10px 18px 8px 22px;overflow-y:auto}.anam-transcript-empty{color:#b0a89b;padding:14px 0;font-size:12.5px}.anam-transcript-row{border-left:2px solid #e3ded6;padding:10px 0 10px 16px;position:relative}.anam-transcript-row:last-child{border-left-color:#ff6200}.anam-transcript-meta{align-items:baseline;gap:8px;margin-bottom:3px;display:flex}.anam-transcript-role{letter-spacing:.1em;text-transform:uppercase;color:#6b7280;font-size:9.5px;font-weight:700}.anam-transcript-row-agent .anam-transcript-role{color:#ff6200}.anam-transcript-time{color:#b4aca0;font-variant-numeric:tabular-nums;font-size:9.5px}.anam-transcript-text{color:#33383f;overflow-wrap:anywhere;font-size:12.5px;line-height:1.5}.anam-transcript-row-user .anam-transcript-text{color:#5a616b}.anam-transcript-footer{flex:none;padding:8px 12px 12px;display:flex}.anam-transcript-footer .anam-control-bar{width:100%;position:static}.anam-transcript-footer .anam-ctl-btn{-webkit-backdrop-filter:none;box-shadow:none;color:#6b6257;background:#fff;border:1px solid #e2dcd2}.anam-transcript-footer .anam-ctl-btn:hover{color:#4a4239;background:#faf8f5}.anam-transcript-footer .anam-ctl-input{-webkit-backdrop-filter:none;box-shadow:none;color:#33383f;background:#fff;border:1px solid #e2dcd2}.anam-transcript-footer .anam-ctl-input::placeholder{color:#b0a89b}.anam-transcript-footer .anam-ctl-input:focus{background:#fff;border-color:#d0c8ba}.anam-transcript-footer .anam-ctl-send,.anam-transcript-footer .anam-ctl-send:not(:disabled){color:#b0a89b}.anam-transcript-footer .anam-ctl-send:not(:disabled):hover{color:#4a4239}.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 Fr extends Re{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){console.error("[AnamWidget] Render error:",e)}render(){return this.state.hasError?C("div",{class:"anam-overlay-error",children:C("div",{class:"anam-overlay-error-text",children:"Widget failed to load"})}):this.props.children}}function Pt(t,e){const i={...t};for(const n of Object.keys(e)){const a=e[n];a!==void 0&&(a!==null&&typeof a=="object"&&!Array.isArray(a)&&typeof i[n]=="object"&&i[n]!==null&&!Array.isArray(i[n])?i[n]=Pt(i[n],a):i[n]=a)}return i}function ct(t){if(t!==void 0)return t==="true"}function $r(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const i=ct(t["ui-mute-button"]);i!==void 0&&(e.showMuteButton=i);const n=ct(t["ui-text-input"]);n!==void 0&&(e.showTextInput=n);const a=ct(t["ui-captions"]);a!==void 0&&(e.showCaptions=a);const s=ct(t["ui-transcript"]);return s!==void 0&&(e.showTranscript=s),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const Vr=()=>C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round",children:C("path",{d:"M18 6L6 18M6 6l12 12"})}),Wr=()=>C("svg",{width:"24",height:"24",viewBox:"0 0 640 640",fill:"currentColor",children:C("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"})}),jr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),C("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),Gr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),C("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),C("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),C("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),Hr=()=>C("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),C("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),zr=()=>C("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M6 9l6 6 6-6"})}),qr=()=>C("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M15 18l-6-6 6-6"})}),Yr=()=>C("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",children:C("path",{d:"M9 18l6-6-6-6"})}),Bt=()=>C("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[C("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),C("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function Qi({session:t,agentLabel:e,rowsRef:i}){const n=t.messages.value;return C("div",{class:"anam-transcript-rows",ref:i,children:[n.length===0&&C("div",{class:"anam-transcript-empty",children:"Messages will appear here as you talk."}),n.map(a=>{const s=a.role==="persona";return C("div",{class:`anam-transcript-row ${s?"anam-transcript-row-agent":"anam-transcript-row-user"}`,children:[C("div",{class:"anam-transcript-meta",children:[C("span",{class:"anam-transcript-role",children:s?e:"You"}),C("span",{class:"anam-transcript-time",children:t.messageTimes.get(a.id)??""})]}),C("div",{class:"anam-transcript-text",children:a.content})]},a.id)})]})}function Kr({config:t,session:e,videoRef:i,avatarSrc:n,avatarVideoSrc:a,displayCta:s,agentName:d,onCollapse:l,onStop:m,dispatch:p}){const f=We(null),[u,y]=St(""),E=e.connectionStatus.value==="connected",S=e.connectionStatus.value==="connecting",T=e.connectionStatus.value==="error",I=e.isStreaming.value,w=!S&&!E&&!T,b=E||I,O=t.orientation??"landscape",k=t.showTranscript&&b,[R,ee]=St(!1),G=We(null),oe=d||"Agent",te=je(()=>{const j=!R;ee(j),p(j?X.TRANSCRIPT_OPENED:X.TRANSCRIPT_CLOSED,{})},[R,p]);Oe(()=>{b||ee(!1)},[b]),Oe(()=>{R&&G.current&&(G.current.scrollTop=G.current.scrollHeight)},[R]),Oe(()=>{const j=G.current;if(!j||!R)return;j.scrollHeight-j.scrollTop-j.clientHeight<160&&(j.scrollTop=j.scrollHeight)},[e.messages.value,R]);const se=k&&R&&O==="landscape",W=t.showCaptions?e.caption.value:null,Q=e.sentCaption.value,Ie=W&&Q?W.at>=Q.at?W:Q:W??Q,be=je(async()=>{i.current&&await e.startSession(i.current)},[e.startSession]),Ce=je(()=>{u.trim()&&(e.sendMessage(u.trim()),y(""),f.current?.focus())},[u]),Ke=je(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),Ce())},[Ce]),ne=t.showTextInput?C("div",{class:"anam-ctl-input-wrap",children:[C("input",{ref:f,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:u,onInput:j=>y(j.target.value),onKeyDown:Ke,disabled:!E}),C("button",{class:"anam-ctl-send",onClick:Ce,disabled:!E||!u.trim(),"aria-label":"Send message",children:C(Hr,{})})]}):null,dt=C("div",{class:"anam-control-bar",children:[t.showMuteButton&&C("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?C(Gr,{}):C(jr,{})}),ne,k&&O==="landscape"&&C("button",{class:"anam-ctl-btn anam-transcript-toggle",onClick:te,"aria-expanded":R,"aria-label":R?"Hide transcript":"Show transcript",children:C(zr,{})})]});return C("div",{class:"anam-sheet","data-orientation":O,"data-transcript":R?"open":"closed",children:[k&&O==="portrait"&&C("div",{class:"anam-transcript-rail",children:C("div",{class:"anam-transcript-rail-inner",children:[C("div",{class:"anam-transcript-head",children:[C("span",{class:"anam-transcript-title",children:"Transcript"}),C("button",{class:"anam-transcript-collapse",onClick:te,"aria-label":"Hide transcript",children:C(qr,{})})]}),C(Qi,{session:e,agentLabel:oe,rowsRef:G})]})}),C("div",{class:"anam-video-region",children:[C("video",{ref:i,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":I?void 0:"true"}),w&&(e.isConfigured.value?C("div",{class:"anam-overlay-idle",children:[a?C("video",{src:a,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:j=>{j.target.style.display="none"}}):null,n?C("img",{src:n,alt:"Avatar",class:a?"anam-preview-fallback":void 0}):C(Bt,{}),C("div",{class:"anam-scrim"}),C("button",{class:"anam-cta-pill",onClick:be,children:[C(Wr,{}),s]})]}):C("div",{class:"anam-overlay-unconfigured",children:[C(Bt,{}),C("span",{children:"Agent not configured"})]})),S&&C("div",{class:"anam-overlay-loading",children:[C("span",{class:"anam-spinner"}),C("span",{children:"Starting your conversation..."})]}),T&&C("div",{class:"anam-overlay-error",children:[C("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),C("button",{class:"anam-retry-btn",onClick:be,children:"Try Again"})]}),(l||m&&(E||S||I))&&C("button",{class:"anam-close-btn",onClick:l||m,"aria-label":l?"Close":"End call",children:C(Vr,{})}),b&&C(he,{children:[C("div",{class:"anam-scrim"}),Ie&&C("div",{class:`anam-captions ${Ie.role==="persona"?"anam-captions-agent":"anam-captions-user"}`,children:Ie.content}),!se&&dt,k&&O==="portrait"&&!R&&C("button",{class:"anam-transcript-tab",onClick:te,"aria-label":"Show transcript",children:C(Yr,{})})]}),!t.removeWatermark&&C("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:C("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[C("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"}),C("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),C("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"}),C("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"})]})})]}),k&&O==="landscape"&&C("div",{class:"anam-transcript-pane",children:[C(Qi,{session:e,agentLabel:oe,rowsRef:G}),se&&C("div",{class:"anam-transcript-footer",children:dt})]})]})}function Jr(t){return C(he,{children:[C("style",{children:Br}),C(Fr,{children:C(Xr,{...t})})]})}function Xr(t){const e=We(null),i=We(null),n=je((O,k)=>{const R=i.current?.getRootNode();R&&R instanceof ShadowRoot&&Pr(R.host,O,k)},[]);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 a=t["session-token"]?void 0:t["agent-id"],s=Ur(a,t["api-base-url"],t["session-token"],n);Oe(()=>()=>{s.cleanup()},[]);const d=xe(()=>$r(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["ui-transcript"],t["call-to-action"]]),l=xe(()=>{const O=s.serverConfig.value;return Pt(Pt({...wt},O??{}),d)},[s.serverConfig.value,d]),m=Mi(l.layout==="floating"?l.initialState:"expanded");Oe(()=>{l.layout==="inline"?m.value="expanded":m.value=l.initialState},[l.layout,l.initialState]),Oe(()=>{s.fetchWidgetConfig()},[a,t["api-base-url"],t["session-token"]]);const p=t["avatar-url"]||s.avatarThumbnailUrl.value||null,f=t["avatar-video-url"]||s.avatarVideoUrl.value||null,y=t["agent-name"]||s.personaName.value,E=l.callToAction===wt.callToAction&&y?`Talk to ${y}`:l.callToAction,S=xe(()=>{if(l.layout==="inline")return"";const O=Ln(l.position);return Object.entries(O).map(([k,R])=>`${k}: ${R}`).join("; ")},[l.layout,l.position]),T=l.layout==="floating",I=()=>{m.value="expanded",n(X.EXPANDED,{})},w=async()=>{s.connectionStatus.value!=="idle"&&await s.stopSession(),m.value="minimized",n(X.COLLAPSED,{})},b=T?m.value==="expanded":!0;return s.isReady.value?C("div",{ref:i,class:"anam-widget","data-layout":l.layout,"data-state":m.value,style:S,children:[T&&m.value==="minimized"&&C("button",{class:"anam-trigger",onClick:I,"aria-label":E,children:p?C("img",{src:p,alt:"Avatar"}):C(Bt,{})}),b&&C(Kr,{config:l,session:s,videoRef:e,avatarSrc:p,avatarVideoSrc:f,displayCta:E,agentName:y||null,onCollapse:T?w:null,onStop:T?null:()=>s.stopSession(),dispatch:n})]}):null}const Zr=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","ui-transcript","call-to-action","avatar-url","avatar-video-url","agent-name"];function Ft(t="anam-agent"){gn(Jr,t,[...Zr],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Ft()):Ft()),ue.DefaultConfig=wt,ue.WidgetEventNames=X,ue.registerWidget=Ft,Object.defineProperty(ue,Symbol.toStringTag,{value:"Module"})}));
|