@anam-ai/agent-widget 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ (function(le,ne){typeof exports=="object"&&typeof module<"u"?ne(exports):typeof define=="function"&&define.amd?define(["exports"],ne):(le=typeof globalThis<"u"?globalThis:le||self,ne(le.AnamAgentWidget={}))})(this,(function(le){"use strict";var ne,O,Bt,Lt,ge,Pt,Ft,$t,Gt,ht,ft,pt,Ne={},Vt=[],Ki=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,je=Array.isArray;function ee(t,e){for(var n in e)t[n]=e[n];return t}function _t(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Se(t,e,n){var o,c,a,u={};for(a in e)a=="key"?o=e[a]:a=="ref"?c=e[a]:u[a]=e[a];if(arguments.length>2&&(u.children=arguments.length>3?ne.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(a in t.defaultProps)u[a]===void 0&&(u[a]=t.defaultProps[a]);return Oe(t,u,o,c,null)}function Oe(t,e,n,o,c){var a={type:t,props:e,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:c??++Bt,__i:-1,__u:0};return c==null&&O.vnode!=null&&O.vnode(a),a}function re(t){return t.children}function ke(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function jt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return jt(t)}}function Ht(t){(!t.__d&&(t.__d=!0)&&ge.push(t)&&!He.__r++||Pt!=O.debounceRendering)&&((Pt=O.debounceRendering)||Ft)(He)}function He(){for(var t,e,n,o,c,a,u,l=1;ge.length;)ge.length>l&&ge.sort($t),t=ge.shift(),l=ge.length,t.__d&&(n=void 0,o=void 0,c=(o=(e=t).__v).__e,a=[],u=[],e.__P&&((n=ee({},o)).__v=o.__v+1,O.vnode&&O.vnode(n),Et(e.__P,n,o,e.__n,e.__P.namespaceURI,32&o.__u?[c]:null,a,c??we(o),!!(32&o.__u),u),n.__v=o.__v,n.__.__k[n.__i]=n,Kt(a,n,u),o.__e=o.__=null,n.__e!=c&&jt(n)));He.__r=0}function Wt(t,e,n,o,c,a,u,l,g,p,_){var d,S,m,y,A,w,I,b=o&&o.__k||Vt,x=e.length;for(g=Ji(n,e,b,g,x),d=0;d<x;d++)(m=n.__k[d])!=null&&(S=m.__i==-1?Ne:b[m.__i]||Ne,m.__i=d,w=Et(t,m,S,c,a,u,l,g,p,_),y=m.__e,m.ref&&S.ref!=m.ref&&(S.ref&&gt(S.ref,null,m),_.push(m.ref,m.__c||y,m)),A==null&&y!=null&&(A=y),(I=!!(4&m.__u))||S.__k===m.__k?g=zt(m,g,t,I):typeof m.type=="function"&&w!==void 0?g=w:y&&(g=y.nextSibling),m.__u&=-7);return n.__e=A,g}function Ji(t,e,n,o,c){var a,u,l,g,p,_=n.length,d=_,S=0;for(t.__k=new Array(c),a=0;a<c;a++)(u=e[a])!=null&&typeof u!="boolean"&&typeof u!="function"?(typeof u=="string"||typeof u=="number"||typeof u=="bigint"||u.constructor==String?u=t.__k[a]=Oe(null,u,null,null,null):je(u)?u=t.__k[a]=Oe(re,{children:u},null,null,null):u.constructor===void 0&&u.__b>0?u=t.__k[a]=Oe(u.type,u.props,u.key,u.ref?u.ref:null,u.__v):t.__k[a]=u,g=a+S,u.__=t,u.__b=t.__b+1,l=null,(p=u.__i=Xi(u,n,g,d))!=-1&&(d--,(l=n[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(c>_?S--:c<_&&S++),typeof u.type!="function"&&(u.__u|=4)):p!=g&&(p==g-1?S--:p==g+1?S++:(p>g?S--:S++,u.__u|=4))):t.__k[a]=null;if(d)for(a=0;a<_;a++)(l=n[a])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=we(l)),Xt(l,l));return o}function zt(t,e,n,o){var c,a;if(typeof t.type=="function"){for(c=t.__k,a=0;c&&a<c.length;a++)c[a]&&(c[a].__=t,e=zt(c[a],e,n,o));return e}t.__e!=e&&(o&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Xi(t,e,n,o){var c,a,u,l=t.key,g=t.type,p=e[n],_=p!=null&&(2&p.__u)==0;if(p===null&&l==null||_&&l==p.key&&g==p.type)return n;if(o>(_?1:0)){for(c=n-1,a=n+1;c>=0||a<e.length;)if((p=e[u=c>=0?c--:a++])!=null&&(2&p.__u)==0&&l==p.key&&g==p.type)return u}return-1}function qt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ki.test(e)?n:n+"px"}function We(t,e,n,o,c){var a,u;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof o=="string"&&(t.style.cssText=o=""),o)for(e in o)n&&e in n||qt(t.style,e,"");if(n)for(e in n)o&&n[e]==o[e]||qt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")a=e!=(e=e.replace(Gt,"$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+a]=n,n?o?n.u=o.u:(n.u=ht,t.addEventListener(e,a?pt:ft,a)):t.removeEventListener(e,a?pt:ft,a);else{if(c=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Yt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ht++;else if(e.t<n.u)return;return n(O.event?O.event(e):e)}}}function Et(t,e,n,o,c,a,u,l,g,p){var _,d,S,m,y,A,w,I,b,x,M,N,Z,W,_e,se,ae,Q=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(g=!!(32&n.__u),a=[l=e.__e=n.__e]),(_=O.__b)&&_(e);e:if(typeof Q=="function")try{if(I=e.props,b="prototype"in Q&&Q.prototype.render,x=(_=Q.contextType)&&o[_.__c],M=_?x?x.props.value:_.__:o,n.__c?w=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new Q(I,M):(e.__c=d=new ke(I,M),d.constructor=Q,d.render=Qi),x&&x.sub(d),d.state||(d.state={}),d.__n=o,S=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&Q.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ee({},d.__s)),ee(d.__s,Q.getDerivedStateFromProps(I,d.__s))),m=d.props,y=d.state,d.__v=e,S)b&&Q.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&Q.getDerivedStateFromProps==null&&I!==m&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(I,M),e.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(I,d.__s,M)===!1){for(e.__v!=n.__v&&(d.props=I,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Ee){Ee&&(Ee.__=e)}),N=0;N<d._sb.length;N++)d.__h.push(d._sb[N]);d._sb=[],d.__h.length&&u.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(I,d.__s,M),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(m,y,A)})}if(d.context=M,d.props=I,d.__P=t,d.__e=!1,Z=O.__r,W=0,b){for(d.state=d.__s,d.__d=!1,Z&&Z(e),_=d.render(d.props,d.state,d.context),_e=0;_e<d._sb.length;_e++)d.__h.push(d._sb[_e]);d._sb=[]}else do d.__d=!1,Z&&Z(e),_=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++W<25);d.state=d.__s,d.getChildContext!=null&&(o=ee(ee({},o),d.getChildContext())),b&&!S&&d.getSnapshotBeforeUpdate!=null&&(A=d.getSnapshotBeforeUpdate(m,y)),se=_,_!=null&&_.type===re&&_.key==null&&(se=Jt(_.props.children)),l=Wt(t,je(se)?se:[se],e,n,o,c,a,u,l,g,p),d.base=e.__e,e.__u&=-161,d.__h.length&&u.push(d),w&&(d.__E=d.__=null)}catch(Ee){if(e.__v=null,g||a!=null)if(Ee.then){for(e.__u|=g?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;a[a.indexOf(l)]=null,e.__e=l}else{for(ae=a.length;ae--;)_t(a[ae]);mt(e)}else e.__e=n.__e,e.__k=n.__k,Ee.then||mt(e);O.__e(Ee,e,n)}else a==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Zi(n.__e,e,n,o,c,a,u,g,p);return(_=O.diffed)&&_(e),128&e.__u?void 0:l}function mt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(mt)}function Kt(t,e,n){for(var o=0;o<n.length;o++)gt(n[o],n[++o],n[++o]);O.__c&&O.__c(e,t),t.some(function(c){try{t=c.__h,c.__h=[],t.some(function(a){a.call(c)})}catch(a){O.__e(a,c.__v)}})}function Jt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:je(t)?t.map(Jt):ee({},t)}function Zi(t,e,n,o,c,a,u,l,g){var p,_,d,S,m,y,A,w=n.props||Ne,I=e.props,b=e.type;if(b=="svg"?c="http://www.w3.org/2000/svg":b=="math"?c="http://www.w3.org/1998/Math/MathML":c||(c="http://www.w3.org/1999/xhtml"),a!=null){for(p=0;p<a.length;p++)if((m=a[p])&&"setAttribute"in m==!!b&&(b?m.localName==b:m.nodeType==3)){t=m,a[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(I);t=document.createElementNS(c,b,I.is&&I),l&&(O.__m&&O.__m(e,a),l=!1),a=null}if(b==null)w===I||l&&t.data==I||(t.data=I);else{if(a=a&&ne.call(t.childNodes),!l&&a!=null)for(w={},p=0;p<t.attributes.length;p++)w[(m=t.attributes[p]).name]=m.value;for(p in w)if(m=w[p],p!="children"){if(p=="dangerouslySetInnerHTML")d=m;else if(!(p in I)){if(p=="value"&&"defaultValue"in I||p=="checked"&&"defaultChecked"in I)continue;We(t,p,null,m,c)}}for(p in I)m=I[p],p=="children"?S=m:p=="dangerouslySetInnerHTML"?_=m:p=="value"?y=m:p=="checked"?A=m:l&&typeof m!="function"||w[p]===m||We(t,p,m,w[p],c);if(_)l||d&&(_.__html==d.__html||_.__html==t.innerHTML)||(t.innerHTML=_.__html),e.__k=[];else if(d&&(t.innerHTML=""),Wt(e.type=="template"?t.content:t,je(S)?S:[S],e,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":c,a,u,a?a[0]:n.__k&&we(n,0),l,g),a!=null)for(p=a.length;p--;)_t(a[p]);l||(p="value",b=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[p]||b=="progress"&&!y||b=="option"&&y!=w[p])&&We(t,p,y,w[p],c),p="checked",A!=null&&A!=t[p]&&We(t,p,A,w[p],c))}return t}function gt(t,e,n){try{if(typeof t=="function"){var o=typeof t.__u=="function";o&&t.__u(),o&&e==null||(t.__u=t(e))}else t.current=e}catch(c){O.__e(c,n)}}function Xt(t,e,n){var o,c;if(O.unmount&&O.unmount(t),(o=t.ref)&&(o.current&&o.current!=t.__e||gt(o,null,e)),(o=t.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(a){O.__e(a,e)}o.base=o.__P=null}if(o=t.__k)for(c=0;c<o.length;c++)o[c]&&Xt(o[c],e,n||typeof t.type!="function");n||_t(t.__e),t.__c=t.__=t.__e=void 0}function Qi(t,e,n){return this.constructor(t,n)}function ze(t,e,n){var o,c,a,u;e==document&&(e=document.documentElement),O.__&&O.__(t,e),c=(o=typeof n=="function")?null:n&&n.__k||e.__k,a=[],u=[],Et(e,t=(!o&&n||e).__k=Se(re,null,[t]),c||Ne,Ne,e.namespaceURI,!o&&n?[n]:c?null:e.firstChild?ne.call(e.childNodes):null,a,!o&&n?n:c?c.__e:e.firstChild,o,u),Kt(a,t,u)}function Zt(t,e){ze(t,e,Zt)}function Qt(t,e,n){var o,c,a,u,l=ee({},t.props);for(a in t.type&&t.type.defaultProps&&(u=t.type.defaultProps),e)a=="key"?o=e[a]:a=="ref"?c=e[a]:l[a]=e[a]===void 0&&u!=null?u[a]:e[a];return arguments.length>2&&(l.children=arguments.length>3?ne.call(arguments,2):n),Oe(t.type,l,o||t.key,c||t.ref,null)}ne=Vt.slice,O={__e:function(t,e,n,o){for(var c,a,u;e=e.__;)if((c=e.__c)&&!c.__)try{if((a=c.constructor)&&a.getDerivedStateFromError!=null&&(c.setState(a.getDerivedStateFromError(t)),u=c.__d),c.componentDidCatch!=null&&(c.componentDidCatch(t,o||{}),u=c.__d),u)return c.__E=c}catch(l){t=l}throw t}},Bt=0,Lt=function(t){return t!=null&&t.constructor===void 0},ke.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ee({},this.state),typeof t=="function"&&(t=t(ee({},n),this.props)),t&&ee(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ht(this))},ke.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ht(this))},ke.prototype.render=re,ge=[],Ft=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$t=function(t,e){return t.__v.__b-e.__v.__b},He.__r=0,Gt=/(PointerCapture)$|Capture$/i,ht=0,ft=Yt(!1),pt=Yt(!0);function qe(){return qe=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},qe.apply(this,arguments)}function ei(t,e){if(t==null)return{};var n,o,c={},a=Object.keys(t);for(o=0;o<a.length;o++)e.indexOf(n=a[o])>=0||(c[n]=t[n]);return c}var en=["context","children"],tn=["useFragment"];function nn(t,e,n,o){function c(){var a,u=Reflect.construct(HTMLElement,[],c);return u._vdomComponent=t,o&&o.shadow?(u._root=u.attachShadow({mode:o.mode||"open",serializable:(a=o.serializable)!=null&&a}),o.adoptedStyleSheets&&(u._root.adoptedStyleSheets=o.adoptedStyleSheets)):u._root=u,u}return(c.prototype=Object.create(HTMLElement.prototype)).constructor=c,c.prototype.connectedCallback=function(){on.call(this,o)},c.prototype.attributeChangedCallback=sn,c.prototype.disconnectedCallback=an,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),c.observedAttributes=n,t.formAssociated&&(c.formAssociated=!0),n.forEach(function(a){Object.defineProperty(c.prototype,a,{get:function(){return this._vdom?this._vdom.props[a]:this._props[a]},set:function(u){this._vdom?this.attributeChangedCallback(a,null,u):(this._props||(this._props={}),this._props[a]=u);var l=typeof u;u!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(a,u)}})}),customElements.define(e||t.tagName||t.displayName||t.name,c),c}function rn(t){this.getChildContext=function(){return t.context};var e=t.children,n=ei(t,en);return Qt(e,n)}function on(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Se(rn,qe({},this._props,{context:e.detail.context}),ni(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?Zt:ze)(this._vdom,this._root)}function ti(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function sn(t,e,n){if(this._vdom){var o={};o[t]=n=n??void 0,o[ti(t)]=n,this._vdom=Qt(this._vdom,o),ze(this._vdom,this._root)}}function an(){ze(this._vdom=null,this._root)}function ii(t,e){var n=this,o=t.useFragment,c=ei(t,tn);return Se(o?re:"slot",qe({},c,{ref:function(a){a?(n.ref=a,n._listener||(n._listener=function(u){u.stopPropagation(),u.detail.context=e},a.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function ni(t,e,n){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var o=[],c={},a=0,u=t.attributes,l=t.childNodes;for(a=u.length;a--;)u[a].name!=="slot"&&(c[u[a].name]=u[a].value,c[ti(u[a].name)]=u[a].value);for(a=l.length;a--;){var g=ni(l[a],null,n),p=l[a].slot;p?c[p]=Se(ii,{name:p},g):o[a]=g}var _=!(!n||!n.shadow),d=e?Se(ii,{useFragment:!_},o):o;return!_&&e&&(t.innerHTML=""),Se(e||t.nodeName.toLowerCase(),c,d)}var ln=0;function C(t,e,n,o,c,a){e||(e={});var u,l,g=e;if("ref"in g)for(l in g={},e)l=="ref"?u=e[l]:g[l]=e[l];var p={type:t,props:g,key:n,ref:u,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ln,__i:-1,__u:0,__source:c,__self:a};if(typeof t=="function"&&(u=t.defaultProps))for(l in u)g[l]===void 0&&(g[l]=u[l]);return O.vnode&&O.vnode(p),p}var De,P,vt,ri,Me=0,oi=[],F=O,si=F.__b,ai=F.__r,li=F.diffed,ci=F.__c,ui=F.unmount,di=F.__;function yt(t,e){F.__h&&F.__h(P,t,Me||e),Me=0;var n=P.__H||(P.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ye(t){return Me=1,cn(pi,t)}function cn(t,e,n){var o=yt(De++,2);if(o.t=t,!o.__c&&(o.__=[pi(void 0,e),function(l){var g=o.__N?o.__N[0]:o.__[0],p=o.t(g,l);g!==p&&(o.__N=[p,o.__[1]],o.__c.setState({}))}],o.__c=P,!P.__f)){var c=function(l,g,p){if(!o.__c.__H)return!0;var _=o.__c.__H.__.filter(function(S){return!!S.__c});if(_.every(function(S){return!S.__N}))return!a||a.call(this,l,g,p);var d=o.__c.props!==l;return _.forEach(function(S){if(S.__N){var m=S.__[0];S.__=S.__N,S.__N=void 0,m!==S.__[0]&&(d=!0)}}),a&&a.call(this,l,g,p)||d};P.__f=!0;var a=P.shouldComponentUpdate,u=P.componentWillUpdate;P.componentWillUpdate=function(l,g,p){if(this.__e){var _=a;a=void 0,c(l,g,p),a=_}u&&u.call(this,l,g,p)},P.shouldComponentUpdate=c}return o.__N||o.__}function St(t,e){var n=yt(De++,3);!F.__s&&fi(n.__H,e)&&(n.__=t,n.u=e,P.__H.__h.push(n))}function Ke(t){return Me=5,Ce(function(){return{current:t}},[])}function Ce(t,e){var n=yt(De++,7);return fi(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Je(t,e){return Me=8,Ce(function(){return t},e)}function un(){for(var t;t=oi.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Xe),t.__H.__h.forEach(wt),t.__H.__h=[]}catch(e){t.__H.__h=[],F.__e(e,t.__v)}}F.__b=function(t){P=null,si&&si(t)},F.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),di&&di(t,e)},F.__r=function(t){ai&&ai(t),De=0;var e=(P=t.__c).__H;e&&(vt===P?(e.__h=[],P.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Xe),e.__h.forEach(wt),e.__h=[],De=0)),vt=P},F.diffed=function(t){li&&li(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(oi.push(e)!==1&&ri===F.requestAnimationFrame||((ri=F.requestAnimationFrame)||dn)(un)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),vt=P=null},F.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Xe),n.__h=n.__h.filter(function(o){return!o.__||wt(o)})}catch(o){e.some(function(c){c.__h&&(c.__h=[])}),e=[],F.__e(o,n.__v)}}),ci&&ci(t,e)},F.unmount=function(t){ui&&ui(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(o){try{Xe(o)}catch(c){e=c}}),n.__H=void 0,e&&F.__e(e,n.__v))};var hi=typeof requestAnimationFrame=="function";function dn(t){var e,n=function(){clearTimeout(o),hi&&cancelAnimationFrame(e),setTimeout(t)},o=setTimeout(n,35);hi&&(e=requestAnimationFrame(n))}function Xe(t){var e=P,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),P=e}function wt(t){var e=P;t.__c=t.__(),P=e}function fi(t,e){return!t||t.length!==e.length||e.some(function(n,o){return n!==t[o]})}function pi(t,e){return typeof e=="function"?e(t):e}var hn=Symbol.for("preact-signals");function Ze(){if(ce>1)ce--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,Ct++;n!==void 0;){var o=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&mi(n))try{n.c()}catch(c){e||(t=c,e=!0)}n=o}}if(Ct=0,ce--,e)throw t}}function fn(t){if(ce>0)return t();ce++;try{return t()}finally{Ze()}}var k=void 0;function _i(t){var e=k;k=void 0;try{return t()}finally{k=e}}var Ue=void 0,ce=0,Ct=0,Qe=0;function Ei(t){if(k!==void 0){var e=t.n;if(e===void 0||e.t!==k)return e={i:0,S:t,p:k.s,n:void 0,t:k,e:void 0,x:void 0,r:e},k.s!==void 0&&(k.s.n=e),k.s=e,t.n=e,32&k.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=k.s,e.n=void 0,k.s.n=e,k.s=e),e}}function V(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}V.prototype.brand=hn,V.prototype.h=function(){return!0},V.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:_i(function(){var o;(o=e.W)==null||o.call(e)}))},V.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,o=t.x;n!==void 0&&(n.x=o,t.e=void 0),o!==void 0&&(o.e=n,t.x=void 0),t===this.t&&(this.t=o,o===void 0&&_i(function(){var c;(c=e.Z)==null||c.call(e)}))}},V.prototype.subscribe=function(t){var e=this;return Be(function(){var n=e.value,o=k;k=void 0;try{t(n)}finally{k=o}},{name:"sub"})},V.prototype.valueOf=function(){return this.value},V.prototype.toString=function(){return this.value+""},V.prototype.toJSON=function(){return this.value},V.prototype.peek=function(){var t=k;k=void 0;try{return this.value}finally{k=t}},Object.defineProperty(V.prototype,"value",{get:function(){var t=Ei(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(Ct>100)throw new Error("Cycle detected");this.v=t,this.i++,Qe++,ce++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Ze()}}}});function q(t,e){return new V(t,e)}function mi(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 gi(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function vi(t){for(var e=t.s,n=void 0;e!==void 0;){var o=e.p;e.i===-1?(e.S.U(e),o!==void 0&&(o.n=e.n),e.n!==void 0&&(e.n.p=o)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=o}t.s=n}function ve(t,e){V.call(this,void 0),this.x=t,this.s=void 0,this.g=Qe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ve.prototype=new V,ve.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Qe))return!0;if(this.g=Qe,this.f|=1,this.i>0&&!mi(this))return this.f&=-2,!0;var t=k;try{gi(this),k=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return k=t,vi(this),this.f&=-2,!0},ve.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)}V.prototype.S.call(this,t)},ve.prototype.U=function(t){if(this.t!==void 0&&(V.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)}},ve.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(ve.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Ei(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function yi(t,e){return new ve(t,e)}function Si(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ce++;var n=k;k=void 0;try{e()}catch(o){throw t.f&=-2,t.f|=8,It(t),o}finally{k=n,Ze()}}}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,Si(t)}function pn(t){if(k!==this)throw new Error("Out-of-order effect");vi(this),k=t,this.f&=-2,8&this.f&&It(this),Ze()}function Ie(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ie.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ie.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Si(this),gi(this),ce++;var t=k;return k=this,pn.bind(this,t)},Ie.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ie.prototype.d=function(){this.f|=8,1&this.f||It(this)},Ie.prototype.dispose=function(){this.d()};function Be(t,e){var n=new Ie(t,e);try{n.c()}catch(c){throw n.d(),c}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var wi,bt,_n=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Ci=[];Be(function(){wi=this.N})();function be(t,e){O[t]=e.bind(null,O[t]||function(){})}function et(t){bt&&bt(),bt=t&&t.S()}function Ii(t){var e=this,n=t.data,o=bi(n);o.value=n;var c=Ce(function(){for(var l=e,g=e.__v;g=g.__;)if(g.__c){g.__c.__$f|=4;break}var p=yi(function(){var m=o.value.value;return m===0?0:m===!0?"":m||""}),_=yi(function(){return!Array.isArray(p.value)&&!Lt(p.value)}),d=Be(function(){if(this.N=Ai,_.value){var m=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=m)}}),S=e.__$u.d;return e.__$u.d=function(){d(),S.call(this)},[_,p]},[]),a=c[0],u=c[1];return a.value?u.peek():u.value}Ii.displayName="ReactiveTextNode",Object.defineProperties(V.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ii},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),be("__b",function(t,e){if(typeof e.type=="string"){var n,o=e.props;for(var c in o)if(c!=="children"){var a=o[c];a instanceof V&&(n||(e.__np=n={}),n[c]=a,o[c]=a.peek())}}t(e)}),be("__r",function(t,e){if(e.type!==re){et();var n,o=e.__c;o&&(o.__$f&=-2,(n=o.__$u)===void 0&&(o.__$u=n=(function(c,a){var u;return Be(function(){u=this},{name:a}),u.c=c,u})(function(){var c;_n&&((c=n.y)==null||c.call(n)),o.__$f|=1,o.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),et(n)}t(e)}),be("__e",function(t,e,n,o){et(),t(e,n,o)}),be("diffed",function(t,e){et();var n;if(typeof e.type=="string"&&(n=e.__e)){var o=e.__np,c=e.props;if(o){var a=n.U;if(a)for(var u in a){var l=a[u];l!==void 0&&!(u in o)&&(l.d(),a[u]=void 0)}else a={},n.U=a;for(var g in o){var p=a[g],_=o[g];p===void 0?(p=En(n,g,_,c),a[g]=p):p.o(_,c)}}}t(e)});function En(t,e,n,o){var c=e in t&&t.ownerSVGElement===void 0,a=q(n);return{o:function(u,l){a.value=u,o=l},d:Be(function(){this.N=Ai;var u=a.value.value;o[e]!==u&&(o[e]=u,c?t[e]=u:u!=null&&(u!==!1||e[4]==="-")?t.setAttribute(e,u):t.removeAttribute(e))})}}be("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var c in o){var a=o[c];a&&a.d()}}}}else{var u=e.__c;if(u){var l=u.__$u;l&&(u.__$u=void 0,l.d())}}t(e)}),be("__h",function(t,e,n,o){(o<3||o===9)&&(e.__$f|=2),t(e,n,o)}),ke.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var c in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(o||a||4&this.__$f)||1&this.__$f)return!0}else if(!(o||4&this.__$f)||3&this.__$f)return!0;for(var u in t)if(u!=="__source"&&t[u]!==this.props[u])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function bi(t,e){return Ye(function(){return q(t,e)})[0]}var mn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function gn(){fn(function(){for(var t;t=Ci.shift();)wi.call(t)})}function Ai(){Ci.push(this)===1&&(O.requestAnimationFrame||mn)(gn)}const Le={mode:"orb",layout:"fixed",position:"bottom-right",styles:{backgroundColor:"#ffffff",textColor:"#1f2937"},showTranscript:!0,showTextInput:!0,showMuteButton:!0,interactionMode:"both",startExpanded:!1,textContents:{callToAction:"Talk to our assistant",connecting:"Connecting...",listening:"Listening...",speaking:"Speaking...",endCall:"End",sendMessage:"Send",placeholder:"Type a message..."}},tt={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}};function vn(t){if(tt[t])return tt[t];const e=t.match(/^\[(.+)\]$/);if(!e)return tt["bottom-right"];const n={};for(const o of e[1].split(",")){const c=o.trim(),a=c.lastIndexOf("-");if(a<=0)continue;const u=c.slice(0,a),l=c.slice(a+1);n[u]=/^\d+$/.test(l)?`${l}px`:l}return Object.keys(n).length>0?n:tt["bottom-right"]}const yn=["agent-id","api-base-url","mode","layout","position","variant","placement","background-color","text-color","show-transcript","show-text-input","show-mute-button","interaction-mode","start-expanded","text-call-to-action","text-connecting","text-listening","text-speaking","text-end-call","override-config"];function it(t){return t===void 0?!1:t==="true"||t===""}var At={},Pe={},Ti;function Sn(){if(Ti)return Pe;Ti=1,Pe.byteLength=l,Pe.toByteArray=p,Pe.fromByteArray=S;for(var t=[],e=[],n=typeof Uint8Array<"u"?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,a=o.length;c<a;++c)t[c]=o[c],e[o.charCodeAt(c)]=c;e[45]=62,e[95]=63;function u(m){var y=m.length;if(y%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var A=m.indexOf("=");A===-1&&(A=y);var w=A===y?0:4-A%4;return[A,w]}function l(m){var y=u(m),A=y[0],w=y[1];return(A+w)*3/4-w}function g(m,y,A){return(y+A)*3/4-A}function p(m){var y,A=u(m),w=A[0],I=A[1],b=new n(g(m,w,I)),x=0,M=I>0?w-4:w,N;for(N=0;N<M;N+=4)y=e[m.charCodeAt(N)]<<18|e[m.charCodeAt(N+1)]<<12|e[m.charCodeAt(N+2)]<<6|e[m.charCodeAt(N+3)],b[x++]=y>>16&255,b[x++]=y>>8&255,b[x++]=y&255;return I===2&&(y=e[m.charCodeAt(N)]<<2|e[m.charCodeAt(N+1)]>>4,b[x++]=y&255),I===1&&(y=e[m.charCodeAt(N)]<<10|e[m.charCodeAt(N+1)]<<4|e[m.charCodeAt(N+2)]>>2,b[x++]=y>>8&255,b[x++]=y&255),b}function _(m){return t[m>>18&63]+t[m>>12&63]+t[m>>6&63]+t[m&63]}function d(m,y,A){for(var w,I=[],b=y;b<A;b+=3)w=(m[b]<<16&16711680)+(m[b+1]<<8&65280)+(m[b+2]&255),I.push(_(w));return I.join("")}function S(m){for(var y,A=m.length,w=A%3,I=[],b=16383,x=0,M=A-w;x<M;x+=b)I.push(d(m,x,x+b>M?M:x+b));return w===1?(y=m[A-1],I.push(t[y>>2]+t[y<<4&63]+"==")):w===2&&(y=(m[A-2]<<8)+m[A-1],I.push(t[y>>10]+t[y>>4&63]+t[y<<2&63]+"=")),I.join("")}return Pe}var nt={};var Ri;function wn(){return Ri||(Ri=1,nt.read=function(t,e,n,o,c){var a,u,l=c*8-o-1,g=(1<<l)-1,p=g>>1,_=-7,d=n?c-1:0,S=n?-1:1,m=t[e+d];for(d+=S,a=m&(1<<-_)-1,m>>=-_,_+=l;_>0;a=a*256+t[e+d],d+=S,_-=8);for(u=a&(1<<-_)-1,a>>=-_,_+=o;_>0;u=u*256+t[e+d],d+=S,_-=8);if(a===0)a=1-p;else{if(a===g)return u?NaN:(m?-1:1)*(1/0);u=u+Math.pow(2,o),a=a-p}return(m?-1:1)*u*Math.pow(2,a-o)},nt.write=function(t,e,n,o,c,a){var u,l,g,p=a*8-c-1,_=(1<<p)-1,d=_>>1,S=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=o?0:a-1,y=o?1:-1,A=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,u=_):(u=Math.floor(Math.log(e)/Math.LN2),e*(g=Math.pow(2,-u))<1&&(u--,g*=2),u+d>=1?e+=S/g:e+=S*Math.pow(2,1-d),e*g>=2&&(u++,g/=2),u+d>=_?(l=0,u=_):u+d>=1?(l=(e*g-1)*Math.pow(2,c),u=u+d):(l=e*Math.pow(2,d-1)*Math.pow(2,c),u=0));c>=8;t[n+m]=l&255,m+=y,l/=256,c-=8);for(u=u<<c|l,p+=c;p>0;t[n+m]=u&255,m+=y,u/=256,p-=8);t[n+m-y]|=A*128}),nt}var xi;function Cn(){return xi||(xi=1,(function(t){const e=Sn(),n=wn(),o=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=b,t.INSPECT_MAX_BYTES=50;const c=2147483647;t.kMaxLength=c,l.TYPED_ARRAY_SUPPORT=a(),!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 a(){try{const s=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(s,i),s.foo()===42}catch{return!1}}Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}});function u(s){if(s>c)throw new RangeError('The value "'+s+'" is invalid for option "size"');const i=new Uint8Array(s);return Object.setPrototypeOf(i,l.prototype),i}function l(s,i,r){if(typeof s=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(s)}return g(s,i,r)}l.poolSize=8192;function g(s,i,r){if(typeof s=="string")return S(s,i);if(ArrayBuffer.isView(s))return y(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ie(s,ArrayBuffer)||s&&ie(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ie(s,SharedArrayBuffer)||s&&ie(s.buffer,SharedArrayBuffer)))return A(s,i,r);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=s.valueOf&&s.valueOf();if(h!=null&&h!==s)return l.from(h,i,r);const f=w(s);if(f)return f;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return l.from(s[Symbol.toPrimitive]("string"),i,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}l.from=function(s,i,r){return g(s,i,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function _(s,i,r){return p(s),s<=0?u(s):i!==void 0?typeof r=="string"?u(s).fill(i,r):u(s).fill(i):u(s)}l.alloc=function(s,i,r){return _(s,i,r)};function d(s){return p(s),u(s<0?0:I(s)|0)}l.allocUnsafe=function(s){return d(s)},l.allocUnsafeSlow=function(s){return d(s)};function S(s,i){if((typeof i!="string"||i==="")&&(i="utf8"),!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const r=x(s,i)|0;let h=u(r);const f=h.write(s,i);return f!==r&&(h=h.slice(0,f)),h}function m(s){const i=s.length<0?0:I(s.length)|0,r=u(i);for(let h=0;h<i;h+=1)r[h]=s[h]&255;return r}function y(s){if(ie(s,Uint8Array)){const i=new Uint8Array(s);return A(i.buffer,i.byteOffset,i.byteLength)}return m(s)}function A(s,i,r){if(i<0||s.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<i+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return i===void 0&&r===void 0?h=new Uint8Array(s):r===void 0?h=new Uint8Array(s,i):h=new Uint8Array(s,i,r),Object.setPrototypeOf(h,l.prototype),h}function w(s){if(l.isBuffer(s)){const i=I(s.length)|0,r=u(i);return r.length===0||s.copy(r,0,0,i),r}if(s.length!==void 0)return typeof s.length!="number"||Ut(s.length)?u(0):m(s);if(s.type==="Buffer"&&Array.isArray(s.data))return m(s.data)}function I(s){if(s>=c)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+c.toString(16)+" bytes");return s|0}function b(s){return+s!=s&&(s=0),l.alloc(+s)}l.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==l.prototype},l.compare=function(i,r){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),ie(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(i)||!l.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===r)return 0;let h=i.length,f=r.length;for(let E=0,v=Math.min(h,f);E<v;++E)if(i[E]!==r[E]){h=i[E],f=r[E];break}return h<f?-1:f<h?1:0},l.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(i,r){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return l.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<i.length;++h)r+=i[h].length;const f=l.allocUnsafe(r);let E=0;for(h=0;h<i.length;++h){let v=i[h];if(ie(v,Uint8Array))E+v.length>f.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(f,E)):Uint8Array.prototype.set.call(f,v,E);else if(l.isBuffer(v))v.copy(f,E);else throw new TypeError('"list" argument must be an Array of Buffers');E+=v.length}return f};function x(s,i){if(l.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ie(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const r=s.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let f=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Mt(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Yi(s).length;default:if(f)return h?-1:Mt(s).length;i=(""+i).toLowerCase(),f=!0}}l.byteLength=x;function M(s,i,r){let h=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,i>>>=0,r<=i))return"";for(s||(s="utf8");;)switch(s){case"hex":return Sr(this,i,r);case"utf8":case"utf-8":return Fi(this,i,r);case"ascii":return vr(this,i,r);case"latin1":case"binary":return yr(this,i,r);case"base64":return mr(this,i,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return wr(this,i,r);default:if(h)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function N(s,i,r){const h=s[i];s[i]=s[r],s[r]=h}l.prototype.swap16=function(){const i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<i;r+=2)N(this,r,r+1);return this},l.prototype.swap32=function(){const i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<i;r+=4)N(this,r,r+3),N(this,r+1,r+2);return this},l.prototype.swap64=function(){const i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<i;r+=8)N(this,r,r+7),N(this,r+1,r+6),N(this,r+2,r+5),N(this,r+3,r+4);return this},l.prototype.toString=function(){const i=this.length;return i===0?"":arguments.length===0?Fi(this,0,i):M.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(i){if(!l.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:l.compare(this,i)===0},l.prototype.inspect=function(){let i="";const r=t.INSPECT_MAX_BYTES;return i=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(i+=" ... "),"<Buffer "+i+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(i,r,h,f,E){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),!l.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(r===void 0&&(r=0),h===void 0&&(h=i?i.length:0),f===void 0&&(f=0),E===void 0&&(E=this.length),r<0||h>i.length||f<0||E>this.length)throw new RangeError("out of range index");if(f>=E&&r>=h)return 0;if(f>=E)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,f>>>=0,E>>>=0,this===i)return 0;let v=E-f,T=h-r;const B=Math.min(v,T),U=this.slice(f,E),L=i.slice(r,h);for(let D=0;D<B;++D)if(U[D]!==L[D]){v=U[D],T=L[D];break}return v<T?-1:T<v?1:0};function Z(s,i,r,h,f){if(s.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Ut(r)&&(r=f?0:s.length-1),r<0&&(r=s.length+r),r>=s.length){if(f)return-1;r=s.length-1}else if(r<0)if(f)r=0;else return-1;if(typeof i=="string"&&(i=l.from(i,h)),l.isBuffer(i))return i.length===0?-1:W(s,i,r,h,f);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?f?Uint8Array.prototype.indexOf.call(s,i,r):Uint8Array.prototype.lastIndexOf.call(s,i,r):W(s,[i],r,h,f);throw new TypeError("val must be string, number or Buffer")}function W(s,i,r,h,f){let E=1,v=s.length,T=i.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(s.length<2||i.length<2)return-1;E=2,v/=2,T/=2,r/=2}function B(L,D){return E===1?L[D]:L.readUInt16BE(D*E)}let U;if(f){let L=-1;for(U=r;U<v;U++)if(B(s,U)===B(i,L===-1?0:U-L)){if(L===-1&&(L=U),U-L+1===T)return L*E}else L!==-1&&(U-=U-L),L=-1}else for(r+T>v&&(r=v-T),U=r;U>=0;U--){let L=!0;for(let D=0;D<T;D++)if(B(s,U+D)!==B(i,D)){L=!1;break}if(L)return U}return-1}l.prototype.includes=function(i,r,h){return this.indexOf(i,r,h)!==-1},l.prototype.indexOf=function(i,r,h){return Z(this,i,r,h,!0)},l.prototype.lastIndexOf=function(i,r,h){return Z(this,i,r,h,!1)};function _e(s,i,r,h){r=Number(r)||0;const f=s.length-r;h?(h=Number(h),h>f&&(h=f)):h=f;const E=i.length;h>E/2&&(h=E/2);let v;for(v=0;v<h;++v){const T=parseInt(i.substr(v*2,2),16);if(Ut(T))return v;s[r+v]=T}return v}function se(s,i,r,h){return dt(Mt(i,s.length-r),s,r,h)}function ae(s,i,r,h){return dt(Ar(i),s,r,h)}function Q(s,i,r,h){return dt(Yi(i),s,r,h)}function Ee(s,i,r,h){return dt(Tr(i,s.length-r),s,r,h)}l.prototype.write=function(i,r,h,f){if(r===void 0)f="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")f=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,f===void 0&&(f="utf8")):(f=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const E=this.length-r;if((h===void 0||h>E)&&(h=E),i.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");f||(f="utf8");let v=!1;for(;;)switch(f){case"hex":return _e(this,i,r,h);case"utf8":case"utf-8":return se(this,i,r,h);case"ascii":case"latin1":case"binary":return ae(this,i,r,h);case"base64":return Q(this,i,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ee(this,i,r,h);default:if(v)throw new TypeError("Unknown encoding: "+f);f=(""+f).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function mr(s,i,r){return i===0&&r===s.length?e.fromByteArray(s):e.fromByteArray(s.slice(i,r))}function Fi(s,i,r){r=Math.min(s.length,r);const h=[];let f=i;for(;f<r;){const E=s[f];let v=null,T=E>239?4:E>223?3:E>191?2:1;if(f+T<=r){let B,U,L,D;switch(T){case 1:E<128&&(v=E);break;case 2:B=s[f+1],(B&192)===128&&(D=(E&31)<<6|B&63,D>127&&(v=D));break;case 3:B=s[f+1],U=s[f+2],(B&192)===128&&(U&192)===128&&(D=(E&15)<<12|(B&63)<<6|U&63,D>2047&&(D<55296||D>57343)&&(v=D));break;case 4:B=s[f+1],U=s[f+2],L=s[f+3],(B&192)===128&&(U&192)===128&&(L&192)===128&&(D=(E&15)<<18|(B&63)<<12|(U&63)<<6|L&63,D>65535&&D<1114112&&(v=D))}}v===null?(v=65533,T=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),f+=T}return gr(h)}const $i=4096;function gr(s){const i=s.length;if(i<=$i)return String.fromCharCode.apply(String,s);let r="",h=0;for(;h<i;)r+=String.fromCharCode.apply(String,s.slice(h,h+=$i));return r}function vr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]&127);return h}function yr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]);return h}function Sr(s,i,r){const h=s.length;(!i||i<0)&&(i=0),(!r||r<0||r>h)&&(r=h);let f="";for(let E=i;E<r;++E)f+=Rr[s[E]];return f}function wr(s,i,r){const h=s.slice(i,r);let f="";for(let E=0;E<h.length-1;E+=2)f+=String.fromCharCode(h[E]+h[E+1]*256);return f}l.prototype.slice=function(i,r){const h=this.length;i=~~i,r=r===void 0?h:~~r,i<0?(i+=h,i<0&&(i=0)):i>h&&(i=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<i&&(r=i);const f=this.subarray(i,r);return Object.setPrototypeOf(f,l.prototype),f};function G(s,i,r){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+i>r)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return f},l.prototype.readUintBE=l.prototype.readUIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i+--r],E=1;for(;r>0&&(E*=256);)f+=this[i+--r]*E;return f},l.prototype.readUint8=l.prototype.readUInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]|this[i+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]<<8|this[i+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])},l.prototype.readBigUInt64LE=me(function(i){i=i>>>0,xe(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,E=this[++i]+this[++i]*2**8+this[++i]*2**16+h*2**24;return BigInt(f)+(BigInt(E)<<BigInt(32))}),l.prototype.readBigUInt64BE=me(function(i){i=i>>>0,xe(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],E=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h;return(BigInt(f)<<BigInt(32))+BigInt(E)}),l.prototype.readIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return E*=128,f>=E&&(f-=Math.pow(2,8*r)),f},l.prototype.readIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=r,E=1,v=this[i+--f];for(;f>0&&(E*=256);)v+=this[i+--f]*E;return E*=128,v>=E&&(v-=Math.pow(2,8*r)),v},l.prototype.readInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]},l.prototype.readInt16LE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i]|this[i+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i+1]|this[i]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24},l.prototype.readInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]},l.prototype.readBigInt64LE=me(function(i){i=i>>>0,xe(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(h<<24);return(BigInt(f)<<BigInt(32))+BigInt(r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)}),l.prototype.readBigInt64BE=me(function(i){i=i>>>0,xe(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=(r<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(f)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h)}),l.prototype.readFloatLE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!0,23,4)},l.prototype.readFloatBE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!1,23,4)},l.prototype.readDoubleLE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!0,52,8)},l.prototype.readDoubleBE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!1,52,8)};function Y(s,i,r,h,f,E){if(!l.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>f||i<E)throw new RangeError('"value" argument is out of bounds');if(r+h>s.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;Y(this,i,r,h,T,0)}let E=1,v=0;for(this[r]=i&255;++v<h&&(E*=256);)this[r+v]=i/E&255;return r+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;Y(this,i,r,h,T,0)}let E=h-1,v=1;for(this[r+E]=i&255;--E>=0&&(v*=256);)this[r+E]=i/v&255;return r+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,1,255,0),this[r]=i&255,r+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,2,65535,0),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,2,65535,0),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,4,4294967295,0),this[r+3]=i>>>24,this[r+2]=i>>>16,this[r+1]=i>>>8,this[r]=i&255,r+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,4,4294967295,0),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};function Gi(s,i,r,h,f){qi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,r}function Vi(s,i,r,h,f){qi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r+7]=E,E=E>>8,s[r+6]=E,E=E>>8,s[r+5]=E,E=E>>8,s[r+4]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r+3]=v,v=v>>8,s[r+2]=v,v=v>>8,s[r+1]=v,v=v>>8,s[r]=v,r+8}l.prototype.writeBigUInt64LE=me(function(i,r=0){return Gi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=me(function(i,r=0){return Vi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const B=Math.pow(2,8*h-1);Y(this,i,r,h,B-1,-B)}let E=0,v=1,T=0;for(this[r]=i&255;++E<h&&(v*=256);)i<0&&T===0&&this[r+E-1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const B=Math.pow(2,8*h-1);Y(this,i,r,h,B-1,-B)}let E=h-1,v=1,T=0;for(this[r+E]=i&255;--E>=0&&(v*=256);)i<0&&T===0&&this[r+E+1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeInt8=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,1,127,-128),i<0&&(i=255+i+1),this[r]=i&255,r+1},l.prototype.writeInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,2,32767,-32768),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,2,32767,-32768),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,4,2147483647,-2147483648),this[r]=i&255,this[r+1]=i>>>8,this[r+2]=i>>>16,this[r+3]=i>>>24,r+4},l.prototype.writeInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||Y(this,i,r,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4},l.prototype.writeBigInt64LE=me(function(i,r=0){return Gi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=me(function(i,r=0){return Vi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ji(s,i,r,h,f,E){if(r+h>s.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Hi(s,i,r,h,f){return i=+i,r=r>>>0,f||ji(s,i,r,4),n.write(s,i,r,h,23,4),r+4}l.prototype.writeFloatLE=function(i,r,h){return Hi(this,i,r,!0,h)},l.prototype.writeFloatBE=function(i,r,h){return Hi(this,i,r,!1,h)};function Wi(s,i,r,h,f){return i=+i,r=r>>>0,f||ji(s,i,r,8),n.write(s,i,r,h,52,8),r+8}l.prototype.writeDoubleLE=function(i,r,h){return Wi(this,i,r,!0,h)},l.prototype.writeDoubleBE=function(i,r,h){return Wi(this,i,r,!1,h)},l.prototype.copy=function(i,r,h,f){if(!l.isBuffer(i))throw new TypeError("argument should be a Buffer");if(h||(h=0),!f&&f!==0&&(f=this.length),r>=i.length&&(r=i.length),r||(r=0),f>0&&f<h&&(f=h),f===h||i.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("sourceEnd out of bounds");f>this.length&&(f=this.length),i.length-r<f-h&&(f=i.length-r+h);const E=f-h;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,f):Uint8Array.prototype.set.call(i,this.subarray(h,f),r),E},l.prototype.fill=function(i,r,h,f){if(typeof i=="string"){if(typeof r=="string"?(f=r,r=0,h=this.length):typeof h=="string"&&(f=h,h=this.length),f!==void 0&&typeof f!="string")throw new TypeError("encoding must be a string");if(typeof f=="string"&&!l.isEncoding(f))throw new TypeError("Unknown encoding: "+f);if(i.length===1){const v=i.charCodeAt(0);(f==="utf8"&&v<128||f==="latin1")&&(i=v)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(r<0||this.length<r||this.length<h)throw new RangeError("Out of range index");if(h<=r)return this;r=r>>>0,h=h===void 0?this.length:h>>>0,i||(i=0);let E;if(typeof i=="number")for(E=r;E<h;++E)this[E]=i;else{const v=l.isBuffer(i)?i:l.from(i,f),T=v.length;if(T===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(E=0;E<h-r;++E)this[E+r]=v[E%T]}return this};const Re={};function Dt(s,i,r){Re[s]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(f){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:f,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}Dt("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Dt("ERR_INVALID_ARG_TYPE",function(s,i){return`The "${s}" argument must be of type number. Received type ${typeof i}`},TypeError),Dt("ERR_OUT_OF_RANGE",function(s,i,r){let h=`The value of "${s}" is out of range.`,f=r;return Number.isInteger(r)&&Math.abs(r)>2**32?f=zi(String(r)):typeof r=="bigint"&&(f=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(f=zi(f)),f+="n"),h+=` It must be ${i}. Received ${f}`,h},RangeError);function zi(s){let i="",r=s.length;const h=s[0]==="-"?1:0;for(;r>=h+4;r-=3)i=`_${s.slice(r-3,r)}${i}`;return`${s.slice(0,r)}${i}`}function Cr(s,i,r){xe(i,"offset"),(s[i]===void 0||s[i+r]===void 0)&&Ve(i,s.length-(r+1))}function qi(s,i,r,h,f,E){if(s>r||s<i){const v=typeof i=="bigint"?"n":"";let T;throw i===0||i===BigInt(0)?T=`>= 0${v} and < 2${v} ** ${(E+1)*8}${v}`:T=`>= -(2${v} ** ${(E+1)*8-1}${v}) and < 2 ** ${(E+1)*8-1}${v}`,new Re.ERR_OUT_OF_RANGE("value",T,s)}Cr(h,f,E)}function xe(s,i){if(typeof s!="number")throw new Re.ERR_INVALID_ARG_TYPE(i,"number",s)}function Ve(s,i,r){throw Math.floor(s)!==s?(xe(s,r),new Re.ERR_OUT_OF_RANGE("offset","an integer",s)):i<0?new Re.ERR_BUFFER_OUT_OF_BOUNDS:new Re.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${i}`,s)}const Ir=/[^+/0-9A-Za-z-_]/g;function br(s){if(s=s.split("=")[0],s=s.trim().replace(Ir,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function Mt(s,i){i=i||1/0;let r;const h=s.length;let f=null;const E=[];for(let v=0;v<h;++v){if(r=s.charCodeAt(v),r>55295&&r<57344){if(!f){if(r>56319){(i-=3)>-1&&E.push(239,191,189);continue}else if(v+1===h){(i-=3)>-1&&E.push(239,191,189);continue}f=r;continue}if(r<56320){(i-=3)>-1&&E.push(239,191,189),f=r;continue}r=(f-55296<<10|r-56320)+65536}else f&&(i-=3)>-1&&E.push(239,191,189);if(f=null,r<128){if((i-=1)<0)break;E.push(r)}else if(r<2048){if((i-=2)<0)break;E.push(r>>6|192,r&63|128)}else if(r<65536){if((i-=3)<0)break;E.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((i-=4)<0)break;E.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return E}function Ar(s){const i=[];for(let r=0;r<s.length;++r)i.push(s.charCodeAt(r)&255);return i}function Tr(s,i){let r,h,f;const E=[];for(let v=0;v<s.length&&!((i-=2)<0);++v)r=s.charCodeAt(v),h=r>>8,f=r%256,E.push(f),E.push(h);return E}function Yi(s){return e.toByteArray(br(s))}function dt(s,i,r,h){let f;for(f=0;f<h&&!(f+r>=i.length||f>=s.length);++f)i[f+r]=s[f];return f}function ie(s,i){return s instanceof i||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===i.name}function Ut(s){return s!==s}const Rr=(function(){const s="0123456789abcdef",i=new Array(256);for(let r=0;r<16;++r){const h=r*16;for(let f=0;f<16;++f)i[h+f]=s[r]+s[f]}return i})();function me(s){return typeof BigInt>"u"?xr:s}function xr(){throw new Error("BigInt not supported")}})(At)),At}var In=Cn();const bn="https://api.anam.ai",An="/v1",Ni={client:"js-sdk",version:"4.8.0"};var Tn=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};const Oi="https://api.anam.ai",Tt="/v1";var oe;(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"})(oe||(oe={}));let Rt=Oi,ki=Tt,ue,Di=!1;const Rn=(t,e=Tt)=>{Rt=t,ki=e},xn=t=>{ue=t},Nn=t=>{Di=t};let de={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ae=t=>{de=Object.assign(Object.assign({},de),t)},ye=(t,e,n)=>Tn(void 0,void 0,void 0,function*(){if(!Di)try{const o=Object.assign(Object.assign({},Ni),n);de.sessionId&&(o.sessionId=de.sessionId),de.organizationId&&(o.organizationId=de.organizationId),de.attemptCorrelationId&&(o.attemptCorrelationId=de.attemptCorrelationId);const c=`${ki}/metrics/client`;let a,u={"Content-Type":"application/json"};ue?.enabled&&ue?.baseUrl?(a=`${ue.baseUrl}${c}`,u["X-Anam-Target-Url"]=`${Rt}${c}`):a=`${Rt}${c}`,yield fetch(a,{method:"POST",headers:u,body:JSON.stringify({name:t,value:e,tags:o})})}catch(o){console.error("Failed to send error metric:",o)}}),On=(t,e="console")=>{var n,o,c;const a={};t.forEach(d=>{a[d.type]||(a[d.type]=[]),a[d.type].push(d)});const u={issues:[]},l=((n=a["inbound-rtp"])===null||n===void 0?void 0:n.filter(d=>d.kind==="video"))||[];l.length>0&&(u.personaVideoStream=[],l.forEach(d=>{var S,m,y,A,w;const I={framesReceived:(S=d.framesReceived)!==null&&S!==void 0?S:"unknown",framesDropped:(m=d.framesDropped)!==null&&m!==void 0?m:"unknown",framesPerSecond:(y=d.framesPerSecond)!==null&&y!==void 0?y:"unknown",packetsReceived:(A=d.packetsReceived)!==null&&A!==void 0?A:"unknown",packetsLost:(w=d.packetsLost)!==null&&w!==void 0?w:"unknown",resolution:d.frameWidth&&d.frameHeight?`${d.frameWidth}x${d.frameHeight}`:void 0,jitter:d.jitter!==void 0?d.jitter:void 0};u.personaVideoStream.push(I)}));const g=((o=a["inbound-rtp"])===null||o===void 0?void 0:o.filter(d=>d.kind==="audio"))||[];g.length>0&&(u.personaAudioStream=[],g.forEach(d=>{var S,m,y;const A={packetsReceived:(S=d.packetsReceived)!==null&&S!==void 0?S:"unknown",packetsLost:(m=d.packetsLost)!==null&&m!==void 0?m:"unknown",audioLevel:(y=d.audioLevel)!==null&&y!==void 0?y:"unknown",jitter:d.jitter!==void 0?d.jitter:void 0,totalAudioEnergy:d.totalAudioEnergy!==void 0?d.totalAudioEnergy:void 0};u.personaAudioStream.push(A)}));const p=((c=a["outbound-rtp"])===null||c===void 0?void 0:c.filter(d=>d.kind==="audio"))||[];p.length>0&&(u.userAudioInput=[],p.forEach(d=>{var S,m;const y={packetsSent:(S=d.packetsSent)!==null&&S!==void 0?S:"unknown",retransmittedPackets:(m=d.retransmittedPacketsSent)!==null&&m!==void 0?m:void 0,avgPacketSendDelay:d.totalPacketSendDelay!==void 0?d.totalPacketSendDelay/(d.packetsSent||1)*1e3:void 0};u.userAudioInput.push(y)})),a.codec&&(u.codecs=[],a.codec.forEach(d=>{const S={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(S)})),a.transport&&(u.transportLayer=[],a.transport.forEach(d=>{const S={dtlsState:d.dtlsState||"unknown",iceState:d.iceState||"unknown",bytesSent:d.bytesSent||void 0,bytesReceived:d.bytesReceived||void 0};u.transportLayer.push(S)}));const _=[];if(l.forEach(d=>{typeof d.framesDropped=="number"&&d.framesDropped>0&&_.push(`Video: ${d.framesDropped} frames dropped`),typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Video: ${d.packetsLost} packets lost`),typeof d.framesPerSecond=="number"&&d.framesPerSecond<23&&_.push(`Video: Low frame rate (${d.framesPerSecond} fps)`)}),g.forEach(d=>{typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Audio: ${d.packetsLost} packets lost`),typeof d.jitter=="number"&&d.jitter>.1&&_.push(`Audio: High jitter (${(d.jitter*1e3).toFixed(1)}ms)`)}),u.issues=_,e==="json")return u;console.group("📊 WebRTC Session Statistics Report"),u.personaVideoStream&&u.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),u.personaVideoStream.forEach(d=>{console.log(`Frames Received: ${d.framesReceived}`),console.log(`Frames Dropped: ${d.framesDropped}`),console.log(`Frames Per Second: ${d.framesPerSecond}`),console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),d.resolution&&console.log(`Resolution: ${d.resolution}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`)}),console.groupEnd()),u.personaAudioStream&&u.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),u.personaAudioStream.forEach(d=>{console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),console.log(`Audio Level: ${d.audioLevel}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`),d.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${d.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),u.userAudioInput&&u.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),u.userAudioInput.forEach(d=>{console.log(`Packets Sent: ${typeof d.packetsSent=="number"?d.packetsSent.toLocaleString():d.packetsSent}`),d.retransmittedPackets&&console.log(`Retransmitted Packets: ${d.retransmittedPackets}`),d.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${d.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),u.codecs&&u.codecs.length>0&&(console.group("🔧 Codecs Used"),u.codecs.forEach(d=>{console.log(`${d.status} ${d.mimeType} - Payload Type: ${d.payloadType}`),d.clockRate&&console.log(` Clock Rate: ${d.clockRate}Hz`),d.channels&&console.log(` Channels: ${d.channels}`)}),console.groupEnd()),u.transportLayer&&u.transportLayer.length>0&&(console.group("🚚 Transport Layer"),u.transportLayer.forEach(d=>{console.log(`DTLS State: ${d.dtlsState}`),console.log(`ICE State: ${d.iceState}`),(d.bytesReceived||d.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(d.bytesSent||0).toLocaleString()}, Received: ${(d.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),u.issues.length>0?(console.group("⚠️ Potential Issues Detected"),u.issues.forEach(d=>console.warn(d)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var j;(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"})(j||(j={}));class $ extends Error{constructor(e,n,o=500,c){super(e),this.name="ClientError",this.code=n,this.statusCode=o,this.details=c,Object.setPrototypeOf(this,$.prototype),ye(oe.CLIENT_METRIC_MEASUREMENT_ERROR,n,{details:c,statusCode:o})}}function Mi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function kn(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 H;(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"})(H||(H={}));var Fe;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.REASONING_TEXT="reasoningText"})(Fe||(Fe={}));var he;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(he||(he={}));var rt;(function(t){t.USER="user",t.PERSONA="persona"})(rt||(rt={}));var R;(function(t){t.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",t.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",t.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",t.CONNECTION_CLOSED="CONNECTION_CLOSED",t.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",t.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",t.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",t.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",t.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",t.SESSION_READY="SESSION_READY",t.SERVER_WARNING="SERVER_WARNING",t.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",t.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",t.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",t.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",t.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"})(R||(R={}));var K;(function(t){t.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",t.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",t.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(K||(K={}));var fe;(function(t){t.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",t.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",t.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",t.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",t.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(fe||(fe={}));class Dn{constructor(e,n){this.sequenceNumber=0,this.config=e,this.signallingClient=n}sendAudioChunk(e){const o={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(o)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const n=e instanceof Uint8Array?e:new Uint8Array(e),o=Array.from(n,c=>String.fromCharCode(c)).join("");return btoa(o)}}var Te=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};const Mn=5,Un=5;class Bn{constructor(e,n,o,c,a){var u,l,g,p,_;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=o,this.internalEventEmitter=c,this.apiGatewayConfig=a,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:d,maxWsReconnectionAttempts:S,url:m}=n;if(this.heartbeatIntervalSeconds=d||Mn,this.maxWsReconnectionAttempts=S||Un,!m.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((u=this.apiGatewayConfig)===null||u===void 0)&&u.enabled&&(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.baseUrl)){const y=new URL(this.apiGatewayConfig.baseUrl),A=(g=this.apiGatewayConfig.wsPath)!==null&&g!==void 0?g:"/ws";y.protocol=y.protocol.replace("http","ws"),y.pathname=A,this.url=y;const w=m.protocol||"https",I=w==="http"?"ws":"wss",b=`${w}://${m.baseUrl}`,x=(p=m.signallingPath)!==null&&p!==void 0?p:"/ws",M=new URL(b);M.protocol=I==="ws"?"ws:":"wss:",m.port&&(M.port=m.port),M.pathname=x,M.searchParams.append("session_id",e),this.url.searchParams.append("target_url",M.href)}else{const A=`${m.protocol||"https"}://${m.baseUrl}`;this.url=new URL(A),this.url.protocol=m.protocol==="http"?"ws:":"wss:",m.port&&(this.url.port=m.port),this.url.pathname=(_=m.signallingPath)!==null&&_!==void 0?_:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Te(this,void 0,void 0,function*(){const n={connectionDescription:e,userUid:this.sessionId},o={actionType:H.OFFER,sessionId:this.sessionId,payload:n};this.sendSignalMessage(o)})}sendIceCandidate(e){return Te(this,void 0,void 0,function*(){const n={actionType:H.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(n)})}sendSignalMessage(e){var n;if(((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(o){console.error("SignallingClient - sendSignalMessage: error sending message",o)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Te(this,void 0,void 0,function*(){const n={actionType:H.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)})}sendAgentAudioInput(e){const n={actionType:H.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)}sendAgentAudioInputEnd(){const e={actionType:H.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Te(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(K.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,fe.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Te(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,fe.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(n=>{var o;((o=this.socket)===null||o===void 0?void 0:o.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(n)):e.push(n)}),this.sendingBuffer=e}onMessage(e){return Te(this,void 0,void 0,function*(){const n=JSON.parse(e.data);this.internalEventEmitter.emit(K.SIGNAL_MESSAGE_RECEIVED,n)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,n={actionType:H.HEARTBEAT,sessionId:this.sessionId,payload:""},o=JSON.stringify(n);this.heartBeatIntervalRef=setInterval(()=>{var c;this.stopSignal||((c=this.socket)===null||c===void 0?void 0:c.readyState)===WebSocket.OPEN&&this.socket.send(o)},e)}}function Ln(t){return"brainType"in t||"llmId"in t}var Ui=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};class Pn{constructor(e,n,o){if(!e&&!n)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=n||null,this.baseUrl=o?.baseUrl||bn,this.apiVersion=o?.apiVersion||An,this.apiGatewayConfig=o?.apiGateway||void 0}buildGatewayUrlAndHeaders(e,n){var o,c;if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((c=this.apiGatewayConfig)===null||c===void 0)&&c.baseUrl)){const a=`${this.apiGatewayConfig.baseUrl}${e}`,u=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},n),{"X-Anam-Target-Url":u.href});return{url:a,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:n}}startSession(e,n){return Ui(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",j.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const o=`${this.apiVersion}/engine/session`,{url:c,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),u=yield fetch(c,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:n,clientMetadata:Ni})}),l=yield u.json(),g=l.error;switch(u.status){case 200:case 201:return l;case 400:throw new $("Invalid request to start session",j.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new $("Authentication failed when starting session",j.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new $("Please sign up for a plan to start a session",j.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new $("Authentication failed when starting session",j.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw g==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",j.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):g==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",j.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new $("Usage limit reached, please upgrade your plan",j.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new $("There are no available personas, please try again later",j.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new $("Unknown error when starting session",j.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(o){throw o instanceof $?o:new $("Failed to start session",j.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:o instanceof Error?o.message:String(o)})}})}unsafe_getSessionToken(e){return Ui(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let n={clientLabel:"js-sdk-api-key"};Ln(e)&&(n=Object.assign(Object.assign({},n),{personaConfig:e}));try{const o=`${this.apiVersion}/auth/session-token`,{url:c,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(c,{method:"POST",headers:a,body:JSON.stringify(n)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Fn=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};class $n{constructor(e,n,o){this.baseUrl=e,this.sessionId=n,this.apiGatewayConfig=o}sendTalkCommand(e){return Fn(this,void 0,void 0,function*(){var n,o;try{let c,a={"Content-Type":"application/json"};const u="/talk",l=`?session_id=${this.sessionId}`;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.baseUrl)){c=`${this.apiGatewayConfig.baseUrl}${u}${l}`;const p=new URL(`${this.baseUrl}${u}${l}`);a["X-Anam-Target-Url"]=p.href}else c=`${this.baseUrl}${u}${l}`;const g=yield fetch(c,{method:"POST",headers:a,body:JSON.stringify({content:e})});if(!g.ok)throw new Error(`Failed to send talk command: ${g.status} ${g.statusText}`)}catch(c){throw console.error(c),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Gn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}class Vn{constructor(e,n){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(K.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const n={id:e.id,content:e.content,role:e.role};this.messages.push(n)}processPersonaMessage(e){const n={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},o=this.messages.findIndex(c=>c.id===n.id);if(o!==-1){const c=this.messages[o];this.messages[o]=Object.assign(Object.assign({},c),{content:c.content+n.content,interrupted:c.interrupted||n.interrupted})}else this.messages.push(n)}processWebRtcTextMessageEvent(e){const n=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(R.MESSAGE_STREAM_EVENT_RECEIVED,n),n.role){case rt.USER:this.processUserMessage(n);break;case rt.PERSONA:this.processPersonaMessage(n);break}n.endOfSpeech&&this.publicEventEmitter.emit(R.MESSAGE_HISTORY_UPDATED,this.messages)}}class jn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){if(e===R.CONNECTION_ESTABLISHED&&ye(oe.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===R.CONNECTION_CLOSED){const[o,c]=n;ye(oe.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,o,c?{details:c}:void 0)}this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}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 xt=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};class Hn{constructor(e,n,o){this.state=z.UNSTARTED,this.correlationId=e,this.internalEventEmitter=n,this.signallingClient=o,this.internalEventEmitter.addListener(K.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(K.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return xt(this,void 0,void 0,function*(){e.actionType===H.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=z.INTERRUPTED,this.onDeactivate())})}endMessage(){return xt(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 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,n){return xt(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 o={content:e,startOfSpeech:this.state===z.UNSTARTED,endOfSpeech:n,correlationId:this.correlationId};this.state=n?z.ENDED:z.STREAMING,this.state===z.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(o)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===z.STREAMING||this.state===z.UNSTARTED}getState(){return this.state}}var J=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};const Wn=15e3,zn=5e3,qn=2;class Yn{constructor(e,n,o,c){var a,u,l,g;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:he.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=o,this.internalEventEmitter=c,this.apiGatewayConfig=n.apiGateway;const{inputAudio:p}=n;this.inputAudioState=p.inputAudioState,n.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=n.inputAudio.userProvidedMediaStream),this.disableInputAudio=n.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(K.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(K.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.iceServers=n.iceServers,this.signallingClient=new Bn(e,n.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new $n(n.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=n.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(u=(a=n.metrics)===null||a===void 0?void 0:a.showPeerConnectionStatsReport)!==null&&u!==void 0?u:!1,this.peerConnectionStatsReportOutputFormat=(g=(l=n.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&g!==void 0?g:"console"}onInputAudioStateChange(e,n){e.isMuted!==n.isMuted&&(n.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>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)}}),zn))}sendClientSideMetrics(e){e.forEach(n=>{if(n.type==="inbound-rtp"){const o={message_type:"remote_rtp_stats",data:n};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(o))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Wn);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 n=yield this.peerConnection.getStats();let o=!1,c=null;n.forEach(a=>{a.type==="inbound-rtp"&&a.kind==="video"&&(a.framesDecoded!==void 0&&a.framesDecoded>0?(o=!0,c="framesDecoded"):a.framesReceived!==void 0&&a.framesReceived>0?(o=!0,c="framesReceived"):a.bytesReceived>0&&a.packetsReceived>0&&a.bytesReceived>1e5&&(o=!0,c="bytesReceived"))}),o&&!this.successMetricFired&&(this.successMetricFired=!0,ye(oe.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",c?{detectionMethod:c}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return 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 n=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(c=>{c.stop()});const o={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:o}),this.audioDeviceId=e,yield this.setupAudioTrack(),n&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(R.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(o){throw console.error("Failed to change audio input device:",o),new Error(`StreamingClient - changeAudioInputDevice: ${o instanceof Error?o.message:String(o)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const n=document.getElementById(e);if(!n)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=n}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return 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 Hn(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Dn(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return J(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:qn}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return J(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case H.ANSWER:const n=e.payload;yield this.peerConnection.setRemoteDescription(n),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case H.ICE_CANDIDATE:const o=e.payload,c=new RTCIceCandidate(o);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(c):this.remoteIceCandidateBuffer.push(c);break;case H.END_SESSION:const a=e.payload;this.publicEventEmitter.emit(R.CONNECTION_CLOSED,fe.SERVER_CLOSED_CONNECTION,a),this.shutdown();break;case H.WARNING:const u=e.payload;console.warn("Warning received from server: "+u),this.publicEventEmitter.emit(R.SERVER_WARNING,u);break;case H.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(R.TALK_STREAM_INTERRUPTED,l.correlationId);break;case H.SESSION_READY:const g=e.sessionId;this.publicEventEmitter.emit(R.SESSION_READY,g);break;case H.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-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(){this.remoteIceCandidateBuffer.forEach(e=>{var n;(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,n;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(R.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(R.CONNECTION_CLOSED,fe.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(R.CONNECTION_CLOSED,fe.WEBRTC_FAILURE);try{this.stopConnection()}catch(n){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",n)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(R.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const n=this.videoElement.requestVideoFrameCallback(()=>{var o;(o=this.videoElement)===null||o===void 0||o.cancelVideoFrameCallback(n),this.publicEventEmitter.emit(R.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ye(oe.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(R.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return J(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=n=>{try{const o=JSON.parse(n.data);switch(o.messageType){case Fe.SPEECH_TEXT:this.internalEventEmitter.emit(K.WEBRTC_CHAT_MESSAGE_RECEIVED,o.data);break;case Fe.CLIENT_TOOL_EVENT:const c=o.data;this.internalEventEmitter.emit(K.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,c);const a=Kn.WebRTCClientToolEventToClientToolEvent(c);this.publicEventEmitter.emit(R.CLIENT_TOOL_EVENT_RECEIVED,a);break;case Fe.REASONING_TEXT:this.internalEventEmitter.emit(K.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,o.data);break;default:break}}catch(o){console.error("Failed to parse data channel message:",o)}}})}requestMicrophonePermissionAsync(){return J(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==he.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.PENDING}),this.publicEventEmitter.emit(R.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.GRANTED}),this.publicEventEmitter.emit(R.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:he.DENIED});const n=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(R.MIC_PERMISSION_DENIED,n)}}})}setupAudioTrack(){return J(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 a;return((a=c.track)===null||a===void 0?void 0:a.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(R.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return J(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 J(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const n=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(n){const o=On(n,this.peerConnectionStatsReportOutputFormat);o&&console.log(o,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(n=>{n.stop()}),this.inputAudioStream=null}catch(n){console.error("StreamingClient - shutdown: error stopping input audio stream",n)}try{this.signallingClient.stop()}catch(n){console.error("StreamingClient - shutdown: error stopping signallilng",n)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(n){console.error("StreamingClient - shutdown: error closing peer connection",n)}})}}class Kn{static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}class Jn{constructor(e,n){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(K.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const n=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(R.REASONING_STREAM_EVENT_RECEIVED,n);const o={id:n.id,content:n.content,role:n.role},c=this.reasoning_messages.findIndex(a=>a.id===o.id);if(c!==-1){const a=this.reasoning_messages[c];a.content+=o.content,this.reasoning_messages[c]=a}else this.reasoning_messages.push(o);n.endOfThought&&this.publicEventEmitter.emit(R.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var pe=function(t,e,n,o){function c(a){return a instanceof n?a:new n(function(u){u(a)})}return new(n||(n=Promise))(function(a,u){function l(_){try{p(o.next(_))}catch(d){u(d)}}function g(_){try{p(o.throw(_))}catch(d){u(d)}}function p(_){_.done?a(_.value):c(_.value).then(l,g)}p((o=o.apply(t,e||[])).next())})};class Xn{constructor(e,n,o){var c,a,u,l,g;this.inputAudioState={isMuted:!1,permissionState:he.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,n,o);if(p)throw new $(p,j.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=n,this.clientOptions=o,(!((c=o?.api)===null||c===void 0)&&c.baseUrl||!((a=o?.api)===null||a===void 0)&&a.apiVersion)&&Rn(o.api.baseUrl||Oi,o.api.apiVersion||Tt),!((l=(u=o?.api)===null||u===void 0?void 0:u.apiGateway)===null||l===void 0)&&l.enabled&&xn(o.api.apiGateway),!((g=o?.metrics)===null||g===void 0)&&g.disableClientMetrics&&Nn(!0),this.publicEventEmitter=new jn,this.internalEventEmitter=new Gn,this.apiClient=new Pn(e,o?.apiKey,o?.api),this.messageHistoryClient=new Vn(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Jn(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const n=e.split(".")[1],o=In.Buffer.from(n,"base64").toString("utf8");return JSON.parse(o)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,n,o){var c,a;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=kn((c=o?.api)===null||c===void 0?void 0:c.apiGateway);if(u)return u;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,Ae({organizationId:this.organizationId});const g=(a=l.type)===null||a===void 0?void 0:a.toLowerCase();if(g==="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((g==="ephemeral"||g==="stateful")&&n)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!n)return"Missing persona config. Persona configuration must be provided when using apiKey";if(o?.voiceDetection){if(o.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(o.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof o.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(o.voiceDetection.endOfSpeechSensitivity<0||o.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const n={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(n.voiceDetection=this.clientOptions.voiceDetection),Object.keys(n).length!==0)return n}startSession(e){return pe(this,void 0,void 0,function*(){var n,o,c,a,u,l,g,p,_,d,S,m;const y=this.personaConfig,A=this.buildStartSessionOptionsForClient(),w=yield this.apiClient.startSession(y,A),{sessionId:I,clientConfig:b,engineHost:x,engineProtocol:M,signallingEndpoint:N}=w,{heartbeatIntervalSeconds:Z,maxWsReconnectionAttempts:W,iceServers:_e}=b;this.sessionId=I,Ae({sessionId:this.sessionId});const se=!((n=this.clientOptions)===null||n===void 0)&&n.iceServers?this.clientOptions.iceServers:_e;try{this.streamingClient=new Yn(I,{engine:{baseUrl:`${M}://${x}`},signalling:{heartbeatIntervalSeconds:Z,maxWsReconnectionAttempts:W,url:{baseUrl:x,protocol:M,signallingPath:N}},iceServers:se,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio?void 0:e,audioDeviceId:(c=this.clientOptions)===null||c===void 0?void 0:c.audioDeviceId,disableInputAudio:(a=this.clientOptions)===null||a===void 0?void 0:a.disableInputAudio},apiGateway:(l=(u=this.clientOptions)===null||u===void 0?void 0:u.api)===null||l===void 0?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:(_=(p=(g=this.clientOptions)===null||g===void 0?void 0:g.metrics)===null||p===void 0?void 0:p.showPeerConnectionStatsReport)!==null&&_!==void 0?_:!1,peerConnectionStatsReportOutputFormat:(m=(S=(d=this.clientOptions)===null||d===void 0?void 0:d.metrics)===null||S===void 0?void 0:S.peerConnectionStatsReportOutputFormat)!==null&&m!==void 0?m:"console"}},this.publicEventEmitter,this.internalEventEmitter)}catch(ae){throw Ae({sessionId:null}),new $("Failed to initialize streaming client",j.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:ae instanceof Error?ae.message:String(ae),sessionId:I})}return I})}startSessionIfNeeded(e){return pe(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new $("Session ID or streaming client is not available after starting session",j.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return pe(this,void 0,void 0,function*(){var n;if(this._isStreaming)throw new Error("Already streaming");const o=Mi();return Ae({attemptCorrelationId:o,sessionId:null}),ye(oe.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(c=>{var a;const u=[];let l=!1,g=!1;this.publicEventEmitter.addListener(R.VIDEO_STREAM_STARTED,p=>{u.push(p),l=!0,g&&c(u)}),this.publicEventEmitter.addListener(R.AUDIO_STREAM_STARTED,p=>{u.push(p),g=!0,l&&c(u)}),(a=this.streamingClient)===null||a===void 0||a.startConnection()})})}streamToVideoAndAudioElements(e,n,o){return pe(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,o)})}streamToVideoElement(e,n){return pe(this,void 0,void 0,function*(){var o;const c=Mi();Ae({attemptCorrelationId:c,sessionId:null}),ye(oe.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio&&n&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(n)}catch(a){throw a instanceof $?a:new $("Failed to start session",j.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a instanceof Error?a.message:String(a),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return pe(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const n=this.getActiveSessionId();if(!n)throw new Error("Failed to send user message: no active session");const o=new Date().toISOString().replace("Z",""),c=JSON.stringify({content:e,timestamp:o,session_id:n,message_type:"speech"});this.sendDataMessage(c)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const n=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(n)}stopStreaming(){return pe(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(R.CONNECTION_CLOSED,fe.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ae({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return pe(this,void 0,void 0,function*(){var n;if(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,n){this.publicEventEmitter.addListener(e,n)}removeListener(e,n){this.publicEventEmitter.removeListener(e,n)}getActiveSessionId(){return this.sessionId}}const Zn=(t,e)=>new Xn(t,void 0,e),Qn="https://api.anam.ai",X=q(null),te=q("idle"),$e=q(!1),ot=q(!1),st=q([]),Ge=q(null),at=q(null),lt=q(null),ct=q(null),Nt=q(null),Bi=q(!1),ut=q(!1);function er(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."}async function tr(t,e){ut.value=!1;try{const n=await fetch(`${e}/v1/personas/${t}/widget`);if(!n.ok)return;const o=await n.json();lt.value=o.persona?.avatarImageUrl||null,ct.value=o.persona?.name||null,Nt.value=o.widgetConfig||null}catch{}finally{ut.value=!0}}async function ir(t,e,n){if(te.value==="connecting"||te.value==="connected")return;te.value="connecting",Ge.value=null;let o;try{console.log("[AnamWidget] Fetching session for agent:",t);const c=await fetch(`${e}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:t})});if(o=c.status,!c.ok){const g=await c.json().catch(()=>({}));throw new Error(g.error||`HTTP ${c.status}`)}const a=await c.json();console.log("[AnamWidget] Got session from agent-id:",{persona:a.persona?.name,hasToken:!!a.sessionToken}),lt.value=a.persona?.avatarImageUrl||null,ct.value=a.persona?.name||null;const u=Zn(a.sessionToken,{api:e?{baseUrl:e}:void 0,metrics:{disableClientMetrics:!0}});u.addListener(R.CONNECTION_ESTABLISHED,()=>{console.log("[AnamWidget] Connection established"),te.value="connected"}),u.addListener(R.VIDEO_STREAM_STARTED,()=>{console.log("[AnamWidget] Video stream started"),$e.value=!0}),u.addListener(R.AUDIO_STREAM_STARTED,()=>{console.log("[AnamWidget] Audio stream started")}),u.addListener(R.MESSAGE_HISTORY_UPDATED,g=>{st.value=[...g]}),u.addListener(R.CONNECTION_CLOSED,(g,p)=>{console.log("[AnamWidget] Connection closed:",g,p),te.value="idle",$e.value=!1,at.value=null}),u.addListener(R.SESSION_READY,g=>{console.log("[AnamWidget] Session ready:",g),at.value=g}),X.value=u;const l=await u.stream();if(n&&l.length>0){const g=l.find(p=>p.getVideoTracks().length>0);g&&(n.srcObject=g)}}catch(c){console.error("[AnamWidget] Failed to start session:",c),Ge.value=er(c,o),te.value="error",X.value=null}}async function nr(){if(X.value)try{await X.value.stopStreaming()}catch(t){console.error("[AnamWidget] Failed to stop session:",t)}X.value=null,te.value="idle",$e.value=!1,st.value=[]}function rr(t){!X.value||te.value!=="connected"||X.value.sendUserMessage(t)}function or(){X.value&&(ot.value?(X.value.unmuteInputAudio(),ot.value=!1):(X.value.muteInputAudio(),ot.value=!0))}function sr(){X.value?.isStreaming()&&X.value.stopStreaming(),X.value=null,te.value="idle",$e.value=!1,st.value=[],Ge.value=null,at.value=null,lt.value=null,ct.value=null,Nt.value=null}function ar(t,e){Bi.value=!!t;const n=e||Qn;return{connectionStatus:te,isStreaming:$e,isMuted:ot,messages:st,error:Ge,sessionId:at,hasAgentId:Bi,isReady:ut,avatarThumbnailUrl:lt,personaName:ct,serverConfig:Nt,fetchWidgetConfig:()=>{if(!t){ut.value=!0;return}tr(t,n)},startSession:a=>t?ir(t,n,a):(Ge.value="No agent ID configured",Promise.resolve()),stopSession:nr,sendMessage:rr,toggleMute:or,cleanup:sr}}const Li='@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}.fixed{position:fixed}.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-background:#fff;--anam-text:#18181b;--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:var(--anam-text);-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=fixed]{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:16px;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-mode=expanded][data-layout=inline] .anam-sheet{border-radius:16px;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-cta-pill{-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#00000080;border:1px solid #ffffff1a;border-radius:999px;align-items:center;gap:10px;padding:12px 28px;font-family:inherit;font-size:15px;font-weight:500;transition:all .2s;display:flex;position:absolute;bottom:40px;left:50%;transform:translate(-50%)}.anam-cta-pill:hover{background:#000000a6;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0}.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(8px);color:#fff;cursor:pointer;background:#00000073;border:1px solid #ffffff14;border-radius:50%;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:background .15s;display:flex;position:absolute;top:12px;right:12px}.anam-close-btn:hover{background:#0009}.anam-toast{z-index:10;-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:#0009;border:1px solid #ffffff0f;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:linear-gradient(#0000,#00000040 40%,#0000008c);align-items:center;gap:8px;padding:48px 16px 16px;display:flex;position:absolute;bottom:0;left:0;right:0}.anam-ctl-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff24;border:1px solid #ffffff0f;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:#ffffff38}.anam-ctl-btn:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-btn-muted{background:#dc26268c;border-color:#dc262633}.anam-ctl-btn-muted:hover{background:#dc2626b3}.anam-ctl-end{background:#dc262699;border-color:#dc262626}.anam-ctl-end:hover{background:#dc2626cc}.anam-ctl-input{-webkit-backdrop-filter:blur(8px);color:#fff;background:#ffffff1a;border:1px solid #ffffff14;border-radius:999px;outline:none;flex:1;min-width:0;padding:11px 18px;font-family:inherit;font-size:14px;transition:background .15s,border-color .15s}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff26;border-color:#ffffff2e}.anam-ctl-input:disabled{opacity:.35;cursor:not-allowed}@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}';function Pi(t,e){const n={...t};for(const o of Object.keys(e)){const c=e[o];c!==void 0&&(c!==null&&typeof c=="object"&&!Array.isArray(c)&&typeof n[o]=="object"&&n[o]!==null&&!Array.isArray(n[o])?n[o]=Pi(n[o],c):n[o]=c)}return n}const lr=()=>C("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round",children:C("path",{d:"M18 6L6 18M6 6l12 12"})}),cr=()=>C("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:C("path",{d:"M8 5.14v13.72a1 1 0 0 0 1.5.86l11.04-6.86a1 1 0 0 0 0-1.72L9.5 4.28A1 1 0 0 0 8 5.14Z"})}),ur=()=>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"})]}),dr=()=>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"})]}),fr=()=>C("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[C("path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 2.59 3.4z"}),C("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),Ot=()=>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 pr({config:t,session:e,videoRef:n,avatarSrc:o,displayCta:c,onCollapse:a}){const u=Ke(null),[l,g]=Ye(""),[p,_]=Ye(null),[d,S]=Ye(!1),m=Ke(null),y=e.connectionStatus.value==="connected",A=e.connectionStatus.value==="connecting",w=e.connectionStatus.value==="error",I=e.isStreaming.value,b=!A&&!y&&!w,x=Je(async()=>{n.current&&await e.startSession(n.current)},[]),M=Je(async()=>{await e.stopSession()},[]),N=Je(()=>{if(!l.trim())return;const W=l.trim();e.sendMessage(W),g(""),u.current?.focus(),m.current&&clearTimeout(m.current),S(!1),_(W),m.current=window.setTimeout(()=>{S(!0),m.current=window.setTimeout(()=>{_(null),S(!1)},400)},2600)},[l]),Z=Je(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),N())},[N]);return St(()=>()=>{m.current&&clearTimeout(m.current)},[]),C("div",{class:"anam-sheet",children:[C("video",{ref:n,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":I?void 0:"true"}),b&&(e.hasAgentId.value?C("div",{class:"anam-overlay-idle",children:[o?C("img",{src:o,alt:"Avatar"}):C(Ot,{}),C("button",{class:"anam-cta-pill",onClick:x,children:[C(cr,{}),c]})]}):C("div",{class:"anam-overlay-unconfigured",children:[C(Ot,{}),C("span",{children:"Agent not configured"})]})),A&&C("div",{class:"anam-overlay-loading",children:[C("span",{class:"anam-spinner"}),C("span",{children:"Starting your conversation..."})]}),w&&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:x,children:"Try Again"})]}),(y||I)&&C(re,{children:[a&&C("button",{class:"anam-close-btn",onClick:a,"aria-label":"Close",children:C(lr,{})}),p&&C("div",{class:`anam-toast ${d?"anam-toast-out":""}`,children:p}),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(dr,{}):C(ur,{})}),t.showTextInput&&C(re,{children:[C("input",{ref:u,type:"text",class:"anam-ctl-input",placeholder:t.textContents.placeholder,value:l,onInput:W=>g(W.target.value),onKeyDown:Z,disabled:!y}),C("button",{class:"anam-ctl-btn",onClick:N,disabled:!y||!l.trim(),"aria-label":"Send message",children:C(hr,{})})]}),C("button",{class:"anam-ctl-btn anam-ctl-end",onClick:M,"aria-label":"End call",children:C(fr,{})})]})]})]})}function _r(t){const e=Ke(null),n=bi(!1),o=ar(t["agent-id"],t["api-base-url"]),c=Ce(()=>{const w={...Le,styles:{...Le.styles},textContents:{...Le.textContents}};if(t.mode?w.mode=t.mode:t.variant&&(w.mode=t.variant),t.layout?w.layout=t.layout:w.layout=w.mode==="orb"?"fixed":"inline",t.position?w.position=t.position:t.placement&&(w.position=t.placement),t["background-color"]&&(w.styles.backgroundColor=t["background-color"]),t["text-color"]&&(w.styles.textColor=t["text-color"]),t["show-transcript"]!==void 0&&(w.showTranscript=it(t["show-transcript"])),t["show-text-input"]!==void 0&&(w.showTextInput=it(t["show-text-input"])),t["show-mute-button"]!==void 0&&(w.showMuteButton=it(t["show-mute-button"])),t["interaction-mode"]&&(w.interactionMode=t["interaction-mode"]),t["start-expanded"]!==void 0&&(w.startExpanded=it(t["start-expanded"])),t["text-call-to-action"]&&(w.textContents.callToAction=t["text-call-to-action"]),t["override-config"])try{Object.assign(w,JSON.parse(t["override-config"]))}catch(x){console.warn("[AnamWidget] Invalid override-config JSON:",x)}const I=o.serverConfig.value,b=I?Pi(w,I):w;return b.mode==="orb"&&(b.layout="fixed"),b},[t.mode,t.variant,t.layout,t.position,t.placement,t["background-color"],t["text-color"],t["show-transcript"],t["show-text-input"],t["show-mute-button"],t["interaction-mode"],t["start-expanded"],t["text-call-to-action"],t["override-config"],o.serverConfig.value]);St(()=>{o.fetchWidgetConfig()},[t["agent-id"],t["api-base-url"]]);const a=o.avatarThumbnailUrl.value||null,u=c.textContents.callToAction===Le.textContents.callToAction&&o.personaName.value?`Talk to ${o.personaName.value}`:c.textContents.callToAction,l=Ce(()=>`--anam-background: ${c.styles.backgroundColor}; --anam-text: ${c.styles.textColor};`,[c.styles.backgroundColor,c.styles.textColor]),g=Ce(()=>{if(c.layout!=="fixed")return"";const w=vn(c.position);return Object.entries(w).map(([I,b])=>`${I}: ${b}`).join("; ")},[c.layout,c.position]),p=[l,g].filter(Boolean).join("; "),_=Ke(!1),d=()=>{n.value=!0,_.current=!1,setTimeout(()=>{e.current&&o.startSession(e.current)},50)},S=async()=>{o.connectionStatus.value!=="idle"&&await o.stopSession(),_.current=!1,n.value=!1},m=c.mode==="orb",y=o.connectionStatus.value;(y==="connecting"||y==="connected")&&(_.current=!0),St(()=>{m&&n.value&&y==="idle"&&_.current&&(_.current=!1,n.value=!1)},[y]);const A=m?n.value:!0;return o.isReady.value?C(re,{children:[C("style",{children:Li}),C("div",{class:"anam-widget","data-mode":c.mode,"data-layout":c.layout,style:p,children:[m&&!n.value&&C("button",{class:"anam-trigger",onClick:d,"aria-label":u,children:a?C("img",{src:a,alt:"Avatar"}):C(Ot,{})}),A&&C(pr,{config:c,session:o,videoRef:e,avatarSrc:a,displayCta:u,onCollapse:m?S:null})]})]}):C("style",{children:Li})}const Er={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"};function kt(t="anam-agent"){nn(_r,t,[...yn],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>kt()):kt()),le.DefaultConfig=Le,le.WidgetEventNames=Er,le.registerWidget=kt,Object.defineProperty(le,Symbol.toStringTag,{value:"Module"})}));
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@anam-ai/agent-widget",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Embeddable video agent widget for Anam AI",
5
+ "type": "module",
6
+ "main": "./dist/index.umd.js",
7
+ "module": "./dist/index.js",
8
+ "unpkg": "./dist/index.umd.js",
9
+ "jsdelivr": "./dist/index.umd.js",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.umd.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "dev": "vite",
21
+ "build": "vite build",
22
+ "preview": "pnpm build && echo '\n Preview: http://localhost:4173/playground/preview.html\n' && npx serve . -l 4173",
23
+ "typecheck": "tsc --noEmit",
24
+ "lint": "eslint src"
25
+ },
26
+ "keywords": [
27
+ "anam",
28
+ "avatar",
29
+ "ai",
30
+ "widget",
31
+ "webrtc",
32
+ "video",
33
+ "conversational-ai"
34
+ ],
35
+ "author": "Anam AI",
36
+ "license": "MIT",
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "packageManager": "pnpm@10.15.1",
41
+ "dependencies": {
42
+ "@anam-ai/js-sdk": "^4.8.0",
43
+ "@preact/signals": "^2.6.2",
44
+ "clsx": "^2.1.1",
45
+ "preact": "^10.28.3",
46
+ "preact-custom-element": "^4.6.0"
47
+ },
48
+ "devDependencies": {
49
+ "@preact/preset-vite": "^2.10.3",
50
+ "@tailwindcss/vite": "^4.1.18",
51
+ "autoprefixer": "^10.4.24",
52
+ "postcss": "^8.5.6",
53
+ "tailwindcss": "^4.1.18",
54
+ "typescript": "^5.9.3",
55
+ "vite": "^7.3.1"
56
+ }
57
+ }