@eka-care/medassist-widget 0.1.133-2 → 0.1.133-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var qc=Object.defineProperty;var Xc=(e,t,n)=>t in e?qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>Xc(e,typeof t!="symbol"?t+"":t,n);var Pn,Z,Ns,Ut,Cs,xs,Ts,ro,Nr,Dn,ks,oo,so,io,Os,Cr={},xr=[],Zc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ln=Array.isArray;function St(e,t){for(var n in t)e[n]=t[n];return e}function ao(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function et(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?Pn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return Un(e,s,r,o,null)}function Un(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ns,__i:-1,__u:0};return o==null&&Z.vnode!=null&&Z.vnode(i),i}function Rs(){return{current:null}}function me(e){return e.children}function lt(e,t){this.props=e,this.context=t}function dn(e,t){if(t==null)return e.__?dn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?dn(e):null}function Jc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=St({},t);i.__v=t.__v+1,Z.vnode&&Z.vnode(i),co(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??dn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Ls(r,i,o),t.__e=t.__=null,i.__e!=n&&As(i)}}function As(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),As(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Ut.push(e)&&!Tr.__r++||Cs!=Z.debounceRendering)&&((Cs=Z.debounceRendering)||xs)(Tr)}function Tr(){try{for(var e,t=1;Ut.length;)Ut.length>t&&Ut.sort(Ts),e=Ut.shift(),t=Ut.length,Jc(e)}finally{Ut.length=Tr.__r=0}}function Is(e,t,n,r,o,i,s,a,l,d,h){var u,p,E,g,f,b,m,_=r&&r.__k||xr,y=t.length;for(l=Qc(n,t,_,l,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(p=E.__i!=-1&&_[E.__i]||Cr,E.__i=u,b=co(e,E,p,o,i,s,a,l,d,h),g=E.__e,E.ref&&p.ref!=E.ref&&(p.ref&&ho(p.ref,null,E),h.push(E.ref,E.__c||g,E)),f==null&&g!=null&&(f=g),(m=!!(4&E.__u))||p.__k===E.__k?(l=Ms(E,l,e,m),m&&p.__e&&(p.__e=null)):typeof E.type=="function"&&b!==void 0?l=b:g&&(l=g.nextSibling),E.__u&=-7);return n.__e=f,l}function Qc(e,t,n,r,o){var i,s,a,l,d,h=n.length,u=h,p=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=Un(null,s,null,null,null):Ln(s)?s=e.__k[i]=Un(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Un(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,l=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=ed(s,n,l,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?p--:d==l+1?p++:(d>l?p--:p++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=dn(a)),Fs(a,a));return r}function Ms(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Ms(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function At(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ln(e)?e.some(function(n){At(n,t)}):t.push(e)),t}function ed(e,t,n,r){var o,i,s,a=e.key,l=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&l==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&l==d.type)return s}return-1}function Ps(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Zc.test(t)?n:n+"px"}function kr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ps(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ps(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ks,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Dn]=r[Dn]:(n[Dn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ds(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Nr]==null)t[Nr]=oo++;else if(t[Nr]<n[Dn])return;return n(Z.event?Z.event(t):t)}}}function co(e,t,n,r,o,i,s,a,l,d){var h,u,p,E,g,f,b,m,_,y,k,x,w,T,S,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=Z.__b)&&h(t);e:if(typeof v=="function")try{if(m=t.props,_=v.prototype&&v.prototype.render,y=(h=v.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new v(m,k):(t.__c=u=new lt(m,k),u.constructor=v,u.render=nd),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&v.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=St({},u.__s)),St(u.__s,v.getDerivedStateFromProps(m,u.__s))),E=u.props,g=u.state,u.__v=t,p)_&&v.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&v.getDerivedStateFromProps==null&&m!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(m,k),t.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(m,u.__s,k)===!1){t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(C){C&&(C.__=t)}),xr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,g,f)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=Z.__r,w=0,_)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),xr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++w<25);u.state=u.__s,u.getChildContext!=null&&(r=St(St({},r),u.getChildContext())),_&&!p&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(E,g)),T=h!=null&&h.type===me&&h.key==null?Us(h.props.children):h,a=Is(e,Ln(T)?T:[T],t,n,r,o,i,s,a,l,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(C){if(t.__v=null,l||i!=null)if(C.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(S=i.length;S--;)ao(i[S]);uo(t)}else t.__e=n.__e,t.__k=n.__k,C.then||uo(t);Z.__e(C,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=td(n.__e,t,n,r,o,i,s,l,d);return(h=Z.diffed)&&h(t),128&t.__u?void 0:a}function uo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(uo))}function Ls(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);Z.__c&&Z.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){Z.__e(i,o.__v)}})}function Us(e){return typeof e!="object"||e==null||e.__b>0?e:Ln(e)?e.map(Us):e.constructor!==void 0?null:St({},e)}function td(e,t,n,r,o,i,s,a,l){var d,h,u,p,E,g,f,b=n.props||Cr,m=t.props,_=t.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(d=0;d<i.length;d++)if((E=i[d])&&"setAttribute"in E==!!_&&(_?E.localName==_:E.nodeType==3)){e=E,i[d]=null;break}}if(e==null){if(_==null)return document.createTextNode(m);e=document.createElementNS(o,_,m.is&&m),a&&(Z.__m&&Z.__m(t,i),a=!1),i=null}if(_==null)b===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&Pn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(E=e.attributes[d]).name]=E.value;for(d in b)E=b[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||kr(e,d,null,E,o);for(d in m)E=m[d],d=="children"?p=E:d=="dangerouslySetInnerHTML"?h=E:d=="value"?g=E:d=="checked"?f=E:a&&typeof E!="function"||b[d]===E||kr(e,d,E,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),Is(t.type=="template"?e.content:e,Ln(p)?p:[p],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&dn(n,0),a,l),i!=null)for(d=i.length;d--;)ao(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||_=="progress"&&!g||_=="option"&&g!=b[d])&&kr(e,d,g,b[d],o),d="checked",f!=null&&f!=e[d]&&kr(e,d,f,b[d],o))}return e}function ho(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){Z.__e(o,n)}}function Fs(e,t,n){var r,o;if(Z.unmount&&Z.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ho(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Z.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function nd(e,t,n){return this.constructor(e,n)}function Fn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],co(t,e=(!r&&n||t).__k=et(me,null,[e]),o||Cr,Cr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Pn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Ls(i,e,s)}function Vs(e,t){Fn(e,t,Vs)}function rd(e,t,n){var r,o,i,s,a=St({},e.props);for(i in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)i=="key"?r=t[i]:i=="ref"?o=t[i]:a[i]=t[i]===void 0&&s!=null?s[i]:t[i];return arguments.length>2&&(a.children=arguments.length>3?Pn.call(arguments,2):n),Un(e.type,a,r||e.key,o||e.ref,null)}function bt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,lo(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Os++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Pn=xr.slice,Z={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(a){e=a}throw e}},Ns=0,lt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=St({},this.state),typeof e=="function"&&(e=e(St({},n),this.props)),e&&St(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),lo(this))},lt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},lt.prototype.render=me,Ut=[],xs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ts=function(e,t){return e.__v.__b-t.__v.__b},Tr.__r=0,ro=Math.random().toString(8),Nr="__d"+ro,Dn="__a"+ro,ks=/(PointerCapture)$|Capture$/i,oo=0,so=Ds(!1),io=Ds(!0),Os=0;var od=0;function c(e,t,n,r,o,i){t||(t={});var s,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?s=t[a]:l[a]=t[a];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--od,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)l[a]===void 0&&(l[a]=s[a]);return Z.vnode&&Z.vnode(d),d}var It,fe,mo,js,un=0,zs=[],xe=Z,$s=xe.__b,Ys=xe.__r,Hs=xe.diffed,Bs=xe.__c,Gs=xe.unmount,Ws=xe.__;function qt(e,t){xe.__h&&xe.__h(fe,e,un||t),un=0;var n=fe.__H||(fe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function V(e){return un=1,hn(qs,e)}function hn(e,t,n){var r=qt(It++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):qs(void 0,t),function(a){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,a);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=fe,!fe.__f)){var o=function(a,l,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,l,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var E=p.__[0];p.__=p.__N,p.__N=void 0,E!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,l,d)||u};fe.__f=!0;var i=fe.shouldComponentUpdate,s=fe.componentWillUpdate;fe.componentWillUpdate=function(a,l,d){if(this.__e){var h=i;i=void 0,o(a,l,d),i=h}s&&s.call(this,a,l,d)},fe.shouldComponentUpdate=o}return r.__N||r.__}function H(e,t){var n=qt(It++,3);!xe.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__H.__h.push(n))}function mt(e,t){var n=qt(It++,4);!xe.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__h.push(n))}function q(e){return un=5,ae(function(){return{current:e}},[])}function po(e,t,n){un=6,mt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ae(e,t){var n=qt(It++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function de(e,t){return un=8,ae(function(){return e},t)}function vt(e){var t=fe.context[e.__c],n=qt(It++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(fe)),t.props.value):e.__}function fo(e,t){xe.useDebugValue&&xe.useDebugValue(t?t(e):e)}function sd(e){var t=qt(It++,10),n=V();return t.__=e,fe.componentDidCatch||(fe.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=qt(It++,11);if(!e.__){for(var t=fe.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function id(){for(var e;e=zs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Or),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],xe.__e(n,e.__v)}}}xe.__b=function(e){fe=null,$s&&$s(e)},xe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ws&&Ws(e,t)},xe.__r=function(e){Ys&&Ys(e),It=0;var t=(fe=e.__c).__H;t&&(mo===fe?(t.__h=[],fe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Or),t.__h.some(_o),t.__h=[],It=0)),mo=fe},xe.diffed=function(e){Hs&&Hs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(zs.push(t)!==1&&js===xe.requestAnimationFrame||((js=xe.requestAnimationFrame)||ad)(id)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=fe=null},xe.__c=function(e,t){t.some(function(n){try{n.__h.some(Or),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],xe.__e(r,n.__v)}}),Bs&&Bs(e,t)},xe.unmount=function(e){Gs&&Gs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Or(r)}catch(o){t=o}}),n.__H=void 0,t&&xe.__e(t,n.__v))};var Ks=typeof requestAnimationFrame=="function";function ad(e){var t,n=function(){clearTimeout(r),Ks&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ks&&(t=requestAnimationFrame(n))}function Or(e){var t=fe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),fe=t}function _o(e){var t=fe;e.__c=e.__(),fe=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function qs(e,t){return typeof t=="function"?t(e):t}function Xs(e,t){for(var n in t)e[n]=t[n];return e}function yo(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function So(e,t){var n=t(),r=V({t:{__:n,u:t}}),o=r[0].t,i=r[1];return mt(function(){o.__=n,o.u=t,bo(o)&&i({t:o})},[e,n,t]),H(function(){return bo(o)&&i({t:o}),e(function(){bo(o)&&i({t:o})})},[e]),n}function bo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function vo(e){e()}function wo(e){return e}function No(){return[!1,vo]}var Co=mt;function Rr(e,t){this.props=e,this.context=t}function Xt(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,et(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Rr.prototype=new lt).isPureReactComponent=!0,Rr.prototype.shouldComponentUpdate=function(e,t){return yo(this.props,e)||yo(this.state,t)};var Zs=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Zs&&Zs(e)};var ld=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=Xs({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=ld,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Js=function(e,t){return e==null?null:At(At(e).map(t))},ot={map:Js,forEach:Js,count:function(e){return e?At(e).length:0},only:function(e){var t=At(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:At},cd=Z.__e;Z.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t)}cd(e,t,n,r)};var Qs=Z.unmount;function ei(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Xs({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return ei(r,t,n)})),e}function ti(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ti(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Ze(){this.__u=0,this.o=null,this.__b=null}function ni(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function tt(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(a){a&&(o=a.default||a),r=!0},function(a){n=a,r=!0}),n)throw n;if(!r)throw t;return o?et(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function mn(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Qs&&Qs(e)},(Ze.prototype=new lt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ni(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(l):l())};n.__R=s;var a=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ti(d,d.__c.__P,d.__c.__O)}var h;for(r.setState({__a:r.__b=null});h=r.o.pop();)h.__P=a,h.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},Ze.prototype.componentWillUnmount=function(){this.o=[]},Ze.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=ei(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&et(me,null,e.fallback);return o&&(o.__u&=-33),[et(me,null,t.__a?null:e.children),o]};var ri=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function dd(e){return this.getChildContext=function(){return e.context},e.children}function ud(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Fn(et(dd,{context:t.context},e.__v),t.v)}function oi(e,t){var n=et(ud,{__v:e,h:t});return n.containerInfo=t,n}(mn.prototype=new lt).__a=function(e){var t=this,n=ni(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),ri(t,e,r)):o()};n?n(i):i()}},mn.prototype.render=function(e){this.i=null,this.l=new Map;var t=At(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},mn.prototype.componentDidUpdate=mn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){ri(e,n,t)})};var si=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,hd=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,md=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,pd=/[A-Z0-9]/g,fd=typeof document<"u",gd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Fn(e,t),typeof n=="function"&&n(),e?e.__c:null}function ii(e,t,n){return Vs(e,t),typeof n=="function"&&n(),e?e.__c:null}lt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(lt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ai=Z.event;Z.event=function(e){return ai&&(e=ai(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var To,_d={configurable:!0,get:function(){return this.class}},li=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||fd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||gd(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":md.test(s)&&(s=l):l=s="oninput":i&&hd.test(s)?s=s.replace(pd,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&o[s=l]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=At(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=At(n.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",_d)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=si,li&&li(e)};var ci=Z.__r;Z.__r=function(e){ci&&ci(e),To=e.__c};var di=Z.diffed;Z.diffed=function(e){di&&di(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),To=null};var ui={ReactCurrentDispatcher:{current:{readContext:function(e){return To.__n[e.__c].props.value},useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:H,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:hn,useRef:q,useState:V,useSyncExternalStore:So,useTransition:No}}},Ed="18.3.1";function hi(e){return et.bind(null,e)}function st(e){return!!e&&e.$$typeof===si}function mi(e){return st(e)&&e.type===me}function pi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Ft(e){return st(e)?rd.apply(null,arguments):e}function ko(e){return!!e.__k&&(Fn(null,e),!0)}function fi(e){return e&&(e.base||e.nodeType===1&&e)||null}var gi=function(e,t){return e(t)},_i=function(e,t){var n=Z.debounceRendering;Z.debounceRendering=function(o){return o()};var r=e(t);return Z.debounceRendering=n,r},Ei=st,Vn={useState:V,useId:go,useReducer:hn,useEffect:H,useLayoutEffect:mt,useInsertionEffect:Co,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:vo,useRef:q,useImperativeHandle:po,useMemo:ae,useCallback:de,useContext:vt,useDebugValue:fo,version:"18.3.1",Children:ot,render:xo,hydrate:ii,unmountComponentAtNode:ko,createPortal:oi,createElement:et,createContext:bt,createFactory:hi,cloneElement:Ft,createRef:Rs,Fragment:me,isValidElement:st,isElement:Ei,isFragment:mi,isMemo:pi,findDOMNode:fi,Component:lt,PureComponent:Rr,memo:Xt,forwardRef:ee,flushSync:_i,unstable_batchedUpdates:gi,StrictMode:me,Suspense:Ze,SuspenseList:mn,lazy:tt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:ot,Component:lt,Fragment:me,PureComponent:Rr,StrictMode:me,Suspense:Ze,SuspenseList:mn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui,cloneElement:Ft,createContext:bt,createElement:et,createFactory:hi,createPortal:oi,createRef:Rs,default:Vn,findDOMNode:fi,flushSync:_i,forwardRef:ee,hydrate:ii,isElement:Ei,isFragment:mi,isMemo:pi,isValidElement:st,lazy:tt,memo:Xt,render:xo,startTransition:vo,unmountComponentAtNode:ko,unstable_batchedUpdates:gi,useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:H,useErrorBoundary:sd,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:hn,useRef:q,useState:V,useSyncExternalStore:So,useTransition:No,version:Ed},Symbol.toStringTag,{value:"Module"}));function yd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function yi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ro(...e){return t=>{let n=!1;const r=e.map(o=>{const i=yi(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():yi(e[o],null)}}}}function Vt(...e){return de(Ro(...e),e)}function Sd(e){const t=bd(e),n=ee((r,o)=>{const{children:i,...s}=r,a=ot.toArray(i),l=a.find(wd);if(l){const d=l.props.children,h=a.map(u=>u===l?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:st(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function bd(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(st(o)){const s=Cd(o),a=Nd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vd=Symbol("radix.slottable");function wd(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===vd}function Nd(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Cd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var xd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=xd.reduce((e,t)=>{const n=Sd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Zt=globalThis?.document?mt:()=>{};function Td(e,t){return hn((n,r)=>t[n][r]??n,e)}var fn=e=>{const{present:t,children:n}=e,r=kd(t),o=typeof n=="function"?n({present:r.isPresent}):ot.only(n),i=Vt(r.ref,Od(o));return typeof n=="function"||r.isPresent?Ft(o,{ref:i}):null};fn.displayName="Presence";function kd(e){const[t,n]=V(),r=q(null),o=q(e),i=q("none"),s=e?"mounted":"unmounted",[a,l]=Td(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return H(()=>{const d=Ar(r.current);i.current=a==="mounted"?d:"none"},[a]),Zt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Ar(d);e?l("MOUNT"):p==="none"||d?.display==="none"?l("UNMOUNT"):l(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Zt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const g=Ar(r.current).includes(CSS.escape(E.animationName));if(E.target===t&&g&&(l("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=E=>{E.target===t&&(i.current=Ar(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:de(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Ar(e){return e?.animationName||"none"}function Od(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Si(e,t=[]){let n=[];function r(i,s){const a=bt(s),l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[l]||a,b=ae(()=>g,Object.values(g));return c(f.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[l]||a,g=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Rd(o,...t)]}function Rd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function jt(e){const t=q(e);return H(()=>{t.current=e}),ae(()=>(...n)=>t.current?.(...n),[])}var Ad=bt(void 0);function Id(e){const t=vt(Ad);return e||t||"ltr"}function Md(e,[t,n]){return Math.min(n,Math.max(t,e))}function zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Pd(e,t){return hn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[bi]=Si(Ao),[Dd,ct]=bi(Ao),vi=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,l]=V(null),[d,h]=V(null),[u,p]=V(null),[E,g]=V(null),[f,b]=V(null),[m,_]=V(0),[y,k]=V(0),[x,w]=V(!1),[T,S]=V(!1),v=Vt(t,L=>l(L)),C=Id(o);return c(Dd,{scope:n,type:r,dir:C,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:E,onScrollbarXChange:g,scrollbarXEnabled:x,onScrollbarXEnabledChange:w,scrollbarY:f,onScrollbarYChange:b,scrollbarYEnabled:T,onScrollbarYEnabledChange:S,onCornerWidthChange:_,onCornerHeightChange:k,children:c(pn.div,{dir:C,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});vi.displayName=Ao;var wi="ScrollAreaViewport",Ni=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ct(wi,n),a=q(null),l=Vt(t,a,s.onViewportChange);return c(me,{children:[c("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),c(pn.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ni.displayName=wi;var wt="ScrollAreaScrollbar",Io=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return H(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?c(Ld,{...r,ref:t,forceMount:n}):o.type==="scroll"?c(Ud,{...r,ref:t,forceMount:n}):o.type==="auto"?c(Ci,{...r,ref:t,forceMount:n}):o.type==="always"?c(Mo,{...r,ref:t}):null});Io.displayName=wt;var Ld=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),[i,s]=V(!1);return H(()=>{const a=o.scrollArea;let l=0;if(a){const d=()=>{window.clearTimeout(l),s(!0)},h=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),c(fn,{present:n||i,children:c(Ci,{"data-state":i?"visible":"hidden",...r,ref:t})})}),Ud=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Dr(()=>l("SCROLL_END"),100),[a,l]=Pd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return H(()=>{if(a==="idle"){const d=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,l]),H(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const p=()=>{const E=d[h];u!==E&&(l("SCROLL"),s()),u=E};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[o.viewport,i,l,s]),c(fn,{present:n||a!=="hidden",children:c(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:zt(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:zt(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Ci=ee((e,t)=>{const n=ct(wt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=V(!1),a=e.orientation==="horizontal",l=Dr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return gn(n.viewport,l),gn(n.content,l),c(fn,{present:r||i,children:c(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=ct(wt,e.__scopeScrollArea),i=q(null),s=q(0),[a,l]=V({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ri(a.viewport,a.content),h={...r,sizes:a,onSizesChange:l,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,E){return Yd(p,s.current,a,E)}return n==="horizontal"?c(Fd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,E=Ai(p,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?c(Vd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,E=Ai(p,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Fd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=V(),l=q(null),d=Vt(t,l,i.onScrollbarXChange);return H(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(Ti,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(p),Mi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Mr(s.paddingLeft),paddingEnd:Mr(s.paddingRight)}})}})}),Vd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=V(),l=q(null),d=Vt(t,l,i.onScrollbarYChange);return H(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(Ti,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(p),Mi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Mr(s.paddingTop),paddingEnd:Mr(s.paddingBottom)}})}})}),[jd,xi]=bi(wt),Ti=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:d,onWheelScroll:h,onResize:u,...p}=e,E=ct(wt,n),[g,f]=V(null),b=Vt(t,v=>f(v)),m=q(null),_=q(""),y=E.viewport,k=r.content-r.viewport,x=jt(h),w=jt(l),T=Dr(u,10);function S(v){if(m.current){const C=v.clientX-m.current.left,L=v.clientY-m.current.top;d({x:C,y:L})}}return H(()=>{const v=C=>{const L=C.target;g?.contains(L)&&x(C,k)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[y,g,k,x]),H(w,[r,w]),gn(g,T),gn(E.content,T),c(jd,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:jt(i),onThumbPointerUp:jt(s),onThumbPositionChange:w,onThumbPointerDown:jt(a),children:c(pn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:zt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),m.current=g.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),S(v))}),onPointerMove:zt(e.onPointerMove,S),onPointerUp:zt(e.onPointerUp,v=>{const C=v.target;C.hasPointerCapture(v.pointerId)&&C.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Ir="ScrollAreaThumb",ki=ee((e,t)=>{const{forceMount:n,...r}=e,o=xi(Ir,e.__scopeScrollArea);return c(fn,{present:n||o.hasThumb,children:c(zd,{ref:t,...r})})}),zd=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ct(Ir,n),s=xi(Ir,n),{onThumbPositionChange:a}=s,l=Vt(t,u=>s.onThumbChange(u)),d=q(void 0),h=Dr(()=>{d.current&&(d.current(),d.current=void 0)},100);return H(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const E=Hd(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),c(pn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:zt(e.onPointerDownCapture,u=>{const p=u.target.getBoundingClientRect(),E=u.clientX-p.left,g=u.clientY-p.top;s.onThumbPointerDown({x:E,y:g})}),onPointerUp:zt(e.onPointerUp,s.onThumbPointerUp)})});ki.displayName=Ir;var Po="ScrollAreaCorner",Oi=ee((e,t)=>{const n=ct(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c($d,{...e,ref:t}):null});Oi.displayName=Po;var $d=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ct(Po,n),[i,s]=V(0),[a,l]=V(0),d=!!(i&&a);return gn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),l(h)}),gn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?c(pn.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Mr(e){return e?parseInt(e,10):0}function Ri(e,t){const n=e/t;return isNaN(n)?0:n}function Pr(e){const t=Ri(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Yd(e,t,n,r="ltr"){const o=Pr(n),i=o/2,s=t||i,a=o-s,l=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return Ii([l,d],u)(e)}function Ai(e,t,n="ltr"){const r=Pr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],d=Md(e,l);return Ii([0,s],[0,a])(d)}function Ii(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mi(e,t){return e>0&&e<t}var Hd=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function Dr(e,t){const n=jt(e),r=q(0);return H(()=>()=>window.clearTimeout(r.current),[]),de(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function gn(e,t){const n=jt(t);Zt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Pi=vi,Bd=Ni,Gd=Oi;function Wd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var _n={},jn={},Di={},zn={},$n={},Yn={},Li;function Do(){if(Li)return Yn;Li=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.EventEmitter=void 0;let e=class{constructor(){R(this,"eventListeners",new Map)}on(t,n){const r=this.eventListeners.get(t)||new Set;r.add(n),this.eventListeners.set(t,r)}off(t,n){const r=this.eventListeners.get(t);r&&(r.delete(n),r.size===0&&this.eventListeners.delete(t))}emit(t,...n){const r=this.eventListeners.get(t);r&&r.forEach(o=>o(...n))}removeAllListeners(){this.eventListeners.clear()}};return Yn.EventEmitter=e,Yn}var En={},Ui;function Hn(){return Ui||(Ui=1,Object.defineProperty(En,"__esModule",{value:!0}),En.DisconnectionReason=En.ConnectionStatus=void 0,En.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},En.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),En}var Fi;function Lo(){if(Fi)return $n;Fi=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.BaseConnection=void 0;const e=Do(),t=Hn();let n=class{constructor(){R(this,"status",t.ConnectionStatus.CONNECTING);R(this,"queue",[]);R(this,"eventEmitter",new e.EventEmitter);R(this,"disconnectionDetails",null);R(this,"onErrorCallback",null);R(this,"onDisconnectCallback",null);R(this,"onMessageCallback",null);R(this,"onOpenCallback",null);R(this,"onStatusChangeCallback",null)}getStatus(){return this.status}onOpen(r){this.onOpenCallback=r}onMessage(r){if(this.onMessageCallback=r,this.queue.length>0){const o=[...this.queue];this.queue.length=0,queueMicrotask(()=>{o.forEach(i=>{this.onMessageCallback?.(i)})})}}onDisconnect(r){this.onDisconnectCallback=r;const o=this.disconnectionDetails;o&&queueMicrotask(()=>{this.onDisconnectCallback?.(o)})}onError(r){this.onErrorCallback=r}on(r,o){this.eventEmitter.on(r,o)}off(r,o){this.eventEmitter.off(r,o)}emit(r,...o){this.eventEmitter.emit(r,...o)}onStatusChange(r){this.onStatusChangeCallback=r,queueMicrotask(()=>{r(this.status)})}disconnect(r){this.disconnectionDetails||(this.disconnectionDetails=r,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.onDisconnectCallback?.(r))}handleMessage(r){this.onMessageCallback?this.onMessageCallback(r):this.queue.push(r)}updateStatus(r){this.status!==r&&(this.status=r,this.onStatusChangeCallback?.(r))}};return $n.BaseConnection=n,$n}var Vi={},ji;function it(){return ji||(ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=x,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(S,v=e.SynapseErrorCode.UNKNOWN,C={}){super(S);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=v,this.timestamp=new Date,this.cause=C.cause,this.context=C.context,this.hint=C.hint,this.reason=C.reason,this.displayMessage=C.displayMessage||C?.hint||S,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(S,v,C,L){const X=n.makeMessage(v,C,S);super(X,e.SynapseErrorCode.API,{cause:C,context:{status:v,hasBody:!!C},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:S||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=C,this.headers=L}static makeMessage(S,v,C){const L=v instanceof Error?v.message:C;return S&&L?`HTTP ${S}: ${L}`:S?`${S} status code (no body)`:L||"(no status code or body)"}static generate(S,v,C,L){if(!S)return new r({message:C});const X=v?.error,G=X&&typeof X=="object"&&!Array.isArray(X)?X:void 0;switch(S){case 400:return new i(C||"Bad Request",S,G,L);case 401:return new s(C||"Unauthorized",S,G,L);case 403:return new a(C||"Permission Denied",S,G,L);case 404:return new l(C||"Not Found",S,G,L);case 405:return new d(C||"Method Not Allowed",S,G,L);case 429:return new h(C||"Rate Limit Exceeded",S,G,L);case 500:return new u(C||"Internal Server Error",S,G,L);default:return new n(C||"API Error",S,G,L)}}}e.APIError=n;class r extends n{constructor({message:T}={}){super(T||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:T}={}){super(T||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class l extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="NotFoundError"}}e.NotFoundError=l;class d extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.CONNECTION,S),this.name="ConnectionError"}}e.ConnectionError=p;class E extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.RECORDING,S),this.name="RecordingError"}}e.RecordingError=E;class g extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.AUTH,S),this.name="AuthenticationError"}}e.AuthenticationError=g;class f extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.FILE,S),this.name="FileError"}}e.FileError=f;class b extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.SESSION,S),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.MESSAGE,S),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.STORE,S),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.CONFIGURATION,S),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.VALIDATION,S),this.name="ValidationError"}}e.ValidationError=k;function x(w,T,S,v={}){if(w instanceof T)return w;const C={...v,context:{...w instanceof t?w.context:void 0,...v.context},hint:v.hint??(w instanceof t?w.hint:void 0),reason:v.reason??(w instanceof t?w.reason:void 0),cause:v.cause??w};if(w instanceof t)return new T(w.message,C);const L=w instanceof Error&&w.message?w.message:S;return new T(L,C)}})(Vi)),Vi}var zi;function $i(){if(zi)return zn;zi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.WebSocketConnection=void 0;const e=Lo(),t=Hn(),n=it();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const l=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(l)}}handleError(s){}handleClose(s){const a=s.wasClean,l=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(l===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):l===1001||l===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):l===4001||l===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):l===4401||l===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(l===4401?"Session token expired":"Session credentials rejected")):l===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):l===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:l,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const l=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(l),l}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return zn.WebSocketConnection=r,zn}var Bn={},Yi={},Hi;function Bi(){return Hi||(Hi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=void 0,e.SYNAPSE_CHANNELS={WIDGET:"widget",WEB:"web",SIDE_PANEL:"side_panel"},e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS.WIDGET})(Yi)),Yi}var Gi;function Wi(){if(Gi)return Bn;Gi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.SSEConnection=void 0;const e=Lo(),t=Hn(),n=Bi(),r=it();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const l=new AbortController;this.activeStreamController=l,this.streamChat(a,l)}postChat(a,l,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(l),signal:d.signal})}async streamChat(a,l){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,l);if(h.status===401&&this.config.auth.onUnauthorized){const g=await this.config.auth.onUnauthorized();if(l.signal.aborted)return;g&&(h=await this.postChat(d,a,l))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),p=new TextDecoder;let E="";for(;;){const{done:g,value:f}=await u.read();if(g)break;E+=p.decode(f,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(l.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===l&&(this.activeStreamController=null)}}extractJsonObjects(a){let l=0;for(;l<a.length;){const d=a.indexOf("{",l);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const p=JSON.parse(u);this.handleMessage(p)}catch(p){const E=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(E)}l=h+1}return""}findObjectEnd(a,l){let d=0,h=!1,u=!1;for(let p=l;p<a.length;p++){const E=a[p];if(h){u?u=!1:E==="\\"?u=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")d++;else if(E==="}"&&(d--,d===0))return p}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Bn.SSEConnection=o,Bn}var Ki;function qi(){return Ki||(Ki=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=$i(),n=Wi(),r=it();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(Di)),Di}var Gn={},Xi;function Uo(){if(Xi)return Gn;Xi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix-ws.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Gn.getConfig=r,Gn}var Wn={},Kn={},Zi;function Lr(){if(Zi)return Kn;Zi=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.HttpClient=void 0;const e=it();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const l=this.buildUrl(r,o?.params),d=await fetch(l,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(l){if(s=l,a===i||!(l instanceof TypeError&&l.message==="Failed to fetch"||l instanceof DOMException&&l.name==="AbortError"||l instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Kn.HttpClient=t,Kn}var qn={},Xn={},Ji;function Zn(){if(Ji)return Xn;Ji=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.BaseResource=void 0;let e=class{constructor(t){R(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return Xn.BaseResource=e,Xn}var Qi;function ea(){if(Qi)return qn;Qi=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Session=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:l}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...l&&{nps_base5:l}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return qn.Session=t,qn}var Jn={},ta;function Fo(){if(ta)return Jn;ta=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.Config=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return Jn.Config=t,Jn}var na={},ra;function oa(){return ra||(ra=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Lr(),n=Uo(),r=Fo(),o=new Map,i=(l,d)=>`${l.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(l){const d=l.serverUrl||(0,n.getConfig)(l.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,l.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":l.agentId,...l.channel&&{"x-channel":l.channel}}}),E=new r.Config(p).retrieve(l.agentId);return E.catch(()=>{o.get(h)===E&&o.delete(h)}),o.set(h,E),E}function a(l){const d=o.get(l);return d&&o.delete(l),d}})(na)),na}var Qn={},sa;function Vo(){if(sa)return Qn;sa=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.Auth=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Qn.Auth=t,Qn}var er={},yn={},ia;function jo(){return ia||(ia=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.ErrorType=yn.SYNAPSE_RECOVERY_REASON=void 0,yn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},yn.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),yn}var tr={},aa;function zo(){if(aa)return tr;aa=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.ErrorUtils=void 0;const e=it();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return tr.ErrorUtils=t,tr}var la={},ca;function da(){return ca||(ca=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=l;const t=Lr(),n=Uo(),r=zo(),o=Vo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),p=i.get(u);if(p)return p;const E=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),g=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return g.catch(f=>{r.ErrorUtils.isAuthError(f)||i.get(u)===g&&i.delete(u)}),i.set(u,g),g}function l(d){const h=i.get(d);return h&&i.delete(d),h}})(la)),la}var ua;function Kd(){if(ua)return er;ua=1,Object.defineProperty(er,"__esModule",{value:!0}),er.TokenManager=void 0;const e=it(),t=jo(),n=zo(),r=da();let o=class{constructor(i,s,a,l){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=l.partnerAuthToken,this.refreshToken=l.refreshToken,this.onTokenExchange=l.onTokenExchange,this._level=l.level,this._userId=l.userId,l.sessToken&&(this.sessToken=l.sessToken,this.httpClient.setAuthorization(l.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(l.serverUrl,a,l.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,l){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,l,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return er.TokenManager=o,er}var nr={},ha;function qd(){var n;if(ha)return nr;ha=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceResource=void 0;const e=Zn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return nr.VoiceResource=t,nr}var ma;function pa(){if(ma)return Wn;ma=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ResourceManager=void 0;const e=Lr(),t=ea(),n=it(),r=Fo(),o=oa(),i=Vo(),s=Kd(),a=qd();class l{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:p,intent:E,user_location:g,referer:f,...b}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...p&&{user_context:p},...(E||Object.keys(b).length>0)&&{session_context:{...E&&{intent:E},...g&&{user_location:g},...b}},...f&&{referer:f}},y=await this.session.create(_);if(!y?.session_id)throw new n.APIError("Failed to start session.",500,void 0,void 0);return y}catch(p){throw p instanceof n.APIError?p:new n.APIError("Failed to start session.",500,void 0,void 0)}}async getAgentConfig(){this.config||(this.config=new r.Config(this.httpClient));const h=(0,o.consumePrefetchedAgentConfig)((0,o.buildAgentConfigKey)(this.resourceConfig.serverUrl,this.resourceConfig.agentId));if(h)try{return await h}catch{}try{return await this.config.retrieve(this.resourceConfig.agentId)}catch{throw new n.APIError("Failed to get agent config.",500,void 0,void 0)}}async reinitialiseSession(h){return await this.session.retrieve(h)}async getPastSessions(){return await this.session.history()}async getSessionMessages(h){return(await this.session.retrieve(h,{includeMessages:!0}))?.messages??[]}async refreshTokens(){return await this.tokenManager.refresh()}async sendFeedback({sessionId:h,messageId:u,feedback:p,feedbacks:E,feedbackReason:g,npsBase5:f}){return await this.session.feedback({sessionId:h,messageId:u,feedback:p,feedbacks:E,feedbackReason:g,npsBase5:f})}async callTool(h,u,p,E){return await this.session.callTool(h,u,p,E)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Wn.ResourceManager=l,Wn}var rr={},fa={},ga;function $o(){return ga||(ga=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MULTI_SELECT_ADDITIONAL_OPTION=e.SOCKET_EVENTS=e.SOCKET_CONTENT_TYPES=void 0,e.IsValidSocketMesssage=t,e.SOCKET_CONTENT_TYPES={TEXT:"text",AUDIO:"audio",FILE:"file",TOOL_CALL:"tool",TIPS:"tips",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},e.SOCKET_EVENTS={PING:"ping",PONG:"pong",CHAT:"chat",STREAM:"stream",AUTH:"auth",END_OF_STREAM:"eos",SYNC:"sync",ERROR:"err",CONNECTION_ESTABLISHED:"conn"},e.MULTI_SELECT_ADDITIONAL_OPTION={NOTA:"none_of_the_above",AOTA:"all_of_the_above"};function t(n){return[e.SOCKET_EVENTS.PING,e.SOCKET_EVENTS.PONG,e.SOCKET_EVENTS.ERROR,e.SOCKET_EVENTS.SYNC,e.SOCKET_EVENTS.CONNECTION_ESTABLISHED,e.SOCKET_EVENTS.CHAT,e.SOCKET_EVENTS.STREAM,e.SOCKET_EVENTS.END_OF_STREAM].includes(n.ev)}})(fa)),fa}var _a={},Ea;function Xd(){return Ea||(Ea=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=it();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[]);R(this,"pendingSizes",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type),this.pendingSizes=s.map(a=>a.size)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[],sizes:this.pendingSizes||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.map((a,l)=>({entry:a,file:this.pendingFiles[l]})).filter(({entry:a,file:l})=>l&&a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const{entry:l,file:d}=s[a],h=await fetch(l.url,this.buildUploadRequest(l,d));if(!h.ok)throw new t.FileError(`Failed to upload ${d.name} to URL ${a+1}: ${h.status} ${h.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(l.id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}buildUploadRequest(o,i){if(o.fields){const s=new FormData;for(const[a,l]of Object.entries(o.fields))s.append(a,l);return s.append("file",i),{method:"POST",body:s}}return{method:"PUT",body:i,headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"}}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[],this.pendingSizes=[]}}e.Filemanager=n})(_a)),_a}var pt={},ya;function Ur(){if(ya)return pt;ya=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.SYNAPSE_REALTIME_RESERVED_EVENTS=pt.SYNAPSE_REALTIME_ERROR_CODES=pt.SYNAPSE_REALTIME_EVENTS=pt.SYNAPSE_MESSAGE_TYPES=void 0;const e=$o();return pt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,pt.SYNAPSE_REALTIME_EVENTS={CONNECTED:"connected",DISCONNECTED:"disconnected",PROGRESS_MESSAGE:"progress_message",MESSAGE_CHUNK:"message_chunk",TIPS_MESSAGE:"tips_message",END_OF_STREAM:"end_of_stream",ERROR:"error",TOOL_CALL:"tool_call",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},pt.SYNAPSE_REALTIME_ERROR_CODES={SESSION_INACTIVE:"session_not_found",SESSION_TOKEN_EXPIRED:"sess_token_expired",INVALID_EVENT:"invalid_event",INVALID_CONTENT_TYPE:"invalid_content",PARSING_ERROR:"parsing",FILE_UPLOAD_INPROGRESS:"file_upload_inprogress",TIMEOUT:"timeout",SERVER_ERROR:"server_error",SESSION_TOKEN_MISMATCH:"session_token_mismatch",PROMPT_FETCH_ERROR:"prompt_fetch_error",INVALID_FILE_REQUEST:"invalid_file_request",SESSION_NOT_OWNED:"session_not_owned"},pt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},pt}var or={},Sa;function Zd(){if(Sa)return or;Sa=1,Object.defineProperty(or,"__esModule",{value:!0}),or.AudioManager=void 0;const e=it();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return or.AudioManager=t,or}var ba;function va(){if(ba)return rr;ba=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.MessageManager=void 0;const e=$o(),t=Xd(),n=Ur(),r=Zd(),o=it();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:l,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,file_sizes:this.fileManager.getPendingFileState().sizes,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(l&&l.length>0){const p=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:l,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:l,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...l&&{audio:l},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},...E&&{initial_prompts:E}};return}const g=this.connection;let f;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}f=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:p})}else s?f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},...E&&{initial_prompts:E},...p&&{tool_result:p}}}:l&&l?.audio&&l?.format?f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:l?.audio,format:l?.format,...h&&{tool_declined:h},...p&&{tool_result:p}}}:p&&(f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:p}});if(!f){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g.sendMessage(f)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(l=>{this.sendSocketMessage({urls:l})}).catch(l=>{const d=this.toFileError(l,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,l)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const l={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,l)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,l)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const l={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,l);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const l=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),l={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(l)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const l=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(l),l}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,l=>{const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(l){const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,l,d){return(0,o.normalizeError)(s,o.FileError,a,{context:l,hint:d})}toRecordingError(s,a,l,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:l,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return rr.MessageManager=i,rr}var wa={},Na;function Jd(){return Na||(Na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.outcomeForHttpStatus=e.outcomeForCloseCode=e.RECOVERY_OUTCOME=void 0,e.RECOVERY_OUTCOME={REFRESH_AND_RETRY:"refresh_and_retry",FORBIDDEN:"forbidden",SESSION_GONE:"session_gone",RETRY_LATER:"retry_later",SESSION_NOT_OWNED:"session_not_owned"};const t={4401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,4403:e.RECOVERY_OUTCOME.FORBIDDEN,4404:e.RECOVERY_OUTCOME.SESSION_GONE,1013:e.RECOVERY_OUTCOME.RETRY_LATER},n={401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,403:e.RECOVERY_OUTCOME.FORBIDDEN,404:e.RECOVERY_OUTCOME.SESSION_GONE,429:e.RECOVERY_OUTCOME.RETRY_LATER,503:e.RECOVERY_OUTCOME.RETRY_LATER},r=i=>i===void 0?void 0:t[i];e.outcomeForCloseCode=r;const o=i=>i===void 0?void 0:n[i];e.outcomeForHttpStatus=o})(wa)),wa}var sr={},ir={},Ca;function Qd(){if(Ca)return ir;Ca=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),l=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(l)};l()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return ir.VoiceAudioAnalyser=t,ir}var Sn={},xa;function Ta(){return xa||(xa=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.VOICE_AGENT_EVENTS=Sn.VOICE_AGENT_STATE=void 0,Sn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Sn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Sn}var ka;function eu(){if(ka)return sr;ka=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.VoiceAgent=void 0;const e=Do(),t=Qd(),n=it(),r=Ta(),o=3e3,i=8,s=3600*1e3,a=600;function l(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const E=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),p())}})}let d=class{constructor(h,u,p){R(this,"config");R(this,"resourceManager");R(this,"getCredentials");R(this,"emitter",new e.EventEmitter);R(this,"remoteAnalyser",new t.VoiceAudioAnalyser);R(this,"localAnalyser",new t.VoiceAudioAnalyser);R(this,"pc",null);R(this,"pcId",null);R(this,"dataChannel",null);R(this,"localStream",null);R(this,"remoteAudio",null);R(this,"_state",r.VOICE_AGENT_STATE.IDLE);R(this,"_isMuted",!1);R(this,"manuallyDisconnected",!1);R(this,"_hasConnectionFailureNotified",!1);R(this,"_userSpeaking",!1);R(this,"_silenceTimer",null);R(this,"_cachedIceServers",null);R(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=p}get state(){return this._state}get isMuted(){return this._isMuted}on(h,u){this.emitter.on(h,u)}off(h,u){this.emitter.off(h,u)}async connect(){const h=await this.getCredentials();this.setState(r.VOICE_AGENT_STATE.CONNECTING),this._hasConnectionFailureNotified=!1;try{if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available. Please ensure you are using a secure (HTTPS) connection.");const u=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=u;const p=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:p,iceTransportPolicy:"all"});this.pc=E,this.dataChannel=E.createDataChannel("pipecat-events",{ordered:!0}),this.dataChannel.onopen=()=>{},this.dataChannel.onclose=()=>this.handleConnectionFailure(new Error("Data channel closed"),"Voice connection failed"),this.dataChannel.onerror=()=>this.handleConnectionFailure(new Error("Data channel error"),"Voice connection failed"),u.getAudioTracks().forEach(_=>E.addTrack(_,u)),E.ontrack=_=>this.handleRemoteTrack(_),E.onconnectionstatechange=()=>{E.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(E.connectionState==="failed"||E.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},E.oniceconnectionstatechange=()=>{(E.iceConnectionState==="connected"||E.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):E.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const g=await E.createOffer();await E.setLocalDescription(g);const f=this.config.iceGatheringTimeoutMs??o;await l(E,f);const b=_=>({sdp:E.localDescription.sdp,type:E.localDescription.type,pc_id:this.pcId,request_data:{session_id:_.sessionId,token:_.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(b(h))}catch(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(b(y))}else throw _}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,E.signalingState==="closed")return;await E.setRemoteDescription(new RTCSessionDescription({sdp:m.sdp,type:m.type}))}catch(u){this.handleConnectionFailure(u)}}disconnect(){this.manuallyDisconnected=!0,this.setState(r.VOICE_AGENT_STATE.DISCONNECTING),this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE)}toggleMute(){if(!this.localStream)return;const h=this.localStream.getAudioTracks()[0];if(!h)return;const u=h.enabled;this.localStream.getAudioTracks().forEach(p=>{p.enabled=!u}),this._isMuted=u,this.clearSilenceTimer(),this._userSpeaking=!1,this.setState(u?r.VOICE_AGENT_STATE.MUTED:r.VOICE_AGENT_STATE.LISTENING)}reset(){this.setState(r.VOICE_AGENT_STATE.IDLE)}destroy(){this.releaseResources(),this.emitter.removeAllListeners(),this._state=r.VOICE_AGENT_STATE.IDLE}async fetchIceServers(h){if(this.config.iceServers)return this.config.iceServers;const u=Date.now();if(this._cachedIceServers&&u-this._iceServersCachedAt<s)return this._cachedIceServers;let p;try{p=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const g=await this.getCredentials();p=await this.resourceManager.getVoiceIceServers(g.sessionId)}else throw E}if(!Array.isArray(p?.ice_servers)||p.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=p.ice_servers,this._iceServersCachedAt=Date.now(),this._cachedIceServers}setState(h){this._state=h,this.emitter.emit(r.VOICE_AGENT_EVENTS.STATE_CHANGED,h)}clearSilenceTimer(){this._silenceTimer!==null&&(clearTimeout(this._silenceTimer),this._silenceTimer=null)}handleConnectionFailure(h,u="Voice connection failed"){if(this._hasConnectionFailureNotified||this._state===r.VOICE_AGENT_STATE.DISCONNECTING||this.manuallyDisconnected)return;this._hasConnectionFailureNotified=!0,this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.ERROR);const p={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,p)}releaseResources(){this.remoteAnalyser.stop(),this.localAnalyser.stop(),this.clearSilenceTimer(),this._userSpeaking=!1,this.localStream&&(this.localStream.getTracks().forEach(h=>h.stop()),this.localStream=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.pc&&(this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.ondatachannel=null,this.pc.close(),this.pc=null),this.pcId=null,this._isMuted=!1,this.remoteAudio&&(this.remoteAudio.srcObject=null)}startLocalAudioAnalysis(h){const u=this.config.speakingThreshold??i;this.localAnalyser.start(h,u,p=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(p?(this._userSpeaking=!0,this.clearSilenceTimer(),this._state===r.VOICE_AGENT_STATE.THINKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)):this._userSpeaking&&this._silenceTimer===null&&(this._silenceTimer=setTimeout(()=>{this._silenceTimer=null,this._userSpeaking&&this._state===r.VOICE_AGENT_STATE.LISTENING&&(this._userSpeaking=!1,this.setState(r.VOICE_AGENT_STATE.THINKING))},a)))})}handleRemoteTrack(h){this.remoteAudio||(this.remoteAudio=new Audio,this.remoteAudio.autoplay=!0);const u=h.streams[0];this.remoteAudio.srcObject=u;const p=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,p,E=>{E?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return sr.VoiceAgent=d,sr}var Oa;function tu(){if(Oa)return jn;Oa=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.SynapseSDK=void 0;const e=qi(),t=Hn(),n=Uo(),r=pa(),o=va(),i=Ur(),s=Do(),a=it(),l=jo(),d=Jd(),h=$o(),u=eu();class p{constructor(g){R(this,"connection",null);R(this,"messageManager");R(this,"resourceManager");R(this,"sessionConfig",null);R(this,"config");R(this,"connectionType");R(this,"isRefreshingSession",!1);R(this,"isRecovering",!1);R(this,"forceConsumed",!1);R(this,"connectionAttempts",0);R(this,"sdkEventEmitter",new s.EventEmitter);R(this,"_voice",null);R(this,"pendingNetworkReconnect",!1);R(this,"boundOnlineHandler",null);R(this,"isReconnecting",!1);R(this,"reconnectTimer",null);R(this,"boundVisibilityHandler",null);R(this,"isSessionNotOwned",!1);this.config={...g,environment:g.environment||"production"},this.connectionType=g.connectionType||e.ConnectionType.HTTP_STREAM;const f=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||f,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const g=await this.resourceManager.refreshBearer();if(!g)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(f){this.emitError(this.toConnectionError(f,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return g}async startSession(g){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,g=void 0),await this.resourceManager.ensureCredentials();const f=g?.session_id?g:await this.createNewSession();return await this.initializeConnection(f),this.setupEventHandlers(),f}catch(f){throw this.emitError(f),f}}async sendMessage({message:g,files:f,audio:b,tool_declined:m,tool_id:_,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:g,files:f,audio:b,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(w){this.emitError(w)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(g,f,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:g,feedback:f,feedbackReason:b});break}}async sendSessionFeedback(g,f){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!g?.length&&!f){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:g,npsBase5:f});break}}on(g,f){this.sdkEventEmitter.on(g,f)}off(g,f){this.sdkEventEmitter.off(g,f)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(g){return await this.resourceManager.getSessionMessages(g)}async callTool(g,f,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,g,f,b);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let _={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,_);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:g,onError:f}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:g,onError:f})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const g=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(g),g}}async getAgentConfig(){return this.resourceManager.getAgentConfig()}isConnected(){return this.connection?.isConnected()??!1}clearTokens(){this.resourceManager.clearTokens()}get voice(){return this._voice||(this._voice=new u.VoiceAgent(this.buildVoiceConfig(),this.resourceManager,async()=>(await this.resourceManager.exchangeInit(),{sessionId:(await this.resourceManager.createSession()).session_id,sessionToken:this.resourceManager.getSessToken()||""}))),this._voice}endSession(){this._voice?.destroy(),this._voice=null,this.closeConnection(),this.cleanup()}buildVoiceConfig(){return{offerUrl:`${this.config.serverUrl||(0,n.getConfig)(this.config.environment).BASE_API_URL}/med-assist/voice/offer`,handleRefresh:async()=>{await this.resourceManager.refreshTokens()}}}toClientError(g){if(g instanceof a.APIError){const f=g.reason??(g.status===401||g.status===403?l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:g.error?.msg||g.message,error:g.error,code:g.code,...f&&{reason:f},status:g.status,context:g.context}}return g instanceof a.SynapseError?{message:g.displayMessage||g.message,code:g.code,...g.reason&&{reason:g.reason},context:g.context}:g instanceof Error?{message:g.message}:{message:"An unexpected error occurred"}}emitError(g){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(g))}toSessionError(g,f,b,m){return(0,a.normalizeError)(g,a.SessionError,f,{context:b,hint:m})}async initializeConnection(g){if(this.closeConnection(),!g.session_id||!this.resourceManager.getSessToken())throw new a.SessionError("Session ID or sess token not found",{context:{stage:"initializeConnection"},hint:"Ensure the token exchange and session API completed successfully."});this.sessionConfig=g;const f=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?f.WEBSOCKET_URL:f.BASE_API_URL,_=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:_||m,auth:{sessionId:g.session_id,getToken:()=>this.resourceManager.getSessToken()||"",onUnauthorized:()=>this.resourceManager.refreshBearer()},agentId:this.config.agentId,userId:this.config.userId,overrides:this.config.overrides,...this.config.channel&&{channel:this.config.channel}}),this.connectionAttempts++,this.messageManager.setConnection(this.connection);const y=this.connection.emit.bind(this.connection);this.connection.emit=(k,...x)=>{y(k,...x),this.sdkEventEmitter.emit(k,...x)}}async createNewSession(){return await this.resourceManager.createSession(this.config.userId,this.config.context)}setupEventHandlers(){if(!this.connection)return;this.connection.onOpen(()=>{switch(this.connectionType){case e.ConnectionType.SOCKET:this.onSocketConnectionOpen();break;case e.ConnectionType.HTTP_STREAM:this.messageManager.handleConnectionEstablished();break}}),this.connection.onMessage(f=>{this.onIncomingSocketMessage(f)}),this.connection.onError(f=>{this.onRealtimeConnectionError(f)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const g=this.connection;this.connection.onDisconnect(async f=>{if(this.connection!==g||f.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(f.code);if(b){await this.handleRecovery(b,f);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(f)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(g){if(g instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(g.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:g.message,code:g.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,g);const f=g instanceof a.APIError?g:this.toConnectionError(g,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(f)}onSocketConnectionOpen(){const g=this.resourceManager.getSessToken();if(!g){const f=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(f),f}this.messageManager.sendSocketAuthMessage(g)}onIncomingSocketMessage(g){switch(g.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(g);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(g);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(g);break;case h.SOCKET_EVENTS.PING:this.messageManager.sendSocketPongMessage();break;case h.SOCKET_EVENTS.PONG:this.messageManager.sendSocketPingMessage();break;case h.SOCKET_EVENTS.SYNC:break;case h.SOCKET_EVENTS.ERROR:this.messageManager.handleIncomingSocketErrorMessage(g);break;default:const f=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:g.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(f);return}}get isAuthenticatedUser(){const g=this.resourceManager.getLevel();return g?g==="user":!!this.config.authToken}statusOf(g){if(g instanceof a.APIError)return g.status;if(g instanceof a.SynapseError&&typeof g.context?.status=="number")return g.context.status}emitRecoveryError(g,f,b){this.emitError(new a.SessionError(f,{reason:g,cause:b,context:{stage:"connectionRecovery",reason:g}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(g,f){if(g===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),f&&this.scheduleReconnect(f);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(g){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(g){const f=this.statusOf(g);if(f!==403&&f!==401){this.emitError(this.toSessionError(g,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",g)}}async recoverMissingSession(){const g=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!g){this.closeConnection(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const f=await this.resourceManager.reinitialiseSession(g);await this.connectTo(f);return}catch(f){const b=this.statusOf(f);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",f);return}try{await this.connectTo(await this.createNewSession())}catch(m){const _=this.statusOf(m);if(_===401||_===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(g){await this.initializeConnection(g),this.setupEventHandlers()}async handleAuthExpiry(){if(!(this.isRefreshingSession||this.isRecovering)){this.isRefreshingSession=!0,this.isRecovering=!0;try{await this.recoverExpiredCredentials()}finally{this.isRefreshingSession=!1,this.isRecovering=!1}}}async handleSessionInactiveMessage(){if(!this.isRecovering){this.isRecovering=!0;try{await this.recoverMissingSession()}finally{this.isRecovering=!1}}}toConnectionError(g,f,b,m){return(0,a.normalizeError)(g,a.ConnectionError,f,{context:b,hint:m})}scheduleReconnect(g){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(g);return}const f=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(g)}}},f)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return jn.SynapseSDK=p,jn}var Ra={},Aa;function nu(){return Aa||(Aa=1,Object.defineProperty(Ra,"__esModule",{value:!0})),Ra}var Fr={},Ia;function ru(){return Ia||(Ia=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.USER_FEEDBACK=void 0,Fr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Fr}var Ma={},Pa;function ou(){return Pa||(Pa=1,Object.defineProperty(Ma,"__esModule",{value:!0})),Ma}var ar={},Da;function su(){if(Da)return ar;Da=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.ToolCall=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return ar.ToolCall=t,ar}var Je={},La;function iu(){if(La)return Je;La=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.SYNAPSE_EICITATION_STATUS=Je.SYNAPSE_CTA_ACTIONS=Je.SYNAPSE_TOOL_FORMATS=Je.SYNAPSE_TOOL_CALLBACK_NAME=Je.SYNAPSE_COMPONENTS=Je.SYNAPSE_TOOL_NAME=void 0;var e;(function(s){s.MOBILE_VERIFICATION="mobile_verification",s.AVAILABILITY_DATES="availability_dates",s.AVAILABILITY_SLOTS="availability_slots",s.DOCTOR_AVAILABILITY="doctor_availability",s.DOCTOR_DETAILS="doctor_details",s.GET_LOCATION="get_location"})(e||(Je.SYNAPSE_TOOL_NAME=e={}));var t;(function(s){s.MOBILE="mobile_number",s.OTP="otp",s.EMAIL="email_address",s.PILL="pills",s.MULTI="multi",s.DOCTOR_CARD="doctor_card",s.CARD="card",s.MEDIA_CARD="media_card"})(t||(Je.SYNAPSE_COMPONENTS=t={}));var n;(function(s){s.DOCTOR_AVAILABILITY="get_doctor_availability",s.AVAILABILITY_DATES="get_available_dates",s.AVAILABILITY_SLOTS="get_available_slots",s.MOBILE_VERIFICATION="verify_mobile_number",s.DOCTOR_DETAILS="get_doctor_details"})(n||(Je.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Je.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Je.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Je.SYNAPSE_EICITATION_STATUS=i={})),Je}var Ua={},Fa;function au(){return Fa||(Fa=1,Object.defineProperty(Ua,"__esModule",{value:!0})),Ua}var Va={},ja;function lu(){return ja||(ja=1,Object.defineProperty(Va,"__esModule",{value:!0})),Va}var lr={},za;function cu(){if(za)return lr;za=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(lr.SYNAPSE_CONVERSATION=e={})),lr}var bn={},$a;function du(){return $a||($a=1,(function(e){var t=bn&&bn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=bn&&bn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(Ta(),e)})(bn)),bn}var Ya;function uu(){return Ya||(Ya=1,(function(e){var t=_n&&_n.__createBinding||(Object.create?(function(w,T,S,v){v===void 0&&(v=S);var C=Object.getOwnPropertyDescriptor(T,S);(!C||("get"in C?!T.__esModule:C.writable||C.configurable))&&(C={enumerable:!0,get:function(){return T[S]}}),Object.defineProperty(w,v,C)}):(function(w,T,S,v){v===void 0&&(v=S),w[v]=T[S]})),n=_n&&_n.__exportStar||function(w,T){for(var S in w)S!=="default"&&!Object.prototype.hasOwnProperty.call(T,S)&&t(T,w,S)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=tu();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Lo();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=$i();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Wi();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=qi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Hn(),e);var l=pa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return l.ResourceManager}}),n(nu(),e);var d=ea();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(ru(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=da();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(ou(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var E=oa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var g=su();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return g.ToolCall}}),n(iu(),e);var f=va();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return f.MessageManager}}),n(Ur(),e),n(au(),e);var b=Lr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=it();Object.defineProperty(e,"SynapseError",{enumerable:!0,get:function(){return m.SynapseError}}),Object.defineProperty(e,"APIError",{enumerable:!0,get:function(){return m.APIError}}),Object.defineProperty(e,"APIUserAbortError",{enumerable:!0,get:function(){return m.APIUserAbortError}}),Object.defineProperty(e,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return m.APIConnectionTimeoutError}}),Object.defineProperty(e,"BadRequestError",{enumerable:!0,get:function(){return m.BadRequestError}}),Object.defineProperty(e,"UnauthorizedError",{enumerable:!0,get:function(){return m.UnauthorizedError}}),Object.defineProperty(e,"PermissionDeniedError",{enumerable:!0,get:function(){return m.PermissionDeniedError}}),Object.defineProperty(e,"NotFoundError",{enumerable:!0,get:function(){return m.NotFoundError}}),Object.defineProperty(e,"MethodNotAllowedError",{enumerable:!0,get:function(){return m.MethodNotAllowedError}}),Object.defineProperty(e,"RateLimitError",{enumerable:!0,get:function(){return m.RateLimitError}}),Object.defineProperty(e,"InternalServerError",{enumerable:!0,get:function(){return m.InternalServerError}}),Object.defineProperty(e,"SynapseErrorCode",{enumerable:!0,get:function(){return m.SynapseErrorCode}});var _=jo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return _.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return _.SYNAPSE_RECOVERY_REASON}});var y=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(lu(),e);var k=Bi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var x=Ur();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(cu(),e),n(du(),e)})(_n)),_n}var I=uu();function Ha(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=Ha(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ba(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ha(e))&&(r&&(r+=" "),r+=t);return r}const hu=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},mu=(e,t)=>({classGroupId:e,validator:t}),Ga=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Vr="-",Wa=[],pu="arbitrary..",fu=e=>{const t=_u(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return gu(o);const i=o.split(Vr),s=i[0]===""&&i.length>1?1:0;return Ka(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?hu(a,s):s:a||Wa}return n[o]||Wa}}},Ka=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const l=Ka(e,t+1,o);if(l)return l}const i=n.validators;if(i===null)return;const s=t===0?e.join(Vr):e.slice(t).join(Vr),a=i.length;for(let l=0;l<a;l++){const d=i[l];if(d.validator(s))return d.classGroupId}},gu=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?pu+r:void 0})(),_u=e=>{const{theme:t,classGroups:n}=e;return Eu(n,t)},Eu=(e,t)=>{const n=Ga();for(const r in e){const o=e[r];Yo(o,n,r,t)}return n},Yo=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];yu(s,t,n,r)}},yu=(e,t,n,r)=>{if(typeof e=="string"){Su(e,t,n);return}if(typeof e=="function"){bu(e,t,n,r);return}vu(e,t,n,r)},Su=(e,t,n)=>{const r=e===""?t:qa(t,e);r.classGroupId=n},bu=(e,t,n,r)=>{if(wu(e)){Yo(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(mu(n,e))},vu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,l]=o[s];Yo(l,qa(t,a),n,r)}},qa=(e,t)=>{let n=e;const r=t.split(Vr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Ga(),n.nextPart.set(s,a)),n=a}return n},wu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Nu=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},Ho="!",Xa=":",Cu=[],Za=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),xu=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,d;const h=o.length;for(let f=0;f<h;f++){const b=o[f];if(s===0&&a===0){if(b===Xa){i.push(o.slice(l,f)),l=f+1;continue}if(b==="/"){d=f;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(l);let p=u,E=!1;u.endsWith(Ho)?(p=u.slice(0,-1),E=!0):u.startsWith(Ho)&&(p=u.slice(1),E=!0);const g=d&&d>l?d-l:void 0;return Za(i,E,p,g)};if(t){const o=t+Xa,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Za(Cu,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Tu=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",l=t.has(s);a||l?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},ku=e=>({cache:Nu(e.cacheSize),parseClassName:xu(e),sortModifiers:Tu(e),...fu(e)}),Ou=/\s+/,Ru=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Ou);let l="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:E,baseClassName:g,maybePostfixModifierPosition:f}=n(h);if(u){l=h+(l.length>0?" "+l:l);continue}let b=!!f,m=r(b?g.substring(0,f):g);if(!m){if(!b){l=h+(l.length>0?" "+l:l);continue}if(m=r(g),!m){l=h+(l.length>0?" "+l:l);continue}b=!1}const _=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=E?_+Ho:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,b);for(let w=0;w<x.length;++w){const T=x[w];s.push(y+T)}l=h+(l.length>0?" "+l:l)}return l},Au=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ja(n))&&(o&&(o+=" "),o+=r);return o},Ja=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ja(e[r]))&&(n&&(n+=" "),n+=t);return n},Iu=(e,...t)=>{let n,r,o,i;const s=l=>{const d=t.reduce((h,u)=>u(h),e());return n=ku(d),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const d=r(l);if(d)return d;const h=Ru(l,n);return o(l,h),h};return i=s,(...l)=>i(Au(...l))},Mu=[],Ve=e=>{const t=n=>n[e]||Mu;return t.isThemeGetter=!0,t},Qa=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,el=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Pu=/^\d+\/\d+$/,Du=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Lu=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Uu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Fu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Vu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vn=e=>Pu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),$t=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Mt=e=>Du.test(e),ju=()=>!0,zu=e=>Lu.test(e)&&!Uu.test(e),tl=()=>!1,$u=e=>Fu.test(e),Yu=e=>Vu.test(e),Hu=e=>!$(e)&&!Y(e),Bu=e=>wn(e,il,tl),$=e=>Qa.test(e),Jt=e=>wn(e,al,zu),Go=e=>wn(e,Xu,ne),nl=e=>wn(e,ol,tl),Gu=e=>wn(e,sl,Yu),jr=e=>wn(e,ll,$u),Y=e=>el.test(e),cr=e=>Nn(e,al),Wu=e=>Nn(e,Zu),rl=e=>Nn(e,ol),Ku=e=>Nn(e,il),qu=e=>Nn(e,sl),zr=e=>Nn(e,ll,!0),wn=(e,t,n)=>{const r=Qa.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Nn=(e,t,n=!1)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n:!1},ol=e=>e==="position"||e==="percentage",sl=e=>e==="image"||e==="url",il=e=>e==="length"||e==="size"||e==="bg-size",al=e=>e==="length",Xu=e=>e==="number",Zu=e=>e==="family-name",ll=e=>e==="shadow",Ju=()=>{const e=Ve("color"),t=Ve("font"),n=Ve("text"),r=Ve("font-weight"),o=Ve("tracking"),i=Ve("leading"),s=Ve("breakpoint"),a=Ve("container"),l=Ve("spacing"),d=Ve("radius"),h=Ve("shadow"),u=Ve("inset-shadow"),p=Ve("text-shadow"),E=Ve("drop-shadow"),g=Ve("blur"),f=Ve("perspective"),b=Ve("aspect"),m=Ve("ease"),_=Ve("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),Y,$],w=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],S=()=>[Y,$,l],v=()=>[vn,"full","auto",...S()],C=()=>[$t,"none","subgrid",Y,$],L=()=>["auto",{span:["full",$t,Y,$]},$t,Y,$],X=()=>[$t,"auto",Y,$],G=()=>["auto","min","max","fr",Y,$],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...S()],_e=()=>[vn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],F=()=>[e,Y,$],le=()=>[...k(),rl,nl,{position:[Y,$]}],Re=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",Ku,Bu,{size:[Y,$]}],J=()=>[Bo,cr,Jt],A=()=>["","none","full",d,Y,$],B=()=>["",ne,cr,Jt],re=()=>["solid","dashed","dotted","double"],Se=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],W=()=>[ne,Bo,rl,nl],Ae=()=>["","none",g,Y,$],$e=()=>["none",ne,Y,$],ie=()=>["none",ne,Y,$],Pe=()=>[ne,Y,$],De=()=>[vn,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Mt],breakpoint:[Mt],color:[ju],container:[Mt],"drop-shadow":[Mt],ease:["in","out","in-out"],font:[Hu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Mt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Mt],shadow:[Mt],spacing:["px",ne],text:[Mt],"text-shadow":[Mt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",vn,$,Y,b]}],container:["container"],columns:[{columns:[ne,$,Y,a]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:x()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[$t,"auto",Y,$]}],basis:[{basis:[vn,"full","auto",a,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,vn,"auto","initial","none",$]}],grow:[{grow:["",ne,Y,$]}],shrink:[{shrink:["",ne,Y,$]}],order:[{order:[$t,"first","last","none",Y,$]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":X()}],"col-end":[{"col-end":X()}],"grid-rows":[{"grid-rows":C()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":X()}],"row-end":[{"row-end":X()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:_e()}],w:[{w:[a,"screen",..._e()]}],"min-w":[{"min-w":[a,"screen","none",..._e()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},..._e()]}],h:[{h:["screen","lh",..._e()]}],"min-h":[{"min-h":["screen","lh","none",..._e()]}],"max-h":[{"max-h":["screen","lh",..._e()]}],"font-size":[{text:["base",n,cr,Jt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,Y,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,$]}],"font-family":[{font:[Wu,$,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,Y,$]}],"line-clamp":[{"line-clamp":[ne,"none",Y,Go]}],leading:[{leading:[i,...S()]}],"list-image":[{"list-image":["none",Y,$]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,$]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",Y,Jt]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[ne,"auto",Y,$]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,$]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,$]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Re()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},$t,Y,$],radial:["",Y,$],conic:[$t,Y,$]},qu,Gu]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:J()}],"gradient-via-pos":[{via:J()}],"gradient-to-pos":[{to:J()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:A()}],"rounded-s":[{"rounded-s":A()}],"rounded-e":[{"rounded-e":A()}],"rounded-t":[{"rounded-t":A()}],"rounded-r":[{"rounded-r":A()}],"rounded-b":[{"rounded-b":A()}],"rounded-l":[{"rounded-l":A()}],"rounded-ss":[{"rounded-ss":A()}],"rounded-se":[{"rounded-se":A()}],"rounded-ee":[{"rounded-ee":A()}],"rounded-es":[{"rounded-es":A()}],"rounded-tl":[{"rounded-tl":A()}],"rounded-tr":[{"rounded-tr":A()}],"rounded-br":[{"rounded-br":A()}],"rounded-bl":[{"rounded-bl":A()}],"border-w":[{border:B()}],"border-w-x":[{"border-x":B()}],"border-w-y":[{"border-y":B()}],"border-w-s":[{"border-s":B()}],"border-w-e":[{"border-e":B()}],"border-w-t":[{"border-t":B()}],"border-w-r":[{"border-r":B()}],"border-w-b":[{"border-b":B()}],"border-w-l":[{"border-l":B()}],"divide-x":[{"divide-x":B()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":B()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,Y,$]}],"outline-w":[{outline:["",ne,cr,Jt]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",h,zr,jr]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",u,zr,jr]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[ne,Jt]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":B()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",p,zr,jr]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[ne,Y,$]}],"mix-blend":[{"mix-blend":[...Se(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Se()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":W()}],"mask-image-linear-to-pos":[{"mask-linear-to":W()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":W()}],"mask-image-t-to-pos":[{"mask-t-to":W()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":W()}],"mask-image-r-to-pos":[{"mask-r-to":W()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":W()}],"mask-image-b-to-pos":[{"mask-b-to":W()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":W()}],"mask-image-l-to-pos":[{"mask-l-to":W()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":W()}],"mask-image-x-to-pos":[{"mask-x-to":W()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":W()}],"mask-image-y-to-pos":[{"mask-y-to":W()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Y,$]}],"mask-image-radial-from-pos":[{"mask-radial-from":W()}],"mask-image-radial-to-pos":[{"mask-radial-to":W()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":W()}],"mask-image-conic-to-pos":[{"mask-conic-to":W()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Re()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,$]}],filter:[{filter:["","none",Y,$]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,Y,$]}],contrast:[{contrast:[ne,Y,$]}],"drop-shadow":[{"drop-shadow":["","none",E,zr,jr]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",ne,Y,$]}],"hue-rotate":[{"hue-rotate":[ne,Y,$]}],invert:[{invert:["",ne,Y,$]}],saturate:[{saturate:[ne,Y,$]}],sepia:[{sepia:["",ne,Y,$]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,$]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,Y,$]}],"backdrop-contrast":[{"backdrop-contrast":[ne,Y,$]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,Y,$]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,Y,$]}],"backdrop-invert":[{"backdrop-invert":["",ne,Y,$]}],"backdrop-opacity":[{"backdrop-opacity":[ne,Y,$]}],"backdrop-saturate":[{"backdrop-saturate":[ne,Y,$]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,Y,$]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,$]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",Y,$]}],ease:[{ease:["linear","initial",m,Y,$]}],delay:[{delay:[ne,Y,$]}],animate:[{animate:["none",_,Y,$]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,Y,$]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:$e()}],"rotate-x":[{"rotate-x":$e()}],"rotate-y":[{"rotate-y":$e()}],"rotate-z":[{"rotate-z":$e()}],scale:[{scale:ie()}],"scale-x":[{"scale-x":ie()}],"scale-y":[{"scale-y":ie()}],"scale-z":[{"scale-z":ie()}],"scale-3d":["scale-3d"],skew:[{skew:Pe()}],"skew-x":[{"skew-x":Pe()}],"skew-y":[{"skew-y":Pe()}],transform:[{transform:[Y,$,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Y,$]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,$]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[ne,cr,Jt,Go]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Qu=Iu(Ju);function U(...e){return Qu(Ba(e))}function Qt(e){if(!e&&e!==0)return"";const t=e instanceof Date?e:new Date(typeof e=="number"?e:Number(e)||e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}const eh=e=>{switch(e){case I.SYNAPSE_COMPONENTS.DOCTOR_CARD:case I.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},th=e=>new Promise(t=>setTimeout(t,e)),cl=ee(({className:e,children:t,...n},r)=>c(Pi,{ref:r,className:U("relative overflow-hidden",e),...n,children:[c(Bd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),c(dl,{}),c(Gd,{})]}));cl.displayName=Pi.displayName;const dl=ee(({className:e,orientation:t="vertical",...n},r)=>c(Io,{ref:r,orientation:t,className:U("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c(ki,{className:"relative flex-1 rounded-full bg-border"})}));dl.displayName=Io.displayName;var nh=Symbol.for("react.lazy"),$r=Oo[" use ".trim().toString()];function rh(e){return typeof e=="object"&&e!==null&&"then"in e}function ul(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===nh&&"_payload"in e&&rh(e._payload)}function hl(e){const t=sh(e),n=ee((r,o)=>{let{children:i,...s}=r;ul(i)&&typeof $r=="function"&&(i=$r(i._payload));const a=ot.toArray(i),l=a.find(ah);if(l){const d=l.props.children,h=a.map(u=>u===l?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:st(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var oh=hl("Slot");function sh(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(ul(o)&&typeof $r=="function"&&(o=$r(o._payload)),st(o)){const s=ch(o),a=lh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ih=Symbol("radix.slottable");function ah(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ih}function lh(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function ch(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const ml=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,pl=Ba,dh=(e,t)=>n=>{var r;if(t?.variants==null)return pl(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n?.[d],u=i?.[d];if(h===null)return null;const p=ml(h)||ml(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,...E}=h;return Object.entries(E).every(g=>{let[f,b]=g;return Array.isArray(b)?b.includes({...i,...a}[f]):{...i,...a}[f]===b})?[...d,u,p]:d},[]);return pl(e,s,l,n?.class,n?.className)},uh=dh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Ee=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>c(r?oh:"button",{className:U(uh({variant:t,size:n,className:e})),ref:i,...o}));Ee.displayName="Button";const hh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),mh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),fl=e=>{const t=mh(e);return t.charAt(0).toUpperCase()+t.slice(1)},gl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),ph=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const gh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>et("svg",{ref:l,...fh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:gl("lucide",o),...!i&&!ph(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>et(d,h)),...Array.isArray(i)?i:[i]])),ze=(e,t)=>{const n=ee(({className:r,...o},i)=>et(gh,{ref:i,iconNode:t,className:gl(`lucide-${hh(fl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=fl(e),n},_h=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=ze("chevron-down",_h),Eh=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],yh=ze("ellipsis-vertical",Eh),Sh=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],_l=ze("file-text",Sh),bh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],El=ze("info",bh),vh=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],wh=ze("maximize-2",vh),Nh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Ch=ze("menu",Nh),xh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],dr=ze("message-square-plus",xh),Th=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Ko=ze("mic",Th),kh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Oh=ze("minimize-2",kh),Rh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yl=ze("plus",Rh),Ah=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Ih=ze("rotate-ccw",Ah),Mh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Sl=ze("square",Mh),Ph=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],bl=ze("thumbs-up",Ph),Dh=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],vl=ze("thumbs-down",Dh),Lh=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Uh=ze("triangle-alert",Lh),Fh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Cn=ze("x",Fh),Vh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],jh=ze("zoom-in",Vh),wl=e=>{let t;const n=new Set,r=(a,l)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=l??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},zh=(e=>e?wl(e):wl),$h=e=>e;function Yh(e,t=$h){const n=Vn.useSyncExternalStore(e.subscribe,Vn.useCallback(()=>t(e.getState()),[e,t]),Vn.useCallback(()=>t(e.getInitialState()),[e,t]));return Vn.useDebugValue(n),n}const Hh=e=>{const t=zh(e),n=r=>Yh(t,r);return Object.assign(n,t),n},Bh=(e=>Hh);function Gh(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var o;const i=a=>a===null?null:JSON.parse(a,void 0),s=(o=n.getItem(r))!=null?o:null;return s instanceof Promise?s.then(i):i(s)},setItem:(r,o)=>n.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>n.removeItem(r)}}const qo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qo(r)(n)}}}},Wh=(e,t)=>(n,r,o)=>{let i={storage:Gh(()=>localStorage),partialize:f=>f,version:0,merge:(f,b)=>({...b,...f}),...t},s=!1;const a=new Set,l=new Set;let d=i.storage;if(!d)return e((...f)=>{n(...f)},r,o);const h=()=>{const f=i.partialize({...r()});return d.setItem(i.name,{state:f,version:i.version})},u=o.setState;o.setState=(f,b)=>(u(f,b),h());const p=e((...f)=>(n(...f),h()),r,o);o.getInitialState=()=>p;let E;const g=()=>{var f,b;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:p)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(f=r())!=null?f:p))||void 0;return qo(d.getItem.bind(d))(i.name).then(_=>{if(_)if(typeof _.version=="number"&&_.version!==i.version){if(i.migrate){const y=i.migrate(_.state,_.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[k,x]=_;if(E=i.merge(x,(y=r())!=null?y:p),n(E,!0),k)return h()}).then(()=>{m?.(E,void 0),E=r(),s=!0,l.forEach(_=>_(E))}).catch(_=>{m?.(void 0,_)})};return o.persist={setOptions:f=>{i={...i,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>s,onHydrate:f=>(a.add(f),()=>{a.delete(f)}),onFinishHydration:f=>(l.add(f),()=>{l.delete(f)})},i.skipHydration||g(),E||p},Kh=Wh,Ne={USER:"user",ASSISTANT:"assistant"};var ye=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(ye||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let dt="";const ur=e=>`med-assist-store-${e}`,qh=e=>{xn(),dt=ur(e)},Xh=200;let ft=null,hr=null;function xn(){if(hr&&(clearTimeout(hr),hr=null),!!ft){try{sessionStorage.setItem(ft.key,JSON.stringify(ft.value))}catch{}ft=null}}typeof window<"u"&&(window.addEventListener("pagehide",xn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&xn()}));const Zh={getItem:()=>{if(!dt)return null;if(ft?.key===dt)return ft.value;try{const e=sessionStorage.getItem(dt);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{dt&&(ft&&ft.key!==dt&&xn(),ft={key:dt,value:t},hr||(hr=setTimeout(xn,Xh)))},removeItem:()=>{ft?.key===dt&&(ft=null),dt&&sessionStorage.removeItem(dt)}},Nl={sessionId:"",isStreaming:!1,recordingStatus:ye.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:ge.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},Cl={...Nl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=Bh()(Kh((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:ge.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:ye.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),isMobile:!1,setIsMobile:n=>e({isMobile:n}),displayMode:"widget",setDisplayMode:n=>e({displayMode:n}),toggleDisplayMode:()=>e({displayMode:t().displayMode==="full"?"widget":"full"}),initialDisplayMode:"widget",setInitialDisplayMode:n=>e({initialDisplayMode:n}),chats:{},addMessageToSession:(n,r)=>{e(o=>({chats:{...o.chats,[n]:[...o.chats[n]||[],r]}}))},updateMessageInSession:(n,r,o)=>e(i=>({chats:{...i.chats,[n]:(i.chats[n]||[]).map(s=>s.id===r?{...s,...o}:s)}})),getMessagesForSession:n=>t().chats[n]||[],setMessagesForSession:(n,r)=>e(o=>({chats:{...o.chats,[n]:r}})),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),clearSession:async()=>{e(Nl),await sessionStorage.removeItem(dt||ur(t().agentId))},clearUser:()=>{e(Cl),sessionStorage.removeItem(dt||ur(t().agentId))}}),{name:"med-assist-store",storage:Zh,partialize:e=>({agentId:e.agentId,userId:e.userId,context:e.context,chats:e.chats,sessionId:e.sessionId,refreshToken:e.refreshToken,sessToken:e.sessToken,level:e.level,initialMessage:e.initialMessage,sessionInitialMessages:e.sessionInitialMessages,connectionStatus:e.connectionStatus,elicitationState:e.elicitationState})})),Jh=e=>{const t=ur(e);xn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(Cl),n&&j.setState(n)},Xo=bt(null),Qh=({children:e})=>{const[t,n]=V(null);return c(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},em=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},tm=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},nm=()=>{const[e,t]=V(I.VOICE_AGENT_STATE.IDLE),[n,r]=V(!1),o=em(),i=j(h=>h.setError);H(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},p=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(I.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(I.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=de(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=de(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),l=de(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=de(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:l,toggleMute:d}},en=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));en.displayName="Card";const xl=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("flex flex-col space-y-1.5 p-6",e),...t}));xl.displayName="CardHeader";const Tl=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("font-semibold leading-none tracking-tight",e),...t}));Tl.displayName="CardTitle";const rm=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("text-sm text-muted-foreground",e),...t}));rm.displayName="CardDescription";const kl=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("p-6 pt-0",e),...t}));kl.displayName="CardContent";const Ol=ee(({className:e,...t},n)=>c("div",{ref:n,className:U("flex items-center p-6 pt-0",e),...t}));Ol.displayName="CardFooter";const Zo=5,Rl=3,Al=10*1024*1024,Yr={width:384,height:600},Hr=20,om=400,sm=320,im=560,am=150;function lm({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=de(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Yr.width-Hr,y:window.innerHeight-Yr.height-Hr},[]),[i,s]=V(()=>e??o()),[a,l]=V(!1),d=q({x:0,y:0}),h=q(null),u=q(!1);H(()=>{t||(u.current=!1)},[t]),mt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),H(()=>{if(!t||typeof window>"u")return;let f=null;const b=()=>{s(_=>{const y=Math.max(0,window.innerWidth-Yr.width-Hr),k=Math.max(0,window.innerHeight-Yr.height-Hr),x=Math.max(0,Math.min(_.x,y)),w=Math.max(0,Math.min(_.y,k));return x===_.x&&w===_.y?_:{x,y:w}})},m=()=>{f!==null&&clearTimeout(f),f=setTimeout(b,am)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),f!==null&&clearTimeout(f)}},[t]);const p=de(f=>{if(!t)return;if(!f.target.closest(".synapse-chat-widget-header")){l(!1);return}f.preventDefault(),l(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:f.clientX-m.left,y:f.clientY-m.top}}else d.current={x:f.clientX-i.x,y:f.clientY-i.y};n?.()},[t,i.x,i.y,n]),E=de(f=>{if(!t||!a)return;const b=f.clientX-d.current.x,m=f.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(b,_)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[a,t]),g=de(()=>{!t||!a||(l(!1),r?.())},[a,r]);return H(()=>{if(!t)return;const f=h.current;if(f)return f.addEventListener("mousedown",p),()=>{f.removeEventListener("mousedown",p)}},[t,p]),H(()=>{if(a)return document.addEventListener("mousemove",E),document.addEventListener("mouseup",g),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",g),document.body.style.cursor="",document.body.style.userSelect=""}},[a,E,g]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Jo="#6B5CE0",cm="#F0F0F0",Br={background:cm,backgroundImage:void 0,primary:Jo,textColor:"black"},dm="rgba(0, 0, 0, 0.4)",um="24px";function hm(e){if(e==="dark")return"white";if(e==="light")return"black"}function mm(e){const t=e?.primary??e?.primaryColor??Br.primary,n=e?.textColor??hm(e?.mode);return{background:e?.background??Br.background,backgroundImage:e?.backgroundImage??Br.backgroundImage,primary:t,primaryColor:t,textColor:n??Br.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function pm(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const l=(o+i)/2;if(o!==i){const h=o-i;switch(a=l>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(l*100);return`${s} ${a}% ${d}%`}function fm(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,l=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(l=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),l=Math.round(l*100);const h=Math.round(d*100);return`${a} ${l}% ${h}%`}function gm(e){const t=e.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(!t)throw new Error("Invalid HSL format");return`${t[1]} ${t[2]}% ${t[3]}%`}function Qo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return pm(t);if(t.startsWith("rgb"))return fm(t);if(t.startsWith("hsl"))return gm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Il(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Il(e)>.5?"0 0% 9%":"0 0% 98%"}function _m(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return"0 0% 96%";const n=t[1],r=Math.max(0,parseInt(t[2],10)-5);return`${n} ${r}% 96%`}function Em(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return{50:"262 83% 98%",100:"262 83% 96%",200:"262 83% 92%",300:"262 83% 85%",400:"262 83% 75%",500:"262 83% 58%",600:"262 83% 50%",700:"262 83% 40%",800:"262 83% 30%",900:"262 83% 20%"};const n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);return{50:`${n} ${Math.max(0,r-20)}% ${Math.min(98,o+40)}%`,100:`${n} ${Math.max(0,r-15)}% ${Math.min(96,o+35)}%`,200:`${n} ${Math.max(0,r-10)}% ${Math.min(92,o+30)}%`,300:`${n} ${Math.max(0,r-5)}% ${Math.min(85,o+20)}%`,400:`${n} ${r}% ${Math.min(75,o+10)}%`,500:`${n} ${r}% ${o}%`,600:`${n} ${Math.min(100,r+5)}% ${Math.max(50,o-10)}%`,700:`${n} ${Math.min(100,r+10)}% ${Math.max(40,o-20)}%`,800:`${n} ${Math.min(100,r+15)}% ${Math.max(30,o-30)}%`,900:`${n} ${Math.min(100,r+20)}% ${Math.max(20,o-40)}%`}}function Ml(e,t){const n=t.primary??Jo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,g)=>{const f=e instanceof ShadowRoot?e.host:e;f instanceof HTMLElement&&f.style.setProperty(E,g)};let l;try{l=Qo(n)}catch{l=Qo(Jo)}a("--primary",l),a("--primary-foreground",es(l)),a("--ring",l),a("--border-primary",l);const d=Em(l);for(const[E,g]of Object.entries(d))a(`--primary-${E}`,g);const h=es(l);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const E=i?"#191919":"#F0F0F0";try{a("--background",Qo(E))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${l} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",_m(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${l})`),a("--header-stroke",`hsl(${l} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${l} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${l} / 0.3)`)),s&&!o){const E=Il(h)>.5;a("--header-tagline",E?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",l):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${p}-${E})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",l),a("--accent-foreground",es(l)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",um),a("--theme-background-overlay",dm),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function tn({className:e,style:t}){return c("div",{className:U("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function ts(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Pl(){return c("div",{className:"px-3 pb-2 pt-1",children:[c(ts,{}),c("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[c("div",{className:"px-2 pt-2 pb-1",children:c(tn,{className:"h-5 w-3/5 rounded-md"})}),c("div",{className:"flex items-center justify-between px-1 py-1",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c("div",{className:"flex items-center gap-2",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c(tn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function ym(){const e=[{role:Ne.ASSISTANT,size:"h-16 w-[70%]"},{role:Ne.USER,size:"h-9 w-[45%]"},{role:Ne.ASSISTANT,size:"h-24 w-[75%]"},{role:Ne.USER,size:"h-9 w-[35%]"},{role:Ne.ASSISTANT,size:"h-16 w-[65%]"}];return c("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[c(ts,{}),e.map((t,n)=>c("div",{className:U("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:c(tn,{className:U("rounded-lg",t.size)})},n))]})}function Sm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return c("div",{"aria-hidden":"true",children:[c(ts,{}),Array.from({length:e},(n,r)=>c("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[c(tn,{className:U("h-5 rounded-md",t[r%t.length])}),c(tn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function bm(e,t=[]){let n=[];function r(i,s){const a=bt(s);a.displayName=i+"Context";const l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[l]||a,b=ae(()=>g,Object.values(g));return c(f.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[l]||a,g=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,vm(o,...t)]}function vm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var wm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=wm.reduce((e,t)=>{const n=hl(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Dl={exports:{}},rs={};const Nm=Wd(Oo);var Ll;function Cm(){if(Ll)return rs;Ll=1;var e=Nm;function t(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,p){var E=p(),g=r({inst:{value:E,getSnapshot:p}}),f=g[0].inst,b=g[1];return i(function(){f.value=E,f.getSnapshot=p,l(f)&&b({inst:f})},[u,E,p]),o(function(){return l(f)&&b({inst:f}),u(function(){l(f)&&b({inst:f})})},[u]),s(E),E}function l(u){var p=u.getSnapshot;u=u.value;try{var E=p();return!n(u,E)}catch{return!0}}function d(u,p){return p()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return rs.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,rs}var Ul;function xm(){return Ul||(Ul=1,Dl.exports=Cm()),Dl.exports}var Tm=xm();function km(){return Tm.useSyncExternalStore(Om,()=>!0,()=>!1)}function Om(){return()=>{}}var os="Avatar",[Rm]=bm(os),[Am,Fl]=Rm(os),Vl=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=V("idle");return c(Am,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:c(ns.span,{...r,ref:t})})});Vl.displayName=os;var jl="AvatarImage",zl=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Fl(jl,n),a=Im(r,i),l=jt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Zt(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?c(ns.img,{...i,ref:t,src:r}):null});zl.displayName=jl;var $l="AvatarFallback",Yl=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Fl($l,n),[s,a]=V(r===void 0);return H(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),s&&i.imageLoadingStatus!=="loaded"?c(ns.span,{...o,ref:t}):null});Yl.displayName=$l;function Hl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Im(e,{referrerPolicy:t,crossOrigin:n}){const r=km(),o=q(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=V(()=>Hl(i,e));return Zt(()=>{a(Hl(i,e))},[i,e]),Zt(()=>{const l=u=>()=>{a(u)};if(!i)return;const d=l("loaded"),h=l("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Bl=Vl,Gl=zl,Wl=Yl;const ss=ee(({className:e,...t},n)=>c(Bl,{ref:n,className:U("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Bl.displayName;const Kl=ee(({className:e,...t},n)=>c(Gl,{ref:n,className:U("aspect-square h-full w-full",e),...t}));Kl.displayName=Gl.displayName;const is=ee(({className:e,...t},n)=>c(Wl,{ref:n,className:U("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Wl.displayName;const ql=bt(!1);function Mm({enabled:e,children:t}){return c(ql.Provider,{value:e,children:t})}function Pm(){return vt(ql)}const Xl="(max-width: 768px), (pointer: coarse)",Zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Dm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Xl)?.matches??!1,t=Zl.test(navigator?.userAgent??"");return e||t}function Jl(){const[e,t]=V(Dm);return H(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Xl),r=Zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Lm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:l=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Jl(),p=Pm(),E=j(C=>C.displayMode)==="side_panel",g=p&&!u&&!E,f=j(C=>C.displayMode)==="full",b=j(C=>C.initialDisplayMode)==="full",m=!f&&l?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",_=j(C=>C.connectionStatus),y=j(C=>C.level)==="user",[k,x]=V(!1),w=q(null),T=ae(()=>a===I.VOICE_AGENT_STATE.CONNECTED||a===I.VOICE_AGENT_STATE.CONNECTING||a===I.VOICE_AGENT_STATE.LISTENING||a===I.VOICE_AGENT_STATE.SPEAKING||a===I.VOICE_AGENT_STATE.THINKING,[a]),S=de(()=>{k||(x(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,x(!1)},6e3),s())},[k,s]);H(()=>{_===ge.CONNECTED&&(x(!1),w.current&&clearTimeout(w.current))},[_]);const v=(()=>{switch(_){case ge.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case ge.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case ge.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return c("div",{className:"px-6 py-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative flex-shrink-0",children:[c(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:c(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?c("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):c("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),c("div",{className:U("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,_===ge.CONNECTING&&"animate-pulse")})]}),c("div",{className:"flex flex-col",children:[r?c("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):c("p",{className:U("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",m),children:n||"Health Assist"}),c("div",{className:"flex items-center gap-1.5",children:c("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),c("div",{className:U("flex items-center",!g&&"gap-1"),children:[!T&&!y&&c(Ee,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:S,disabled:k,className:U("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",m),children:c(dr,{className:"w-5 h-5"})}),h&&y&&c(Ee,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:U("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(yh,{className:"w-5 h-5"})}),g&&c(Ee,{onClick:d,type:"button",variant:"ghost",size:"icon",title:f?"Exit fullscreen":"Enter fullscreen",className:U("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:f?c(Oh,{className:"w-8 h-8"}):c(wh,{className:"w-8 h-8"})}),(t||!b)&&c(Ee,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:U("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(Cn,{className:"w-8 h-8"})})]})]})})}const as=ee(({className:e,...t},n)=>c("textarea",{className:U("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:n,...t}));as.displayName="Textarea";function Ql({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=V(!1),[s,a]=V(""),l=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";H(()=>{if(l){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,l]),H(()=>{i(!1)},[e]);const h=()=>l?"text-green-600":"text-text-secondary",u=p=>{if(p===0)return"0 B";const E=1024,g=["B","KB","MB","GB"],f=Math.floor(Math.log(p)/Math.log(E));return`${(p/Math.pow(E,f)).toFixed(1)} ${g[f]}`.toLowerCase()};return!l||o?c("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[c("div",{className:`flex-shrink-0 ${h()}`,children:c(_l,{className:"h-5 w-5"})}),c("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&c("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&c("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:c(Cn,{className:"h-3 w-3"})})]}):c("div",{className:`relative group flex-shrink-0 ${r}`,children:[c("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&c("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:c(Cn,{className:"h-3 w-3"})})]})}function ls({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return c("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return c(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&c("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return c(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),ec=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Um=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},tc=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),Fm=tt(()=>ec().then(e=>({default:e.ElicitationInput})));function Vm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:l,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:E,allowed:g,showStartNewChatButton:f,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:x,showAttention:w}){const T=q(null),S=q(null),v=w?c("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,C=e.trim().length>0||a,L=!g||g.includes(I.SYNAPSE_CONVERSATION.AUDIO),X=!g||g.includes(I.SYNAPSE_CONVERSATION.VOICE),G=C||!L,he=C,pe=!g||g.includes(I.SYNAPSE_CONVERSATION.FILE),se=(d||p!==ye.IDLE)&&!s,_e=U("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":se?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),F=A=>{const B=Array.from(A.target.files||[]);B.length>0&&r(B)},le=()=>{d||(T.current&&(T.current.value=""),T.current?.click())},Re=A=>{A.key==="Enter"&&!A.shiftKey&&he&&!d&&(A.preventDefault(),n())},te=A=>{A.style.height="auto",A.style.overflow="hidden";const B=A.scrollHeight,re=x?20:28,Se=120,W=Math.max(re,Math.min(B,Se));A.style.height=W+"px",B>Se?A.style.overflow="auto":A.style.overflow="hidden"},J=A=>{te(A.currentTarget)};return H(()=>{S.current&&te(S.current)},[e]),H(()=>{d||S.current?.focus()},[d]),f&&b?c("div",{className:"px-4 py-2 flex justify-unset",children:c("button",{type:"button",onClick:b,className:U("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[c("span",{children:"Start new chat"}),c(dr,{className:"w-5 h-5","aria-hidden":!0})]})}):c(me,{children:y?c(Ze,{fallback:c(Pl,{}),children:c(Fm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):x?c("div",{className:"mx-3 mb-3","data-name":"reply-box",children:c("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("input",{ref:T,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:c(as,{ref:S,onInput:J,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:U("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),c("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[c("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:pe&&p===ye.IDLE&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:U("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(yl,{className:"w-6 h-6",strokeWidth:1.5})})}),c("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className:U("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(Sl,{className:"w-4 h-4"})}):L&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:U("h-10 w-10 shrink-0 p-2",_e),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-6 h-6",strokeWidth:1.5})}),G&&!s?c(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:U("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):L&&X&&!s&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):c("div",{className:"px-3 pt-1",children:[c("input",{ref:T,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("div",{className:"px-1 pt-1 pb-0",children:c(as,{ref:S,onInput:J,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:U("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center shrink-0",children:pe&&p===ye.IDLE&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:U("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(yl,{className:"w-5 h-5",strokeWidth:1.5})})}),c("div",{className:"flex items-center gap-2 shrink-0",children:[s?c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className:U("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(Sl,{className:"w-4 h-4"})}):G?c(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:U("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):L&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:U("h-10 w-10 shrink-0",_e),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),L&&X&&!s&&c(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const jm=Xt(Vm),nc=bt(null),rc=nc.Provider;function zm(){const e=vt(nc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function $m({message:e,onDismiss:t}){return c(me,{children:[c("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),c("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:c("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[c("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),c("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:c(Cn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Ym(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=de(()=>{t(null)},[t]);return H(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?c($m,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?c("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:c("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Hm="Before we begin",Bm=e=>`A quick note on how ${e} works and handles your information.`,Gm=e=>[`This assistant is powered by AI. Replies are generated automatically and can be wrong, so please check anything important before you act on it. Don't use it in an urgent or emergency situation \u2014 contact ${e} directly or call your local emergency number.`,`To help you, ${e} and our authorised technology partners process what you share here \u2014 your contact details and your messages \u2014 under contractual and security safeguards, on secure servers. We use it only to provide this service, and keep it only as long as needed or as the law requires.`];function Wm(e,t){return(Array.isArray(e)?e:e.split(/\n\s*\n|\n/)).map(n=>String(n??"").replace(/\{\{\s*name\s*\}\}/gi,t).trim()).filter(Boolean)}const oc=(e,t)=>{if(t){const n=Wm(t,e);if(n.length)return n}return Gm(e)},Km="I agree and consent",qm="By continuing, you consent to the above.",Xm="Continue";function sc({botName:e,consentContent:t,isFullScreen:n}){return c(me,{children:[c("div",{className:"flex flex-col gap-1",children:[c("h2",{className:U("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Hm}),c("p",{className:U("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Bm(e)})]}),c("div",{className:U("overflow-y-auto rounded-lg border border-border-subtle flex flex-col",n?"max-h-[340px] p-4 gap-4":"max-h-[180px] p-3 gap-3"),tabIndex:0,role:"region","aria-label":"Consent details",children:oc(e,t).map((r,o)=>c("p",{className:U("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function Zm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return c(ds,{isOpen:e,onClose:t,children:c("div",{className:U("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?c(sc,{botName:n,consentContent:o,isFullScreen:s}):c("div",{className:"flex flex-col gap-2",children:[c("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),oc(n,o).map((a,l)=>c("p",{className:U("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},l))]}),c(Ee,{onClick:t,className:U("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Jm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=V(!1);return e?c(ds,{isOpen:e,children:c("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:U("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[c(sc,{botName:t,consentContent:n,isFullScreen:o}),c("div",{className:"flex flex-col gap-1.5",children:[c("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[c("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),c("div",{"aria-hidden":"true",className:U("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&c("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:U("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Km})]}),c("p",{className:U("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:qm})]}),c(Ee,{disabled:!i,onClick:()=>i&&r(),className:U("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Xm})]})}):null}const Qm=tt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),ep=tt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),tp=tt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),np=tt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),rp=tt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),op=[{label:"Took longer than expected",value:"took_longer"},{label:"Asking too many questions",value:"too_many_questions"},{label:"Irrelevant response",value:"irrelevant_response"},{label:"Other",value:"other"}],sp=[{Icon:Qm,label:"Bad",score:1},{Icon:ep,label:"Poor",score:2},{Icon:tp,label:"Okay",score:3},{Icon:np,label:"Good",score:4},{Icon:rp,label:"Great!",score:5}];function ip(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function ap({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,l]=V(null),[d,h]=V(new Set),[u,p]=V(!1),E=s&&a!==null?ip(a,t):t.form?.default?.length?t.form.default:op,g=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},f=_=>{l(_),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?c(ds,{isOpen:e,onClose:o,children:c("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[c("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),c("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[c("div",{className:"flex flex-col gap-1",children:[t.title&&c("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&c("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&c("div",{className:"flex items-center justify-between gap-1",children:sp.map(({Icon:_,label:y,score:k})=>{const x=a===k,w=a!==null&&!x;return c("button",{onClick:()=>f(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[c("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${w?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:c(Ze,{fallback:c("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:c(_,{})})}),c("span",{className:`text-[10px] leading-none transition-colors ${x?"text-primary/50 font-medium":w?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&E.length>0&&c("div",{className:"flex flex-col gap-2",children:E.map(_=>c("div",{onClick:()=>g(_.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(_.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:_.label},_.value))}),c(Ee,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),c("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>p(_=>!_),children:[c("div",{className:"relative w-3 h-3 shrink-0",children:c("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&c("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),c("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function ic({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:l,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:E,activeElicitation:g,voiceAgentState:f,theme:b,feedbackModal:m,consentModal:_}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:w,tagline:T,iconUrl:S,onStartNewSession:v,showStartNewChatButton:C,onToggleDisplayMode:L,onOpenSessionDrawer:X}=zm(),[G,he]=V(!1),[pe,se]=V(!1),[_e,F]=V(!1),le=q(null),Re=j(z=>z.level),te=l,J=te==="full",A=te==="side_panel",B=q(null),[re,Se]=V("");H(()=>{B.current!==null&&B.current!==te&&Se(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),B.current=te},[te]);const W=ae(()=>mm(b),[b]),Ae=j(z=>z.setIsMobile),$e=!!E,ie=de(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);mt(()=>{if(!le.current)return;const z=te==="full"?{...W,headerTinted:!1}:W;Ml(le.current,z),te==="full"&&!W.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),Ml(le.current,W))},[W,te]),H(()=>{const z=()=>{const Ie=window?.innerWidth??0,be=navigator?.userAgent?.toLowerCase()??"",Le=Ie<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(be);he(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),mt(()=>{if(!e||!G||!le.current)return;const z=le.current;let Ie=null,be=null,Le=null,qe=window.visualViewport?.offsetTop??0,Ue=0;const gt=2,ut=80;if(window.visualViewport){const je=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,Te=window.visualViewport.offsetTop;Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Te}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Ge}px`,z.style.maxHeight=`${Ge}px`,z.style.minHeight=`${Ge}px`,be&&clearTimeout(be),be=setTimeout(()=>{z.style.transition=""},100)})}},nt=()=>{je()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,Te=Date.now();Math.abs(Ge-qe)<gt||Te-Ue<ut||(Ue=Te,qe=Ge,Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",nt),window.visualViewport.addEventListener("scroll",Be),je(),()=>{Ie&&cancelAnimationFrame(Ie),be&&clearTimeout(be),Le&&clearTimeout(Le),window.visualViewport?.removeEventListener("resize",nt),window.visualViewport?.removeEventListener("scroll",Be),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const je=()=>{z&&(z.style.transition="none",z.style.top="0",z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height="100svh",z.style.maxHeight="100svh",setTimeout(()=>{z.style.transition=""},100))};return window.addEventListener("resize",je),je(),()=>{window.removeEventListener("resize",je),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),H(()=>{if(e&&!(A&&d==="push")){const z=le.current,Ie=window.scrollY,be=document.body.style.cssText,Le=document.documentElement.style.overflow,qe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ie}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",qe>0&&!G&&(document.body.style.paddingRight=`${qe}px`);let Ue=0;const gt=je=>{Ue=je.touches[0].clientY},ut=je=>{if(je.touches.length!==1)return;const nt=Ue-je.touches[0].clientY;Ue=je.touches[0].clientY;let Be=je.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:Te,scrollHeight:Bt,clientHeight:_t}=Be,an=Te<=0&&nt<0,ln=Te+_t>=Bt-1&&nt>0;if(!an&&!ln)return;break}Be=Be.parentElement}je.preventDefault()};return z&&(z.addEventListener("touchstart",gt,{passive:!0}),z.addEventListener("touchmove",ut,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",gt),z.removeEventListener("touchmove",ut)),document.body.style.cssText=be,document.documentElement.style.overflow=Le,window.scrollTo(0,Ie)}}},[e,G,A,d]),H(()=>{if(!(!A||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,A,d,h,u,p]);const{position:Pe,elementRef:De}=lm({enabled:e&&!G&&!J&&!A});H(()=>{le.current&&(De.current=le.current)},[De]);const Ct=U("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!J&&!A?"transition-all duration-300":"",G?"w-screen h-[100svh]":J?"w-screen h-screen":A?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Ht=U("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",W.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":J?"rounded-none border-0 flex-row":A?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return c("div",{ref:le,"data-mode":te,className:Ct,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...J&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...J&&!e&&{display:"none"},...A&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...A&&!e&&{display:"none"},...!G&&!J&&!A&&{left:`${Pe.x}px`,top:`${Pe.y}px`,bottom:"auto",right:"auto"},...G&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:W.backgroundImage?"transparent":"hsl(var(--background))"}},children:[c("style",{children:`
1
+ var qc=Object.defineProperty;var Xc=(e,t,n)=>t in e?qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>Xc(e,typeof t!="symbol"?t+"":t,n);var Pn,Z,Ns,Ut,Cs,xs,Ts,ro,Nr,Dn,ks,oo,so,io,Os,Cr={},xr=[],Zc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ln=Array.isArray;function St(e,t){for(var n in t)e[n]=t[n];return e}function ao(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function et(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?Pn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return Un(e,s,r,o,null)}function Un(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ns,__i:-1,__u:0};return o==null&&Z.vnode!=null&&Z.vnode(i),i}function Rs(){return{current:null}}function me(e){return e.children}function lt(e,t){this.props=e,this.context=t}function dn(e,t){if(t==null)return e.__?dn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?dn(e):null}function Jc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=St({},t);i.__v=t.__v+1,Z.vnode&&Z.vnode(i),co(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??dn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Ls(r,i,o),t.__e=t.__=null,i.__e!=n&&As(i)}}function As(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),As(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Ut.push(e)&&!Tr.__r++||Cs!=Z.debounceRendering)&&((Cs=Z.debounceRendering)||xs)(Tr)}function Tr(){try{for(var e,t=1;Ut.length;)Ut.length>t&&Ut.sort(Ts),e=Ut.shift(),t=Ut.length,Jc(e)}finally{Ut.length=Tr.__r=0}}function Is(e,t,n,r,o,i,s,a,c,d,h){var u,p,E,g,f,b,m,_=r&&r.__k||xr,y=t.length;for(c=Qc(n,t,_,c,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(p=E.__i!=-1&&_[E.__i]||Cr,E.__i=u,b=co(e,E,p,o,i,s,a,c,d,h),g=E.__e,E.ref&&p.ref!=E.ref&&(p.ref&&ho(p.ref,null,E),h.push(E.ref,E.__c||g,E)),f==null&&g!=null&&(f=g),(m=!!(4&E.__u))||p.__k===E.__k?(c=Ms(E,c,e,m),m&&p.__e&&(p.__e=null)):typeof E.type=="function"&&b!==void 0?c=b:g&&(c=g.nextSibling),E.__u&=-7);return n.__e=f,c}function Qc(e,t,n,r,o){var i,s,a,c,d,h=n.length,u=h,p=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=Un(null,s,null,null,null):Ln(s)?s=e.__k[i]=Un(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Un(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=ed(s,n,c,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=c&&(d==c-1?p--:d==c+1?p++:(d>c?p--:p++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=dn(a)),Fs(a,a));return r}function Ms(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Ms(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function At(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ln(e)?e.some(function(n){At(n,t)}):t.push(e)),t}function ed(e,t,n,r){var o,i,s,a=e.key,c=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&c==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&c==d.type)return s}return-1}function Ps(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Zc.test(t)?n:n+"px"}function kr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ps(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ps(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ks,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Dn]=r[Dn]:(n[Dn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ds(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Nr]==null)t[Nr]=oo++;else if(t[Nr]<n[Dn])return;return n(Z.event?Z.event(t):t)}}}function co(e,t,n,r,o,i,s,a,c,d){var h,u,p,E,g,f,b,m,_,y,k,x,w,T,S,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=Z.__b)&&h(t);e:if(typeof v=="function")try{if(m=t.props,_=v.prototype&&v.prototype.render,y=(h=v.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new v(m,k):(t.__c=u=new lt(m,k),u.constructor=v,u.render=nd),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&v.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=St({},u.__s)),St(u.__s,v.getDerivedStateFromProps(m,u.__s))),E=u.props,g=u.state,u.__v=t,p)_&&v.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&v.getDerivedStateFromProps==null&&m!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(m,k),t.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(m,u.__s,k)===!1){t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(C){C&&(C.__=t)}),xr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,g,f)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=Z.__r,w=0,_)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),xr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++w<25);u.state=u.__s,u.getChildContext!=null&&(r=St(St({},r),u.getChildContext())),_&&!p&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(E,g)),T=h!=null&&h.type===me&&h.key==null?Us(h.props.children):h,a=Is(e,Ln(T)?T:[T],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(C){if(t.__v=null,c||i!=null)if(C.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(S=i.length;S--;)ao(i[S]);uo(t)}else t.__e=n.__e,t.__k=n.__k,C.then||uo(t);Z.__e(C,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=td(n.__e,t,n,r,o,i,s,c,d);return(h=Z.diffed)&&h(t),128&t.__u?void 0:a}function uo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(uo))}function Ls(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);Z.__c&&Z.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){Z.__e(i,o.__v)}})}function Us(e){return typeof e!="object"||e==null||e.__b>0?e:Ln(e)?e.map(Us):e.constructor!==void 0?null:St({},e)}function td(e,t,n,r,o,i,s,a,c){var d,h,u,p,E,g,f,b=n.props||Cr,m=t.props,_=t.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(d=0;d<i.length;d++)if((E=i[d])&&"setAttribute"in E==!!_&&(_?E.localName==_:E.nodeType==3)){e=E,i[d]=null;break}}if(e==null){if(_==null)return document.createTextNode(m);e=document.createElementNS(o,_,m.is&&m),a&&(Z.__m&&Z.__m(t,i),a=!1),i=null}if(_==null)b===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&Pn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(E=e.attributes[d]).name]=E.value;for(d in b)E=b[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||kr(e,d,null,E,o);for(d in m)E=m[d],d=="children"?p=E:d=="dangerouslySetInnerHTML"?h=E:d=="value"?g=E:d=="checked"?f=E:a&&typeof E!="function"||b[d]===E||kr(e,d,E,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),Is(t.type=="template"?e.content:e,Ln(p)?p:[p],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&dn(n,0),a,c),i!=null)for(d=i.length;d--;)ao(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||_=="progress"&&!g||_=="option"&&g!=b[d])&&kr(e,d,g,b[d],o),d="checked",f!=null&&f!=e[d]&&kr(e,d,f,b[d],o))}return e}function ho(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){Z.__e(o,n)}}function Fs(e,t,n){var r,o;if(Z.unmount&&Z.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ho(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Z.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function nd(e,t,n){return this.constructor(e,n)}function Fn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],co(t,e=(!r&&n||t).__k=et(me,null,[e]),o||Cr,Cr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Pn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Ls(i,e,s)}function Vs(e,t){Fn(e,t,Vs)}function rd(e,t,n){var r,o,i,s,a=St({},e.props);for(i in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)i=="key"?r=t[i]:i=="ref"?o=t[i]:a[i]=t[i]===void 0&&s!=null?s[i]:t[i];return arguments.length>2&&(a.children=arguments.length>3?Pn.call(arguments,2):n),Un(e.type,a,r||e.key,o||e.ref,null)}function bt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,lo(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Os++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Pn=xr.slice,Z={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(a){e=a}throw e}},Ns=0,lt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=St({},this.state),typeof e=="function"&&(e=e(St({},n),this.props)),e&&St(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),lo(this))},lt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},lt.prototype.render=me,Ut=[],xs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ts=function(e,t){return e.__v.__b-t.__v.__b},Tr.__r=0,ro=Math.random().toString(8),Nr="__d"+ro,Dn="__a"+ro,ks=/(PointerCapture)$|Capture$/i,oo=0,so=Ds(!1),io=Ds(!0),Os=0;var od=0;function l(e,t,n,r,o,i){t||(t={});var s,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?s=t[a]:c[a]=t[a];var d={type:e,props:c,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--od,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)c[a]===void 0&&(c[a]=s[a]);return Z.vnode&&Z.vnode(d),d}var It,fe,mo,js,un=0,zs=[],xe=Z,$s=xe.__b,Ys=xe.__r,Hs=xe.diffed,Bs=xe.__c,Gs=xe.unmount,Ws=xe.__;function qt(e,t){xe.__h&&xe.__h(fe,e,un||t),un=0;var n=fe.__H||(fe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function V(e){return un=1,hn(qs,e)}function hn(e,t,n){var r=qt(It++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):qs(void 0,t),function(a){var c=r.__N?r.__N[0]:r.__[0],d=r.t(c,a);c!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=fe,!fe.__f)){var o=function(a,c,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,c,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var E=p.__[0];p.__=p.__N,p.__N=void 0,E!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,c,d)||u};fe.__f=!0;var i=fe.shouldComponentUpdate,s=fe.componentWillUpdate;fe.componentWillUpdate=function(a,c,d){if(this.__e){var h=i;i=void 0,o(a,c,d),i=h}s&&s.call(this,a,c,d)},fe.shouldComponentUpdate=o}return r.__N||r.__}function H(e,t){var n=qt(It++,3);!xe.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__H.__h.push(n))}function mt(e,t){var n=qt(It++,4);!xe.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__h.push(n))}function q(e){return un=5,ae(function(){return{current:e}},[])}function po(e,t,n){un=6,mt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ae(e,t){var n=qt(It++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function de(e,t){return un=8,ae(function(){return e},t)}function vt(e){var t=fe.context[e.__c],n=qt(It++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(fe)),t.props.value):e.__}function fo(e,t){xe.useDebugValue&&xe.useDebugValue(t?t(e):e)}function sd(e){var t=qt(It++,10),n=V();return t.__=e,fe.componentDidCatch||(fe.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=qt(It++,11);if(!e.__){for(var t=fe.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function id(){for(var e;e=zs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Or),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],xe.__e(n,e.__v)}}}xe.__b=function(e){fe=null,$s&&$s(e)},xe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ws&&Ws(e,t)},xe.__r=function(e){Ys&&Ys(e),It=0;var t=(fe=e.__c).__H;t&&(mo===fe?(t.__h=[],fe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Or),t.__h.some(_o),t.__h=[],It=0)),mo=fe},xe.diffed=function(e){Hs&&Hs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(zs.push(t)!==1&&js===xe.requestAnimationFrame||((js=xe.requestAnimationFrame)||ad)(id)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=fe=null},xe.__c=function(e,t){t.some(function(n){try{n.__h.some(Or),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],xe.__e(r,n.__v)}}),Bs&&Bs(e,t)},xe.unmount=function(e){Gs&&Gs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Or(r)}catch(o){t=o}}),n.__H=void 0,t&&xe.__e(t,n.__v))};var Ks=typeof requestAnimationFrame=="function";function ad(e){var t,n=function(){clearTimeout(r),Ks&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ks&&(t=requestAnimationFrame(n))}function Or(e){var t=fe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),fe=t}function _o(e){var t=fe;e.__c=e.__(),fe=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function qs(e,t){return typeof t=="function"?t(e):t}function Xs(e,t){for(var n in t)e[n]=t[n];return e}function yo(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function So(e,t){var n=t(),r=V({t:{__:n,u:t}}),o=r[0].t,i=r[1];return mt(function(){o.__=n,o.u=t,bo(o)&&i({t:o})},[e,n,t]),H(function(){return bo(o)&&i({t:o}),e(function(){bo(o)&&i({t:o})})},[e]),n}function bo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function vo(e){e()}function wo(e){return e}function No(){return[!1,vo]}var Co=mt;function Rr(e,t){this.props=e,this.context=t}function Xt(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,et(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Rr.prototype=new lt).isPureReactComponent=!0,Rr.prototype.shouldComponentUpdate=function(e,t){return yo(this.props,e)||yo(this.state,t)};var Zs=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Zs&&Zs(e)};var ld=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=Xs({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=ld,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Js=function(e,t){return e==null?null:At(At(e).map(t))},ot={map:Js,forEach:Js,count:function(e){return e?At(e).length:0},only:function(e){var t=At(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:At},cd=Z.__e;Z.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t)}cd(e,t,n,r)};var Qs=Z.unmount;function ei(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Xs({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return ei(r,t,n)})),e}function ti(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ti(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Ze(){this.__u=0,this.o=null,this.__b=null}function ni(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function tt(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(a){a&&(o=a.default||a),r=!0},function(a){n=a,r=!0}),n)throw n;if(!r)throw t;return o?et(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function mn(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Qs&&Qs(e)},(Ze.prototype=new lt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ni(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(c):c())};n.__R=s;var a=n.__P;n.__P=null;var c=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ti(d,d.__c.__P,d.__c.__O)}var h;for(r.setState({__a:r.__b=null});h=r.o.pop();)h.__P=a,h.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},Ze.prototype.componentWillUnmount=function(){this.o=[]},Ze.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=ei(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&et(me,null,e.fallback);return o&&(o.__u&=-33),[et(me,null,t.__a?null:e.children),o]};var ri=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function dd(e){return this.getChildContext=function(){return e.context},e.children}function ud(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Fn(et(dd,{context:t.context},e.__v),t.v)}function oi(e,t){var n=et(ud,{__v:e,h:t});return n.containerInfo=t,n}(mn.prototype=new lt).__a=function(e){var t=this,n=ni(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),ri(t,e,r)):o()};n?n(i):i()}},mn.prototype.render=function(e){this.i=null,this.l=new Map;var t=At(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},mn.prototype.componentDidUpdate=mn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){ri(e,n,t)})};var si=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,hd=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,md=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,pd=/[A-Z0-9]/g,fd=typeof document<"u",gd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Fn(e,t),typeof n=="function"&&n(),e?e.__c:null}function ii(e,t,n){return Vs(e,t),typeof n=="function"&&n(),e?e.__c:null}lt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(lt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ai=Z.event;Z.event=function(e){return ai&&(e=ai(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var To,_d={configurable:!0,get:function(){return this.class}},li=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||fd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||gd(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":md.test(s)&&(s=c):c=s="oninput":i&&hd.test(s)?s=s.replace(pd,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&o[s=c]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=At(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=At(n.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",_d)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=si,li&&li(e)};var ci=Z.__r;Z.__r=function(e){ci&&ci(e),To=e.__c};var di=Z.diffed;Z.diffed=function(e){di&&di(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),To=null};var ui={ReactCurrentDispatcher:{current:{readContext:function(e){return To.__n[e.__c].props.value},useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:H,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:hn,useRef:q,useState:V,useSyncExternalStore:So,useTransition:No}}},Ed="18.3.1";function hi(e){return et.bind(null,e)}function st(e){return!!e&&e.$$typeof===si}function mi(e){return st(e)&&e.type===me}function pi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Ft(e){return st(e)?rd.apply(null,arguments):e}function ko(e){return!!e.__k&&(Fn(null,e),!0)}function fi(e){return e&&(e.base||e.nodeType===1&&e)||null}var gi=function(e,t){return e(t)},_i=function(e,t){var n=Z.debounceRendering;Z.debounceRendering=function(o){return o()};var r=e(t);return Z.debounceRendering=n,r},Ei=st,Vn={useState:V,useId:go,useReducer:hn,useEffect:H,useLayoutEffect:mt,useInsertionEffect:Co,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:vo,useRef:q,useImperativeHandle:po,useMemo:ae,useCallback:de,useContext:vt,useDebugValue:fo,version:"18.3.1",Children:ot,render:xo,hydrate:ii,unmountComponentAtNode:ko,createPortal:oi,createElement:et,createContext:bt,createFactory:hi,cloneElement:Ft,createRef:Rs,Fragment:me,isValidElement:st,isElement:Ei,isFragment:mi,isMemo:pi,findDOMNode:fi,Component:lt,PureComponent:Rr,memo:Xt,forwardRef:ee,flushSync:_i,unstable_batchedUpdates:gi,StrictMode:me,Suspense:Ze,SuspenseList:mn,lazy:tt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:ot,Component:lt,Fragment:me,PureComponent:Rr,StrictMode:me,Suspense:Ze,SuspenseList:mn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui,cloneElement:Ft,createContext:bt,createElement:et,createFactory:hi,createPortal:oi,createRef:Rs,default:Vn,findDOMNode:fi,flushSync:_i,forwardRef:ee,hydrate:ii,isElement:Ei,isFragment:mi,isMemo:pi,isValidElement:st,lazy:tt,memo:Xt,render:xo,startTransition:vo,unmountComponentAtNode:ko,unstable_batchedUpdates:gi,useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:H,useErrorBoundary:sd,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:hn,useRef:q,useState:V,useSyncExternalStore:So,useTransition:No,version:Ed},Symbol.toStringTag,{value:"Module"}));function yd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function yi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ro(...e){return t=>{let n=!1;const r=e.map(o=>{const i=yi(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():yi(e[o],null)}}}}function Vt(...e){return de(Ro(...e),e)}function Sd(e){const t=bd(e),n=ee((r,o)=>{const{children:i,...s}=r,a=ot.toArray(i),c=a.find(wd);if(c){const d=c.props.children,h=a.map(u=>u===c?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:st(d)?Ft(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function bd(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(st(o)){const s=Cd(o),a=Nd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vd=Symbol("radix.slottable");function wd(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===vd}function Nd(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Cd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var xd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=xd.reduce((e,t)=>{const n=Sd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Zt=globalThis?.document?mt:()=>{};function Td(e,t){return hn((n,r)=>t[n][r]??n,e)}var fn=e=>{const{present:t,children:n}=e,r=kd(t),o=typeof n=="function"?n({present:r.isPresent}):ot.only(n),i=Vt(r.ref,Od(o));return typeof n=="function"||r.isPresent?Ft(o,{ref:i}):null};fn.displayName="Presence";function kd(e){const[t,n]=V(),r=q(null),o=q(e),i=q("none"),s=e?"mounted":"unmounted",[a,c]=Td(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return H(()=>{const d=Ar(r.current);i.current=a==="mounted"?d:"none"},[a]),Zt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Ar(d);e?c("MOUNT"):p==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Zt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const g=Ar(r.current).includes(CSS.escape(E.animationName));if(E.target===t&&g&&(c("ANIMATION_END"),!o.current)){const f=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f)})}},p=E=>{E.target===t&&(i.current=Ar(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:de(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Ar(e){return e?.animationName||"none"}function Od(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Si(e,t=[]){let n=[];function r(i,s){const a=bt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[c]||a,b=ae(()=>g,Object.values(g));return l(f.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[c]||a,g=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Rd(o,...t)]}function Rd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function jt(e){const t=q(e);return H(()=>{t.current=e}),ae(()=>(...n)=>t.current?.(...n),[])}var Ad=bt(void 0);function Id(e){const t=vt(Ad);return e||t||"ltr"}function Md(e,[t,n]){return Math.min(n,Math.max(t,e))}function zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Pd(e,t){return hn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[bi]=Si(Ao),[Dd,ct]=bi(Ao),vi=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=V(null),[d,h]=V(null),[u,p]=V(null),[E,g]=V(null),[f,b]=V(null),[m,_]=V(0),[y,k]=V(0),[x,w]=V(!1),[T,S]=V(!1),v=Vt(t,L=>c(L)),C=Id(o);return l(Dd,{scope:n,type:r,dir:C,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:E,onScrollbarXChange:g,scrollbarXEnabled:x,onScrollbarXEnabledChange:w,scrollbarY:f,onScrollbarYChange:b,scrollbarYEnabled:T,onScrollbarYEnabledChange:S,onCornerWidthChange:_,onCornerHeightChange:k,children:l(pn.div,{dir:C,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});vi.displayName=Ao;var wi="ScrollAreaViewport",Ni=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ct(wi,n),a=q(null),c=Vt(t,a,s.onViewportChange);return l(me,{children:[l("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),l(pn.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:l("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ni.displayName=wi;var wt="ScrollAreaScrollbar",Io=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return H(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?l(Ld,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(Ud,{...r,ref:t,forceMount:n}):o.type==="auto"?l(Ci,{...r,ref:t,forceMount:n}):o.type==="always"?l(Mo,{...r,ref:t}):null});Io.displayName=wt;var Ld=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),[i,s]=V(!1);return H(()=>{const a=o.scrollArea;let c=0;if(a){const d=()=>{window.clearTimeout(c),s(!0)},h=()=>{c=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),l(fn,{present:n||i,children:l(Ci,{"data-state":i?"visible":"hidden",...r,ref:t})})}),Ud=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Dr(()=>c("SCROLL_END"),100),[a,c]=Pd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return H(()=>{if(a==="idle"){const d=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,c]),H(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const p=()=>{const E=d[h];u!==E&&(c("SCROLL"),s()),u=E};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[o.viewport,i,c,s]),l(fn,{present:n||a!=="hidden",children:l(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:zt(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:zt(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Ci=ee((e,t)=>{const n=ct(wt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=V(!1),a=e.orientation==="horizontal",c=Dr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return gn(n.viewport,c),gn(n.content,c),l(fn,{present:r||i,children:l(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=ct(wt,e.__scopeScrollArea),i=q(null),s=q(0),[a,c]=V({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ri(a.viewport,a.content),h={...r,sizes:a,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,E){return Yd(p,s.current,a,E)}return n==="horizontal"?l(Fd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,E=Ai(p,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?l(Vd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,E=Ai(p,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Fd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=V(),c=q(null),d=Vt(t,c,i.onScrollbarXChange);return H(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ti,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(p),Mi(p,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Mr(s.paddingLeft),paddingEnd:Mr(s.paddingRight)}})}})}),Vd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=V(),c=q(null),d=Vt(t,c,i.onScrollbarYChange);return H(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ti,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(p),Mi(p,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Mr(s.paddingTop),paddingEnd:Mr(s.paddingBottom)}})}})}),[jd,xi]=bi(wt),Ti=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:u,...p}=e,E=ct(wt,n),[g,f]=V(null),b=Vt(t,v=>f(v)),m=q(null),_=q(""),y=E.viewport,k=r.content-r.viewport,x=jt(h),w=jt(c),T=Dr(u,10);function S(v){if(m.current){const C=v.clientX-m.current.left,L=v.clientY-m.current.top;d({x:C,y:L})}}return H(()=>{const v=C=>{const L=C.target;g?.contains(L)&&x(C,k)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[y,g,k,x]),H(w,[r,w]),gn(g,T),gn(E.content,T),l(jd,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:jt(i),onThumbPointerUp:jt(s),onThumbPositionChange:w,onThumbPointerDown:jt(a),children:l(pn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:zt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),m.current=g.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),S(v))}),onPointerMove:zt(e.onPointerMove,S),onPointerUp:zt(e.onPointerUp,v=>{const C=v.target;C.hasPointerCapture(v.pointerId)&&C.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Ir="ScrollAreaThumb",ki=ee((e,t)=>{const{forceMount:n,...r}=e,o=xi(Ir,e.__scopeScrollArea);return l(fn,{present:n||o.hasThumb,children:l(zd,{ref:t,...r})})}),zd=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ct(Ir,n),s=xi(Ir,n),{onThumbPositionChange:a}=s,c=Vt(t,u=>s.onThumbChange(u)),d=q(void 0),h=Dr(()=>{d.current&&(d.current(),d.current=void 0)},100);return H(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const E=Hd(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),l(pn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:zt(e.onPointerDownCapture,u=>{const p=u.target.getBoundingClientRect(),E=u.clientX-p.left,g=u.clientY-p.top;s.onThumbPointerDown({x:E,y:g})}),onPointerUp:zt(e.onPointerUp,s.onThumbPointerUp)})});ki.displayName=Ir;var Po="ScrollAreaCorner",Oi=ee((e,t)=>{const n=ct(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l($d,{...e,ref:t}):null});Oi.displayName=Po;var $d=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ct(Po,n),[i,s]=V(0),[a,c]=V(0),d=!!(i&&a);return gn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),gn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(pn.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Mr(e){return e?parseInt(e,10):0}function Ri(e,t){const n=e/t;return isNaN(n)?0:n}function Pr(e){const t=Ri(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Yd(e,t,n,r="ltr"){const o=Pr(n),i=o/2,s=t||i,a=o-s,c=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return Ii([c,d],u)(e)}function Ai(e,t,n="ltr"){const r=Pr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,c=n==="ltr"?[0,s]:[s*-1,0],d=Md(e,c);return Ii([0,s],[0,a])(d)}function Ii(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mi(e,t){return e>0&&e<t}var Hd=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function Dr(e,t){const n=jt(e),r=q(0);return H(()=>()=>window.clearTimeout(r.current),[]),de(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function gn(e,t){const n=jt(t);Zt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Pi=vi,Bd=Ni,Gd=Oi;function Wd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var _n={},jn={},Di={},zn={},$n={},Yn={},Li;function Do(){if(Li)return Yn;Li=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.EventEmitter=void 0;let e=class{constructor(){R(this,"eventListeners",new Map)}on(t,n){const r=this.eventListeners.get(t)||new Set;r.add(n),this.eventListeners.set(t,r)}off(t,n){const r=this.eventListeners.get(t);r&&(r.delete(n),r.size===0&&this.eventListeners.delete(t))}emit(t,...n){const r=this.eventListeners.get(t);r&&r.forEach(o=>o(...n))}removeAllListeners(){this.eventListeners.clear()}};return Yn.EventEmitter=e,Yn}var En={},Ui;function Hn(){return Ui||(Ui=1,Object.defineProperty(En,"__esModule",{value:!0}),En.DisconnectionReason=En.ConnectionStatus=void 0,En.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},En.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),En}var Fi;function Lo(){if(Fi)return $n;Fi=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.BaseConnection=void 0;const e=Do(),t=Hn();let n=class{constructor(){R(this,"status",t.ConnectionStatus.CONNECTING);R(this,"queue",[]);R(this,"eventEmitter",new e.EventEmitter);R(this,"disconnectionDetails",null);R(this,"onErrorCallback",null);R(this,"onDisconnectCallback",null);R(this,"onMessageCallback",null);R(this,"onOpenCallback",null);R(this,"onStatusChangeCallback",null)}getStatus(){return this.status}onOpen(r){this.onOpenCallback=r}onMessage(r){if(this.onMessageCallback=r,this.queue.length>0){const o=[...this.queue];this.queue.length=0,queueMicrotask(()=>{o.forEach(i=>{this.onMessageCallback?.(i)})})}}onDisconnect(r){this.onDisconnectCallback=r;const o=this.disconnectionDetails;o&&queueMicrotask(()=>{this.onDisconnectCallback?.(o)})}onError(r){this.onErrorCallback=r}on(r,o){this.eventEmitter.on(r,o)}off(r,o){this.eventEmitter.off(r,o)}emit(r,...o){this.eventEmitter.emit(r,...o)}onStatusChange(r){this.onStatusChangeCallback=r,queueMicrotask(()=>{r(this.status)})}disconnect(r){this.disconnectionDetails||(this.disconnectionDetails=r,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.onDisconnectCallback?.(r))}handleMessage(r){this.onMessageCallback?this.onMessageCallback(r):this.queue.push(r)}updateStatus(r){this.status!==r&&(this.status=r,this.onStatusChangeCallback?.(r))}};return $n.BaseConnection=n,$n}var Vi={},ji;function it(){return ji||(ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=x,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(S,v=e.SynapseErrorCode.UNKNOWN,C={}){super(S);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=v,this.timestamp=new Date,this.cause=C.cause,this.context=C.context,this.hint=C.hint,this.reason=C.reason,this.displayMessage=C.displayMessage||C?.hint||S,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(S,v,C,L){const X=n.makeMessage(v,C,S);super(X,e.SynapseErrorCode.API,{cause:C,context:{status:v,hasBody:!!C},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:S||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=C,this.headers=L}static makeMessage(S,v,C){const L=v instanceof Error?v.message:C;return S&&L?`HTTP ${S}: ${L}`:S?`${S} status code (no body)`:L||"(no status code or body)"}static generate(S,v,C,L){if(!S)return new r({message:C});const X=v?.error,G=X&&typeof X=="object"&&!Array.isArray(X)?X:void 0;switch(S){case 400:return new i(C||"Bad Request",S,G,L);case 401:return new s(C||"Unauthorized",S,G,L);case 403:return new a(C||"Permission Denied",S,G,L);case 404:return new c(C||"Not Found",S,G,L);case 405:return new d(C||"Method Not Allowed",S,G,L);case 429:return new h(C||"Rate Limit Exceeded",S,G,L);case 500:return new u(C||"Internal Server Error",S,G,L);default:return new n(C||"API Error",S,G,L)}}}e.APIError=n;class r extends n{constructor({message:T}={}){super(T||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:T}={}){super(T||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(T,S,v,C){super(T,S,v,C),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.CONNECTION,S),this.name="ConnectionError"}}e.ConnectionError=p;class E extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.RECORDING,S),this.name="RecordingError"}}e.RecordingError=E;class g extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.AUTH,S),this.name="AuthenticationError"}}e.AuthenticationError=g;class f extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.FILE,S),this.name="FileError"}}e.FileError=f;class b extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.SESSION,S),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.MESSAGE,S),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.STORE,S),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.CONFIGURATION,S),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(T,S={}){super(T,e.SynapseErrorCode.VALIDATION,S),this.name="ValidationError"}}e.ValidationError=k;function x(w,T,S,v={}){if(w instanceof T)return w;const C={...v,context:{...w instanceof t?w.context:void 0,...v.context},hint:v.hint??(w instanceof t?w.hint:void 0),reason:v.reason??(w instanceof t?w.reason:void 0),cause:v.cause??w};if(w instanceof t)return new T(w.message,C);const L=w instanceof Error&&w.message?w.message:S;return new T(L,C)}})(Vi)),Vi}var zi;function $i(){if(zi)return zn;zi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.WebSocketConnection=void 0;const e=Lo(),t=Hn(),n=it();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const c=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(c)}}handleError(s){}handleClose(s){const a=s.wasClean,c=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(c===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):c===1001||c===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):c===4001||c===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):c===4401||c===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(c===4401?"Session token expired":"Session credentials rejected")):c===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):c===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:c,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const c=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(c),c}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return zn.WebSocketConnection=r,zn}var Bn={},Yi={},Hi;function Bi(){return Hi||(Hi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=void 0,e.SYNAPSE_CHANNELS={WIDGET:"widget",WEB:"web",SIDE_PANEL:"side_panel"},e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS.WIDGET})(Yi)),Yi}var Gi;function Wi(){if(Gi)return Bn;Gi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.SSEConnection=void 0;const e=Lo(),t=Hn(),n=Bi(),r=it();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const c=new AbortController;this.activeStreamController=c,this.streamChat(a,c)}postChat(a,c,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(c),signal:d.signal})}async streamChat(a,c){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,c);if(h.status===401&&this.config.auth.onUnauthorized){const g=await this.config.auth.onUnauthorized();if(c.signal.aborted)return;g&&(h=await this.postChat(d,a,c))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),p=new TextDecoder;let E="";for(;;){const{done:g,value:f}=await u.read();if(g)break;E+=p.decode(f,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(c.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===c&&(this.activeStreamController=null)}}extractJsonObjects(a){let c=0;for(;c<a.length;){const d=a.indexOf("{",c);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const p=JSON.parse(u);this.handleMessage(p)}catch(p){const E=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(E)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let p=c;p<a.length;p++){const E=a[p];if(h){u?u=!1:E==="\\"?u=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")d++;else if(E==="}"&&(d--,d===0))return p}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Bn.SSEConnection=o,Bn}var Ki;function qi(){return Ki||(Ki=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=$i(),n=Wi(),r=it();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(Di)),Di}var Gn={},Xi;function Uo(){if(Xi)return Gn;Xi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Gn.getConfig=r,Gn}var Wn={},Kn={},Zi;function Lr(){if(Zi)return Kn;Zi=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.HttpClient=void 0;const e=it();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const c=this.buildUrl(r,o?.params),d=await fetch(c,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(c){if(s=c,a===i||!(c instanceof TypeError&&c.message==="Failed to fetch"||c instanceof DOMException&&c.name==="AbortError"||c instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Kn.HttpClient=t,Kn}var qn={},Xn={},Ji;function Zn(){if(Ji)return Xn;Ji=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.BaseResource=void 0;let e=class{constructor(t){R(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return Xn.BaseResource=e,Xn}var Qi;function ea(){if(Qi)return qn;Qi=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Session=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:c}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...c&&{nps_base5:c}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return qn.Session=t,qn}var Jn={},ta;function Fo(){if(ta)return Jn;ta=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.Config=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return Jn.Config=t,Jn}var na={},ra;function oa(){return ra||(ra=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Lr(),n=Uo(),r=Fo(),o=new Map,i=(c,d)=>`${c.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(c){const d=c.serverUrl||(0,n.getConfig)(c.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,c.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":c.agentId,...c.channel&&{"x-channel":c.channel}}}),E=new r.Config(p).retrieve(c.agentId);return E.catch(()=>{o.get(h)===E&&o.delete(h)}),o.set(h,E),E}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(na)),na}var Qn={},sa;function Vo(){if(sa)return Qn;sa=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.Auth=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Qn.Auth=t,Qn}var er={},yn={},ia;function jo(){return ia||(ia=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.ErrorType=yn.SYNAPSE_RECOVERY_REASON=void 0,yn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},yn.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),yn}var tr={},aa;function zo(){if(aa)return tr;aa=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.ErrorUtils=void 0;const e=it();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return tr.ErrorUtils=t,tr}var la={},ca;function da(){return ca||(ca=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=Lr(),n=Uo(),r=zo(),o=Vo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),p=i.get(u);if(p)return p;const E=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),g=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return g.catch(f=>{r.ErrorUtils.isAuthError(f)||i.get(u)===g&&i.delete(u)}),i.set(u,g),g}function c(d){const h=i.get(d);return h&&i.delete(d),h}})(la)),la}var ua;function Kd(){if(ua)return er;ua=1,Object.defineProperty(er,"__esModule",{value:!0}),er.TokenManager=void 0;const e=it(),t=jo(),n=zo(),r=da();let o=class{constructor(i,s,a,c){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=c.partnerAuthToken,this.refreshToken=c.refreshToken,this.onTokenExchange=c.onTokenExchange,this._level=c.level,this._userId=c.userId,c.sessToken&&(this.sessToken=c.sessToken,this.httpClient.setAuthorization(c.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(c.serverUrl,a,c.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,c){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,c,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return er.TokenManager=o,er}var nr={},ha;function qd(){var n;if(ha)return nr;ha=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceResource=void 0;const e=Zn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return nr.VoiceResource=t,nr}var ma;function pa(){if(ma)return Wn;ma=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ResourceManager=void 0;const e=Lr(),t=ea(),n=it(),r=Fo(),o=oa(),i=Vo(),s=Kd(),a=qd();class c{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:p,intent:E,user_location:g,referer:f,...b}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...p&&{user_context:p},...(E||Object.keys(b).length>0)&&{session_context:{...E&&{intent:E},...g&&{user_location:g},...b}},...f&&{referer:f}},y=await this.session.create(_);if(!y?.session_id)throw new n.APIError("Failed to start session.",500,void 0,void 0);return y}catch(p){throw p instanceof n.APIError?p:new n.APIError("Failed to start session.",500,void 0,void 0)}}async getAgentConfig(){this.config||(this.config=new r.Config(this.httpClient));const h=(0,o.consumePrefetchedAgentConfig)((0,o.buildAgentConfigKey)(this.resourceConfig.serverUrl,this.resourceConfig.agentId));if(h)try{return await h}catch{}try{return await this.config.retrieve(this.resourceConfig.agentId)}catch{throw new n.APIError("Failed to get agent config.",500,void 0,void 0)}}async reinitialiseSession(h){return await this.session.retrieve(h)}async getPastSessions(){return await this.session.history()}async getSessionMessages(h){return(await this.session.retrieve(h,{includeMessages:!0}))?.messages??[]}async refreshTokens(){return await this.tokenManager.refresh()}async sendFeedback({sessionId:h,messageId:u,feedback:p,feedbacks:E,feedbackReason:g,npsBase5:f}){return await this.session.feedback({sessionId:h,messageId:u,feedback:p,feedbacks:E,feedbackReason:g,npsBase5:f})}async callTool(h,u,p,E){return await this.session.callTool(h,u,p,E)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Wn.ResourceManager=c,Wn}var rr={},fa={},ga;function $o(){return ga||(ga=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MULTI_SELECT_ADDITIONAL_OPTION=e.SOCKET_EVENTS=e.SOCKET_CONTENT_TYPES=void 0,e.IsValidSocketMesssage=t,e.SOCKET_CONTENT_TYPES={TEXT:"text",AUDIO:"audio",FILE:"file",TOOL_CALL:"tool",TIPS:"tips",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},e.SOCKET_EVENTS={PING:"ping",PONG:"pong",CHAT:"chat",STREAM:"stream",AUTH:"auth",END_OF_STREAM:"eos",SYNC:"sync",ERROR:"err",CONNECTION_ESTABLISHED:"conn"},e.MULTI_SELECT_ADDITIONAL_OPTION={NOTA:"none_of_the_above",AOTA:"all_of_the_above"};function t(n){return[e.SOCKET_EVENTS.PING,e.SOCKET_EVENTS.PONG,e.SOCKET_EVENTS.ERROR,e.SOCKET_EVENTS.SYNC,e.SOCKET_EVENTS.CONNECTION_ESTABLISHED,e.SOCKET_EVENTS.CHAT,e.SOCKET_EVENTS.STREAM,e.SOCKET_EVENTS.END_OF_STREAM].includes(n.ev)}})(fa)),fa}var _a={},Ea;function Xd(){return Ea||(Ea=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=it();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.filter(a=>a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const c=s[a].url,d=await fetch(c,{method:"PUT",body:this.pendingFiles[a],headers:{"Content-Type":this.pendingFiles[a].type,"x-ms-blob-type":"BlockBlob"}});if(!d.ok)throw new t.FileError(`Failed to upload ${this.pendingFiles[a].name} to URL ${a+1}: ${d.status} ${d.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(s[a].id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[]}}e.Filemanager=n})(_a)),_a}var pt={},ya;function Ur(){if(ya)return pt;ya=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.SYNAPSE_REALTIME_RESERVED_EVENTS=pt.SYNAPSE_REALTIME_ERROR_CODES=pt.SYNAPSE_REALTIME_EVENTS=pt.SYNAPSE_MESSAGE_TYPES=void 0;const e=$o();return pt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,pt.SYNAPSE_REALTIME_EVENTS={CONNECTED:"connected",DISCONNECTED:"disconnected",PROGRESS_MESSAGE:"progress_message",MESSAGE_CHUNK:"message_chunk",TIPS_MESSAGE:"tips_message",END_OF_STREAM:"end_of_stream",ERROR:"error",TOOL_CALL:"tool_call",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},pt.SYNAPSE_REALTIME_ERROR_CODES={SESSION_INACTIVE:"session_not_found",SESSION_TOKEN_EXPIRED:"sess_token_expired",INVALID_EVENT:"invalid_event",INVALID_CONTENT_TYPE:"invalid_content",PARSING_ERROR:"parsing",FILE_UPLOAD_INPROGRESS:"file_upload_inprogress",TIMEOUT:"timeout",SERVER_ERROR:"server_error",SESSION_TOKEN_MISMATCH:"session_token_mismatch",PROMPT_FETCH_ERROR:"prompt_fetch_error",INVALID_FILE_REQUEST:"invalid_file_request",SESSION_NOT_OWNED:"session_not_owned"},pt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},pt}var or={},Sa;function Zd(){if(Sa)return or;Sa=1,Object.defineProperty(or,"__esModule",{value:!0}),or.AudioManager=void 0;const e=it();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return or.AudioManager=t,or}var ba;function va(){if(ba)return rr;ba=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.MessageManager=void 0;const e=$o(),t=Xd(),n=Ur(),r=Zd(),o=it();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:c,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(c&&c.length>0){const p=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:c,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:c,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...c&&{audio:c},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},...E&&{initial_prompts:E}};return}const g=this.connection;let f;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}f=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:p})}else s?f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},...E&&{initial_prompts:E},...p&&{tool_result:p}}}:c&&c?.audio&&c?.format?f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:c?.audio,format:c?.format,...h&&{tool_declined:h},...p&&{tool_result:p}}}:p&&(f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:p}});if(!f){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g.sendMessage(f)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(c=>{this.sendSocketMessage({urls:c})}).catch(c=>{const d=this.toFileError(c,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,c)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const c={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,c)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,c)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const c={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,c);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const c=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),c={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(c)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const c=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(c),c}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,c=>{const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(c){const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,c,d){return(0,o.normalizeError)(s,o.FileError,a,{context:c,hint:d})}toRecordingError(s,a,c,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:c,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return rr.MessageManager=i,rr}var wa={},Na;function Jd(){return Na||(Na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.outcomeForHttpStatus=e.outcomeForCloseCode=e.RECOVERY_OUTCOME=void 0,e.RECOVERY_OUTCOME={REFRESH_AND_RETRY:"refresh_and_retry",FORBIDDEN:"forbidden",SESSION_GONE:"session_gone",RETRY_LATER:"retry_later",SESSION_NOT_OWNED:"session_not_owned"};const t={4401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,4403:e.RECOVERY_OUTCOME.FORBIDDEN,4404:e.RECOVERY_OUTCOME.SESSION_GONE,1013:e.RECOVERY_OUTCOME.RETRY_LATER},n={401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,403:e.RECOVERY_OUTCOME.FORBIDDEN,404:e.RECOVERY_OUTCOME.SESSION_GONE,429:e.RECOVERY_OUTCOME.RETRY_LATER,503:e.RECOVERY_OUTCOME.RETRY_LATER},r=i=>i===void 0?void 0:t[i];e.outcomeForCloseCode=r;const o=i=>i===void 0?void 0:n[i];e.outcomeForHttpStatus=o})(wa)),wa}var sr={},ir={},Ca;function Qd(){if(Ca)return ir;Ca=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),c=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(c)};c()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return ir.VoiceAudioAnalyser=t,ir}var Sn={},xa;function Ta(){return xa||(xa=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.VOICE_AGENT_EVENTS=Sn.VOICE_AGENT_STATE=void 0,Sn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Sn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Sn}var ka;function eu(){if(ka)return sr;ka=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.VoiceAgent=void 0;const e=Do(),t=Qd(),n=it(),r=Ta(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const E=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),p())}})}let d=class{constructor(h,u,p){R(this,"config");R(this,"resourceManager");R(this,"getCredentials");R(this,"emitter",new e.EventEmitter);R(this,"remoteAnalyser",new t.VoiceAudioAnalyser);R(this,"localAnalyser",new t.VoiceAudioAnalyser);R(this,"pc",null);R(this,"pcId",null);R(this,"dataChannel",null);R(this,"localStream",null);R(this,"remoteAudio",null);R(this,"_state",r.VOICE_AGENT_STATE.IDLE);R(this,"_isMuted",!1);R(this,"manuallyDisconnected",!1);R(this,"_hasConnectionFailureNotified",!1);R(this,"_userSpeaking",!1);R(this,"_silenceTimer",null);R(this,"_cachedIceServers",null);R(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=p}get state(){return this._state}get isMuted(){return this._isMuted}on(h,u){this.emitter.on(h,u)}off(h,u){this.emitter.off(h,u)}async connect(){const h=await this.getCredentials();this.setState(r.VOICE_AGENT_STATE.CONNECTING),this._hasConnectionFailureNotified=!1;try{if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available. Please ensure you are using a secure (HTTPS) connection.");const u=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=u;const p=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:p,iceTransportPolicy:"all"});this.pc=E,this.dataChannel=E.createDataChannel("pipecat-events",{ordered:!0}),this.dataChannel.onopen=()=>{},this.dataChannel.onclose=()=>this.handleConnectionFailure(new Error("Data channel closed"),"Voice connection failed"),this.dataChannel.onerror=()=>this.handleConnectionFailure(new Error("Data channel error"),"Voice connection failed"),u.getAudioTracks().forEach(_=>E.addTrack(_,u)),E.ontrack=_=>this.handleRemoteTrack(_),E.onconnectionstatechange=()=>{E.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(E.connectionState==="failed"||E.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},E.oniceconnectionstatechange=()=>{(E.iceConnectionState==="connected"||E.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):E.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const g=await E.createOffer();await E.setLocalDescription(g);const f=this.config.iceGatheringTimeoutMs??o;await c(E,f);const b=_=>({sdp:E.localDescription.sdp,type:E.localDescription.type,pc_id:this.pcId,request_data:{session_id:_.sessionId,token:_.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(b(h))}catch(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(b(y))}else throw _}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,E.signalingState==="closed")return;await E.setRemoteDescription(new RTCSessionDescription({sdp:m.sdp,type:m.type}))}catch(u){this.handleConnectionFailure(u)}}disconnect(){this.manuallyDisconnected=!0,this.setState(r.VOICE_AGENT_STATE.DISCONNECTING),this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE)}toggleMute(){if(!this.localStream)return;const h=this.localStream.getAudioTracks()[0];if(!h)return;const u=h.enabled;this.localStream.getAudioTracks().forEach(p=>{p.enabled=!u}),this._isMuted=u,this.clearSilenceTimer(),this._userSpeaking=!1,this.setState(u?r.VOICE_AGENT_STATE.MUTED:r.VOICE_AGENT_STATE.LISTENING)}reset(){this.setState(r.VOICE_AGENT_STATE.IDLE)}destroy(){this.releaseResources(),this.emitter.removeAllListeners(),this._state=r.VOICE_AGENT_STATE.IDLE}async fetchIceServers(h){if(this.config.iceServers)return this.config.iceServers;const u=Date.now();if(this._cachedIceServers&&u-this._iceServersCachedAt<s)return this._cachedIceServers;let p;try{p=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const g=await this.getCredentials();p=await this.resourceManager.getVoiceIceServers(g.sessionId)}else throw E}if(!Array.isArray(p?.ice_servers)||p.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=p.ice_servers,this._iceServersCachedAt=Date.now(),this._cachedIceServers}setState(h){this._state=h,this.emitter.emit(r.VOICE_AGENT_EVENTS.STATE_CHANGED,h)}clearSilenceTimer(){this._silenceTimer!==null&&(clearTimeout(this._silenceTimer),this._silenceTimer=null)}handleConnectionFailure(h,u="Voice connection failed"){if(this._hasConnectionFailureNotified||this._state===r.VOICE_AGENT_STATE.DISCONNECTING||this.manuallyDisconnected)return;this._hasConnectionFailureNotified=!0,this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.ERROR);const p={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,p)}releaseResources(){this.remoteAnalyser.stop(),this.localAnalyser.stop(),this.clearSilenceTimer(),this._userSpeaking=!1,this.localStream&&(this.localStream.getTracks().forEach(h=>h.stop()),this.localStream=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.pc&&(this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.ondatachannel=null,this.pc.close(),this.pc=null),this.pcId=null,this._isMuted=!1,this.remoteAudio&&(this.remoteAudio.srcObject=null)}startLocalAudioAnalysis(h){const u=this.config.speakingThreshold??i;this.localAnalyser.start(h,u,p=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(p?(this._userSpeaking=!0,this.clearSilenceTimer(),this._state===r.VOICE_AGENT_STATE.THINKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)):this._userSpeaking&&this._silenceTimer===null&&(this._silenceTimer=setTimeout(()=>{this._silenceTimer=null,this._userSpeaking&&this._state===r.VOICE_AGENT_STATE.LISTENING&&(this._userSpeaking=!1,this.setState(r.VOICE_AGENT_STATE.THINKING))},a)))})}handleRemoteTrack(h){this.remoteAudio||(this.remoteAudio=new Audio,this.remoteAudio.autoplay=!0);const u=h.streams[0];this.remoteAudio.srcObject=u;const p=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,p,E=>{E?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return sr.VoiceAgent=d,sr}var Oa;function tu(){if(Oa)return jn;Oa=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.SynapseSDK=void 0;const e=qi(),t=Hn(),n=Uo(),r=pa(),o=va(),i=Ur(),s=Do(),a=it(),c=jo(),d=Jd(),h=$o(),u=eu();class p{constructor(g){R(this,"connection",null);R(this,"messageManager");R(this,"resourceManager");R(this,"sessionConfig",null);R(this,"config");R(this,"connectionType");R(this,"isRefreshingSession",!1);R(this,"isRecovering",!1);R(this,"forceConsumed",!1);R(this,"connectionAttempts",0);R(this,"sdkEventEmitter",new s.EventEmitter);R(this,"_voice",null);R(this,"pendingNetworkReconnect",!1);R(this,"boundOnlineHandler",null);R(this,"isReconnecting",!1);R(this,"reconnectTimer",null);R(this,"boundVisibilityHandler",null);R(this,"isSessionNotOwned",!1);this.config={...g,environment:g.environment||"production"},this.connectionType=g.connectionType||e.ConnectionType.HTTP_STREAM;const f=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||f,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const g=await this.resourceManager.refreshBearer();if(!g)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(f){this.emitError(this.toConnectionError(f,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return g}async startSession(g){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,g=void 0),await this.resourceManager.ensureCredentials();const f=g?.session_id?g:await this.createNewSession();return await this.initializeConnection(f),this.setupEventHandlers(),f}catch(f){throw this.emitError(f),f}}async sendMessage({message:g,files:f,audio:b,tool_declined:m,tool_id:_,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:g,files:f,audio:b,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(w){this.emitError(w)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(g,f,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:g,feedback:f,feedbackReason:b});break}}async sendSessionFeedback(g,f){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!g?.length&&!f){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:g,npsBase5:f});break}}on(g,f){this.sdkEventEmitter.on(g,f)}off(g,f){this.sdkEventEmitter.off(g,f)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(g){return await this.resourceManager.getSessionMessages(g)}async callTool(g,f,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,g,f,b);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let _={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,_);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:g,onError:f}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:g,onError:f})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const g=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(g),g}}async getAgentConfig(){return this.resourceManager.getAgentConfig()}isConnected(){return this.connection?.isConnected()??!1}clearTokens(){this.resourceManager.clearTokens()}get voice(){return this._voice||(this._voice=new u.VoiceAgent(this.buildVoiceConfig(),this.resourceManager,async()=>(await this.resourceManager.exchangeInit(),{sessionId:(await this.resourceManager.createSession()).session_id,sessionToken:this.resourceManager.getSessToken()||""}))),this._voice}endSession(){this._voice?.destroy(),this._voice=null,this.closeConnection(),this.cleanup()}buildVoiceConfig(){return{offerUrl:`${this.config.serverUrl||(0,n.getConfig)(this.config.environment).BASE_API_URL}/med-assist/voice/offer`,handleRefresh:async()=>{await this.resourceManager.refreshTokens()}}}toClientError(g){if(g instanceof a.APIError){const f=g.reason??(g.status===401||g.status===403?c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:g.error?.msg||g.message,error:g.error,code:g.code,...f&&{reason:f},status:g.status,context:g.context}}return g instanceof a.SynapseError?{message:g.displayMessage||g.message,code:g.code,...g.reason&&{reason:g.reason},context:g.context}:g instanceof Error?{message:g.message}:{message:"An unexpected error occurred"}}emitError(g){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(g))}toSessionError(g,f,b,m){return(0,a.normalizeError)(g,a.SessionError,f,{context:b,hint:m})}async initializeConnection(g){if(this.closeConnection(),!g.session_id||!this.resourceManager.getSessToken())throw new a.SessionError("Session ID or sess token not found",{context:{stage:"initializeConnection"},hint:"Ensure the token exchange and session API completed successfully."});this.sessionConfig=g;const f=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?f.WEBSOCKET_URL:f.BASE_API_URL,_=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:_||m,auth:{sessionId:g.session_id,getToken:()=>this.resourceManager.getSessToken()||"",onUnauthorized:()=>this.resourceManager.refreshBearer()},agentId:this.config.agentId,userId:this.config.userId,overrides:this.config.overrides,...this.config.channel&&{channel:this.config.channel}}),this.connectionAttempts++,this.messageManager.setConnection(this.connection);const y=this.connection.emit.bind(this.connection);this.connection.emit=(k,...x)=>{y(k,...x),this.sdkEventEmitter.emit(k,...x)}}async createNewSession(){return await this.resourceManager.createSession(this.config.userId,this.config.context)}setupEventHandlers(){if(!this.connection)return;this.connection.onOpen(()=>{switch(this.connectionType){case e.ConnectionType.SOCKET:this.onSocketConnectionOpen();break;case e.ConnectionType.HTTP_STREAM:this.messageManager.handleConnectionEstablished();break}}),this.connection.onMessage(f=>{this.onIncomingSocketMessage(f)}),this.connection.onError(f=>{this.onRealtimeConnectionError(f)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const g=this.connection;this.connection.onDisconnect(async f=>{if(this.connection!==g||f.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(f.code);if(b){await this.handleRecovery(b,f);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(f)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(g){if(g instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(g.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:g.message,code:g.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,g);const f=g instanceof a.APIError?g:this.toConnectionError(g,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(f)}onSocketConnectionOpen(){const g=this.resourceManager.getSessToken();if(!g){const f=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(f),f}this.messageManager.sendSocketAuthMessage(g)}onIncomingSocketMessage(g){switch(g.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(g);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(g);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(g);break;case h.SOCKET_EVENTS.PING:this.messageManager.sendSocketPongMessage();break;case h.SOCKET_EVENTS.PONG:this.messageManager.sendSocketPingMessage();break;case h.SOCKET_EVENTS.SYNC:break;case h.SOCKET_EVENTS.ERROR:this.messageManager.handleIncomingSocketErrorMessage(g);break;default:const f=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:g.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(f);return}}get isAuthenticatedUser(){const g=this.resourceManager.getLevel();return g?g==="user":!!this.config.authToken}statusOf(g){if(g instanceof a.APIError)return g.status;if(g instanceof a.SynapseError&&typeof g.context?.status=="number")return g.context.status}emitRecoveryError(g,f,b){this.emitError(new a.SessionError(f,{reason:g,cause:b,context:{stage:"connectionRecovery",reason:g}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(g,f){if(g===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),f&&this.scheduleReconnect(f);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(g){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(g){const f=this.statusOf(g);if(f!==403&&f!==401){this.emitError(this.toSessionError(g,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",g)}}async recoverMissingSession(){const g=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!g){this.closeConnection(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const f=await this.resourceManager.reinitialiseSession(g);await this.connectTo(f);return}catch(f){const b=this.statusOf(f);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",f);return}try{await this.connectTo(await this.createNewSession())}catch(m){const _=this.statusOf(m);if(_===401||_===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(g){await this.initializeConnection(g),this.setupEventHandlers()}async handleAuthExpiry(){if(!(this.isRefreshingSession||this.isRecovering)){this.isRefreshingSession=!0,this.isRecovering=!0;try{await this.recoverExpiredCredentials()}finally{this.isRefreshingSession=!1,this.isRecovering=!1}}}async handleSessionInactiveMessage(){if(!this.isRecovering){this.isRecovering=!0;try{await this.recoverMissingSession()}finally{this.isRecovering=!1}}}toConnectionError(g,f,b,m){return(0,a.normalizeError)(g,a.ConnectionError,f,{context:b,hint:m})}scheduleReconnect(g){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(g);return}const f=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(g)}}},f)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return jn.SynapseSDK=p,jn}var Ra={},Aa;function nu(){return Aa||(Aa=1,Object.defineProperty(Ra,"__esModule",{value:!0})),Ra}var Fr={},Ia;function ru(){return Ia||(Ia=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.USER_FEEDBACK=void 0,Fr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Fr}var Ma={},Pa;function ou(){return Pa||(Pa=1,Object.defineProperty(Ma,"__esModule",{value:!0})),Ma}var ar={},Da;function su(){if(Da)return ar;Da=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.ToolCall=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return ar.ToolCall=t,ar}var Je={},La;function iu(){if(La)return Je;La=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.SYNAPSE_EICITATION_STATUS=Je.SYNAPSE_CTA_ACTIONS=Je.SYNAPSE_TOOL_FORMATS=Je.SYNAPSE_TOOL_CALLBACK_NAME=Je.SYNAPSE_COMPONENTS=Je.SYNAPSE_TOOL_NAME=void 0;var e;(function(s){s.MOBILE_VERIFICATION="mobile_verification",s.AVAILABILITY_DATES="availability_dates",s.AVAILABILITY_SLOTS="availability_slots",s.DOCTOR_AVAILABILITY="doctor_availability",s.DOCTOR_DETAILS="doctor_details",s.GET_LOCATION="get_location"})(e||(Je.SYNAPSE_TOOL_NAME=e={}));var t;(function(s){s.MOBILE="mobile_number",s.OTP="otp",s.EMAIL="email_address",s.PILL="pills",s.MULTI="multi",s.DOCTOR_CARD="doctor_card",s.CARD="card",s.MEDIA_CARD="media_card"})(t||(Je.SYNAPSE_COMPONENTS=t={}));var n;(function(s){s.DOCTOR_AVAILABILITY="get_doctor_availability",s.AVAILABILITY_DATES="get_available_dates",s.AVAILABILITY_SLOTS="get_available_slots",s.MOBILE_VERIFICATION="verify_mobile_number",s.DOCTOR_DETAILS="get_doctor_details"})(n||(Je.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Je.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Je.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Je.SYNAPSE_EICITATION_STATUS=i={})),Je}var Ua={},Fa;function au(){return Fa||(Fa=1,Object.defineProperty(Ua,"__esModule",{value:!0})),Ua}var Va={},ja;function lu(){return ja||(ja=1,Object.defineProperty(Va,"__esModule",{value:!0})),Va}var lr={},za;function cu(){if(za)return lr;za=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(lr.SYNAPSE_CONVERSATION=e={})),lr}var bn={},$a;function du(){return $a||($a=1,(function(e){var t=bn&&bn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=bn&&bn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(Ta(),e)})(bn)),bn}var Ya;function uu(){return Ya||(Ya=1,(function(e){var t=_n&&_n.__createBinding||(Object.create?(function(w,T,S,v){v===void 0&&(v=S);var C=Object.getOwnPropertyDescriptor(T,S);(!C||("get"in C?!T.__esModule:C.writable||C.configurable))&&(C={enumerable:!0,get:function(){return T[S]}}),Object.defineProperty(w,v,C)}):(function(w,T,S,v){v===void 0&&(v=S),w[v]=T[S]})),n=_n&&_n.__exportStar||function(w,T){for(var S in w)S!=="default"&&!Object.prototype.hasOwnProperty.call(T,S)&&t(T,w,S)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=tu();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Lo();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=$i();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Wi();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=qi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Hn(),e);var c=pa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(nu(),e);var d=ea();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(ru(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=da();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(ou(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var E=oa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var g=su();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return g.ToolCall}}),n(iu(),e);var f=va();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return f.MessageManager}}),n(Ur(),e),n(au(),e);var b=Lr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=it();Object.defineProperty(e,"SynapseError",{enumerable:!0,get:function(){return m.SynapseError}}),Object.defineProperty(e,"APIError",{enumerable:!0,get:function(){return m.APIError}}),Object.defineProperty(e,"APIUserAbortError",{enumerable:!0,get:function(){return m.APIUserAbortError}}),Object.defineProperty(e,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return m.APIConnectionTimeoutError}}),Object.defineProperty(e,"BadRequestError",{enumerable:!0,get:function(){return m.BadRequestError}}),Object.defineProperty(e,"UnauthorizedError",{enumerable:!0,get:function(){return m.UnauthorizedError}}),Object.defineProperty(e,"PermissionDeniedError",{enumerable:!0,get:function(){return m.PermissionDeniedError}}),Object.defineProperty(e,"NotFoundError",{enumerable:!0,get:function(){return m.NotFoundError}}),Object.defineProperty(e,"MethodNotAllowedError",{enumerable:!0,get:function(){return m.MethodNotAllowedError}}),Object.defineProperty(e,"RateLimitError",{enumerable:!0,get:function(){return m.RateLimitError}}),Object.defineProperty(e,"InternalServerError",{enumerable:!0,get:function(){return m.InternalServerError}}),Object.defineProperty(e,"SynapseErrorCode",{enumerable:!0,get:function(){return m.SynapseErrorCode}});var _=jo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return _.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return _.SYNAPSE_RECOVERY_REASON}});var y=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(lu(),e);var k=Bi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var x=Ur();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(cu(),e),n(du(),e)})(_n)),_n}var I=uu();function Ha(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=Ha(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ba(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ha(e))&&(r&&(r+=" "),r+=t);return r}const hu=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},mu=(e,t)=>({classGroupId:e,validator:t}),Ga=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Vr="-",Wa=[],pu="arbitrary..",fu=e=>{const t=_u(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return gu(o);const i=o.split(Vr),s=i[0]===""&&i.length>1?1:0;return Ka(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?hu(a,s):s:a||Wa}return n[o]||Wa}}},Ka=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=Ka(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(Vr):e.slice(t).join(Vr),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},gu=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?pu+r:void 0})(),_u=e=>{const{theme:t,classGroups:n}=e;return Eu(n,t)},Eu=(e,t)=>{const n=Ga();for(const r in e){const o=e[r];Yo(o,n,r,t)}return n},Yo=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];yu(s,t,n,r)}},yu=(e,t,n,r)=>{if(typeof e=="string"){Su(e,t,n);return}if(typeof e=="function"){bu(e,t,n,r);return}vu(e,t,n,r)},Su=(e,t,n)=>{const r=e===""?t:qa(t,e);r.classGroupId=n},bu=(e,t,n,r)=>{if(wu(e)){Yo(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(mu(n,e))},vu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];Yo(c,qa(t,a),n,r)}},qa=(e,t)=>{let n=e;const r=t.split(Vr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Ga(),n.nextPart.set(s,a)),n=a}return n},wu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Nu=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},Ho="!",Xa=":",Cu=[],Za=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),xu=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,c=0,d;const h=o.length;for(let f=0;f<h;f++){const b=o[f];if(s===0&&a===0){if(b===Xa){i.push(o.slice(c,f)),c=f+1;continue}if(b==="/"){d=f;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(c);let p=u,E=!1;u.endsWith(Ho)?(p=u.slice(0,-1),E=!0):u.startsWith(Ho)&&(p=u.slice(1),E=!0);const g=d&&d>c?d-c:void 0;return Za(i,E,p,g)};if(t){const o=t+Xa,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Za(Cu,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Tu=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",c=t.has(s);a||c?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},ku=e=>({cache:Nu(e.cacheSize),parseClassName:xu(e),sortModifiers:Tu(e),...fu(e)}),Ou=/\s+/,Ru=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Ou);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:E,baseClassName:g,maybePostfixModifierPosition:f}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let b=!!f,m=r(b?g.substring(0,f):g);if(!m){if(!b){c=h+(c.length>0?" "+c:c);continue}if(m=r(g),!m){c=h+(c.length>0?" "+c:c);continue}b=!1}const _=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=E?_+Ho:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,b);for(let w=0;w<x.length;++w){const T=x[w];s.push(y+T)}c=h+(c.length>0?" "+c:c)}return c},Au=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ja(n))&&(o&&(o+=" "),o+=r);return o},Ja=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ja(e[r]))&&(n&&(n+=" "),n+=t);return n},Iu=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=ku(d),r=n.cache.get,o=n.cache.set,i=a,a(c)},a=c=>{const d=r(c);if(d)return d;const h=Ru(c,n);return o(c,h),h};return i=s,(...c)=>i(Au(...c))},Mu=[],Ve=e=>{const t=n=>n[e]||Mu;return t.isThemeGetter=!0,t},Qa=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,el=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Pu=/^\d+\/\d+$/,Du=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Lu=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Uu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Fu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Vu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vn=e=>Pu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),$t=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Mt=e=>Du.test(e),ju=()=>!0,zu=e=>Lu.test(e)&&!Uu.test(e),tl=()=>!1,$u=e=>Fu.test(e),Yu=e=>Vu.test(e),Hu=e=>!$(e)&&!Y(e),Bu=e=>wn(e,il,tl),$=e=>Qa.test(e),Jt=e=>wn(e,al,zu),Go=e=>wn(e,Xu,ne),nl=e=>wn(e,ol,tl),Gu=e=>wn(e,sl,Yu),jr=e=>wn(e,ll,$u),Y=e=>el.test(e),cr=e=>Nn(e,al),Wu=e=>Nn(e,Zu),rl=e=>Nn(e,ol),Ku=e=>Nn(e,il),qu=e=>Nn(e,sl),zr=e=>Nn(e,ll,!0),wn=(e,t,n)=>{const r=Qa.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Nn=(e,t,n=!1)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n:!1},ol=e=>e==="position"||e==="percentage",sl=e=>e==="image"||e==="url",il=e=>e==="length"||e==="size"||e==="bg-size",al=e=>e==="length",Xu=e=>e==="number",Zu=e=>e==="family-name",ll=e=>e==="shadow",Ju=()=>{const e=Ve("color"),t=Ve("font"),n=Ve("text"),r=Ve("font-weight"),o=Ve("tracking"),i=Ve("leading"),s=Ve("breakpoint"),a=Ve("container"),c=Ve("spacing"),d=Ve("radius"),h=Ve("shadow"),u=Ve("inset-shadow"),p=Ve("text-shadow"),E=Ve("drop-shadow"),g=Ve("blur"),f=Ve("perspective"),b=Ve("aspect"),m=Ve("ease"),_=Ve("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),Y,$],w=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],S=()=>[Y,$,c],v=()=>[vn,"full","auto",...S()],C=()=>[$t,"none","subgrid",Y,$],L=()=>["auto",{span:["full",$t,Y,$]},$t,Y,$],X=()=>[$t,"auto",Y,$],G=()=>["auto","min","max","fr",Y,$],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...S()],_e=()=>[vn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],F=()=>[e,Y,$],le=()=>[...k(),rl,nl,{position:[Y,$]}],Re=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",Ku,Bu,{size:[Y,$]}],J=()=>[Bo,cr,Jt],A=()=>["","none","full",d,Y,$],B=()=>["",ne,cr,Jt],re=()=>["solid","dashed","dotted","double"],Se=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],W=()=>[ne,Bo,rl,nl],Ae=()=>["","none",g,Y,$],$e=()=>["none",ne,Y,$],ie=()=>["none",ne,Y,$],Pe=()=>[ne,Y,$],De=()=>[vn,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Mt],breakpoint:[Mt],color:[ju],container:[Mt],"drop-shadow":[Mt],ease:["in","out","in-out"],font:[Hu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Mt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Mt],shadow:[Mt],spacing:["px",ne],text:[Mt],"text-shadow":[Mt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",vn,$,Y,b]}],container:["container"],columns:[{columns:[ne,$,Y,a]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:x()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[$t,"auto",Y,$]}],basis:[{basis:[vn,"full","auto",a,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,vn,"auto","initial","none",$]}],grow:[{grow:["",ne,Y,$]}],shrink:[{shrink:["",ne,Y,$]}],order:[{order:[$t,"first","last","none",Y,$]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":X()}],"col-end":[{"col-end":X()}],"grid-rows":[{"grid-rows":C()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":X()}],"row-end":[{"row-end":X()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:_e()}],w:[{w:[a,"screen",..._e()]}],"min-w":[{"min-w":[a,"screen","none",..._e()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},..._e()]}],h:[{h:["screen","lh",..._e()]}],"min-h":[{"min-h":["screen","lh","none",..._e()]}],"max-h":[{"max-h":["screen","lh",..._e()]}],"font-size":[{text:["base",n,cr,Jt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,Y,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,$]}],"font-family":[{font:[Wu,$,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,Y,$]}],"line-clamp":[{"line-clamp":[ne,"none",Y,Go]}],leading:[{leading:[i,...S()]}],"list-image":[{"list-image":["none",Y,$]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Y,$]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",Y,Jt]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[ne,"auto",Y,$]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y,$]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Y,$]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Re()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},$t,Y,$],radial:["",Y,$],conic:[$t,Y,$]},qu,Gu]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:J()}],"gradient-via-pos":[{via:J()}],"gradient-to-pos":[{to:J()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:A()}],"rounded-s":[{"rounded-s":A()}],"rounded-e":[{"rounded-e":A()}],"rounded-t":[{"rounded-t":A()}],"rounded-r":[{"rounded-r":A()}],"rounded-b":[{"rounded-b":A()}],"rounded-l":[{"rounded-l":A()}],"rounded-ss":[{"rounded-ss":A()}],"rounded-se":[{"rounded-se":A()}],"rounded-ee":[{"rounded-ee":A()}],"rounded-es":[{"rounded-es":A()}],"rounded-tl":[{"rounded-tl":A()}],"rounded-tr":[{"rounded-tr":A()}],"rounded-br":[{"rounded-br":A()}],"rounded-bl":[{"rounded-bl":A()}],"border-w":[{border:B()}],"border-w-x":[{"border-x":B()}],"border-w-y":[{"border-y":B()}],"border-w-s":[{"border-s":B()}],"border-w-e":[{"border-e":B()}],"border-w-t":[{"border-t":B()}],"border-w-r":[{"border-r":B()}],"border-w-b":[{"border-b":B()}],"border-w-l":[{"border-l":B()}],"divide-x":[{"divide-x":B()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":B()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,Y,$]}],"outline-w":[{outline:["",ne,cr,Jt]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",h,zr,jr]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",u,zr,jr]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[ne,Jt]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":B()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",p,zr,jr]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[ne,Y,$]}],"mix-blend":[{"mix-blend":[...Se(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Se()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":W()}],"mask-image-linear-to-pos":[{"mask-linear-to":W()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":W()}],"mask-image-t-to-pos":[{"mask-t-to":W()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":W()}],"mask-image-r-to-pos":[{"mask-r-to":W()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":W()}],"mask-image-b-to-pos":[{"mask-b-to":W()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":W()}],"mask-image-l-to-pos":[{"mask-l-to":W()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":W()}],"mask-image-x-to-pos":[{"mask-x-to":W()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":W()}],"mask-image-y-to-pos":[{"mask-y-to":W()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Y,$]}],"mask-image-radial-from-pos":[{"mask-radial-from":W()}],"mask-image-radial-to-pos":[{"mask-radial-to":W()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":W()}],"mask-image-conic-to-pos":[{"mask-conic-to":W()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Re()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Y,$]}],filter:[{filter:["","none",Y,$]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,Y,$]}],contrast:[{contrast:[ne,Y,$]}],"drop-shadow":[{"drop-shadow":["","none",E,zr,jr]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",ne,Y,$]}],"hue-rotate":[{"hue-rotate":[ne,Y,$]}],invert:[{invert:["",ne,Y,$]}],saturate:[{saturate:[ne,Y,$]}],sepia:[{sepia:["",ne,Y,$]}],"backdrop-filter":[{"backdrop-filter":["","none",Y,$]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,Y,$]}],"backdrop-contrast":[{"backdrop-contrast":[ne,Y,$]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,Y,$]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,Y,$]}],"backdrop-invert":[{"backdrop-invert":["",ne,Y,$]}],"backdrop-opacity":[{"backdrop-opacity":[ne,Y,$]}],"backdrop-saturate":[{"backdrop-saturate":[ne,Y,$]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,Y,$]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Y,$]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",Y,$]}],ease:[{ease:["linear","initial",m,Y,$]}],delay:[{delay:[ne,Y,$]}],animate:[{animate:["none",_,Y,$]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,Y,$]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:$e()}],"rotate-x":[{"rotate-x":$e()}],"rotate-y":[{"rotate-y":$e()}],"rotate-z":[{"rotate-z":$e()}],scale:[{scale:ie()}],"scale-x":[{"scale-x":ie()}],"scale-y":[{"scale-y":ie()}],"scale-z":[{"scale-z":ie()}],"scale-3d":["scale-3d"],skew:[{skew:Pe()}],"skew-x":[{"skew-x":Pe()}],"skew-y":[{"skew-y":Pe()}],transform:[{transform:[Y,$,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Y,$]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Y,$]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[ne,cr,Jt,Go]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Qu=Iu(Ju);function U(...e){return Qu(Ba(e))}function Qt(e){if(!e&&e!==0)return"";const t=e instanceof Date?e:new Date(typeof e=="number"?e:Number(e)||e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}const eh=e=>{switch(e){case I.SYNAPSE_COMPONENTS.DOCTOR_CARD:case I.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},th=e=>new Promise(t=>setTimeout(t,e)),cl=ee(({className:e,children:t,...n},r)=>l(Pi,{ref:r,className:U("relative overflow-hidden",e),...n,children:[l(Bd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(dl,{}),l(Gd,{})]}));cl.displayName=Pi.displayName;const dl=ee(({className:e,orientation:t="vertical",...n},r)=>l(Io,{ref:r,orientation:t,className:U("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:l(ki,{className:"relative flex-1 rounded-full bg-border"})}));dl.displayName=Io.displayName;var nh=Symbol.for("react.lazy"),$r=Oo[" use ".trim().toString()];function rh(e){return typeof e=="object"&&e!==null&&"then"in e}function ul(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===nh&&"_payload"in e&&rh(e._payload)}function hl(e){const t=sh(e),n=ee((r,o)=>{let{children:i,...s}=r;ul(i)&&typeof $r=="function"&&(i=$r(i._payload));const a=ot.toArray(i),c=a.find(ah);if(c){const d=c.props.children,h=a.map(u=>u===c?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:st(d)?Ft(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var oh=hl("Slot");function sh(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(ul(o)&&typeof $r=="function"&&(o=$r(o._payload)),st(o)){const s=ch(o),a=lh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ih=Symbol("radix.slottable");function ah(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ih}function lh(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function ch(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const ml=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,pl=Ba,dh=(e,t)=>n=>{var r;if(t?.variants==null)return pl(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n?.[d],u=i?.[d];if(h===null)return null;const p=ml(h)||ml(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,...E}=h;return Object.entries(E).every(g=>{let[f,b]=g;return Array.isArray(b)?b.includes({...i,...a}[f]):{...i,...a}[f]===b})?[...d,u,p]:d},[]);return pl(e,s,c,n?.class,n?.className)},uh=dh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Ee=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?oh:"button",{className:U(uh({variant:t,size:n,className:e})),ref:i,...o}));Ee.displayName="Button";const hh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),mh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),fl=e=>{const t=mh(e);return t.charAt(0).toUpperCase()+t.slice(1)},gl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),ph=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const gh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>et("svg",{ref:c,...fh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:gl("lucide",o),...!i&&!ph(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>et(d,h)),...Array.isArray(i)?i:[i]])),ze=(e,t)=>{const n=ee(({className:r,...o},i)=>et(gh,{ref:i,iconNode:t,className:gl(`lucide-${hh(fl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=fl(e),n},_h=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=ze("chevron-down",_h),Eh=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],yh=ze("ellipsis-vertical",Eh),Sh=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],_l=ze("file-text",Sh),bh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],El=ze("info",bh),vh=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],wh=ze("maximize-2",vh),Nh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Ch=ze("menu",Nh),xh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],dr=ze("message-square-plus",xh),Th=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Ko=ze("mic",Th),kh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Oh=ze("minimize-2",kh),Rh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yl=ze("plus",Rh),Ah=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Ih=ze("rotate-ccw",Ah),Mh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Sl=ze("square",Mh),Ph=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],bl=ze("thumbs-up",Ph),Dh=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],vl=ze("thumbs-down",Dh),Lh=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Uh=ze("triangle-alert",Lh),Fh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Cn=ze("x",Fh),Vh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],jh=ze("zoom-in",Vh),wl=e=>{let t;const n=new Set,r=(a,c)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=c??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},zh=(e=>e?wl(e):wl),$h=e=>e;function Yh(e,t=$h){const n=Vn.useSyncExternalStore(e.subscribe,Vn.useCallback(()=>t(e.getState()),[e,t]),Vn.useCallback(()=>t(e.getInitialState()),[e,t]));return Vn.useDebugValue(n),n}const Hh=e=>{const t=zh(e),n=r=>Yh(t,r);return Object.assign(n,t),n},Bh=(e=>Hh);function Gh(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var o;const i=a=>a===null?null:JSON.parse(a,void 0),s=(o=n.getItem(r))!=null?o:null;return s instanceof Promise?s.then(i):i(s)},setItem:(r,o)=>n.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>n.removeItem(r)}}const qo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qo(r)(n)}}}},Wh=(e,t)=>(n,r,o)=>{let i={storage:Gh(()=>localStorage),partialize:f=>f,version:0,merge:(f,b)=>({...b,...f}),...t},s=!1;const a=new Set,c=new Set;let d=i.storage;if(!d)return e((...f)=>{n(...f)},r,o);const h=()=>{const f=i.partialize({...r()});return d.setItem(i.name,{state:f,version:i.version})},u=o.setState;o.setState=(f,b)=>(u(f,b),h());const p=e((...f)=>(n(...f),h()),r,o);o.getInitialState=()=>p;let E;const g=()=>{var f,b;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:p)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(f=r())!=null?f:p))||void 0;return qo(d.getItem.bind(d))(i.name).then(_=>{if(_)if(typeof _.version=="number"&&_.version!==i.version){if(i.migrate){const y=i.migrate(_.state,_.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[k,x]=_;if(E=i.merge(x,(y=r())!=null?y:p),n(E,!0),k)return h()}).then(()=>{m?.(E,void 0),E=r(),s=!0,c.forEach(_=>_(E))}).catch(_=>{m?.(void 0,_)})};return o.persist={setOptions:f=>{i={...i,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>s,onHydrate:f=>(a.add(f),()=>{a.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},i.skipHydration||g(),E||p},Kh=Wh,Ne={USER:"user",ASSISTANT:"assistant"};var ye=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(ye||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let dt="";const ur=e=>`med-assist-store-${e}`,qh=e=>{xn(),dt=ur(e)},Xh=200;let ft=null,hr=null;function xn(){if(hr&&(clearTimeout(hr),hr=null),!!ft){try{sessionStorage.setItem(ft.key,JSON.stringify(ft.value))}catch{}ft=null}}typeof window<"u"&&(window.addEventListener("pagehide",xn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&xn()}));const Zh={getItem:()=>{if(!dt)return null;if(ft?.key===dt)return ft.value;try{const e=sessionStorage.getItem(dt);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{dt&&(ft&&ft.key!==dt&&xn(),ft={key:dt,value:t},hr||(hr=setTimeout(xn,Xh)))},removeItem:()=>{ft?.key===dt&&(ft=null),dt&&sessionStorage.removeItem(dt)}},Nl={sessionId:"",isStreaming:!1,recordingStatus:ye.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:ge.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},Cl={...Nl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=Bh()(Kh((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:ge.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:ye.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),isMobile:!1,setIsMobile:n=>e({isMobile:n}),displayMode:"widget",setDisplayMode:n=>e({displayMode:n}),toggleDisplayMode:()=>e({displayMode:t().displayMode==="full"?"widget":"full"}),initialDisplayMode:"widget",setInitialDisplayMode:n=>e({initialDisplayMode:n}),chats:{},addMessageToSession:(n,r)=>{e(o=>({chats:{...o.chats,[n]:[...o.chats[n]||[],r]}}))},updateMessageInSession:(n,r,o)=>e(i=>({chats:{...i.chats,[n]:(i.chats[n]||[]).map(s=>s.id===r?{...s,...o}:s)}})),getMessagesForSession:n=>t().chats[n]||[],setMessagesForSession:(n,r)=>e(o=>({chats:{...o.chats,[n]:r}})),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),clearSession:async()=>{e(Nl),await sessionStorage.removeItem(dt||ur(t().agentId))},clearUser:()=>{e(Cl),sessionStorage.removeItem(dt||ur(t().agentId))}}),{name:"med-assist-store",storage:Zh,partialize:e=>({agentId:e.agentId,userId:e.userId,context:e.context,chats:e.chats,sessionId:e.sessionId,refreshToken:e.refreshToken,sessToken:e.sessToken,level:e.level,initialMessage:e.initialMessage,sessionInitialMessages:e.sessionInitialMessages,connectionStatus:e.connectionStatus,elicitationState:e.elicitationState})})),Jh=e=>{const t=ur(e);xn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(Cl),n&&j.setState(n)},Xo=bt(null),Qh=({children:e})=>{const[t,n]=V(null);return l(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},em=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},tm=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},nm=()=>{const[e,t]=V(I.VOICE_AGENT_STATE.IDLE),[n,r]=V(!1),o=em(),i=j(h=>h.setError);H(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},p=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(I.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(I.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=de(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=de(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),c=de(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=de(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:c,toggleMute:d}},en=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));en.displayName="Card";const xl=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("flex flex-col space-y-1.5 p-6",e),...t}));xl.displayName="CardHeader";const Tl=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("font-semibold leading-none tracking-tight",e),...t}));Tl.displayName="CardTitle";const rm=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("text-sm text-muted-foreground",e),...t}));rm.displayName="CardDescription";const kl=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("p-6 pt-0",e),...t}));kl.displayName="CardContent";const Ol=ee(({className:e,...t},n)=>l("div",{ref:n,className:U("flex items-center p-6 pt-0",e),...t}));Ol.displayName="CardFooter";const Zo=5,Rl=3,Al=10*1024*1024,Yr={width:384,height:600},Hr=20,om=400,sm=320,im=560,am=150;function lm({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=de(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Yr.width-Hr,y:window.innerHeight-Yr.height-Hr},[]),[i,s]=V(()=>e??o()),[a,c]=V(!1),d=q({x:0,y:0}),h=q(null),u=q(!1);H(()=>{t||(u.current=!1)},[t]),mt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),H(()=>{if(!t||typeof window>"u")return;let f=null;const b=()=>{s(_=>{const y=Math.max(0,window.innerWidth-Yr.width-Hr),k=Math.max(0,window.innerHeight-Yr.height-Hr),x=Math.max(0,Math.min(_.x,y)),w=Math.max(0,Math.min(_.y,k));return x===_.x&&w===_.y?_:{x,y:w}})},m=()=>{f!==null&&clearTimeout(f),f=setTimeout(b,am)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),f!==null&&clearTimeout(f)}},[t]);const p=de(f=>{if(!t)return;if(!f.target.closest(".synapse-chat-widget-header")){c(!1);return}f.preventDefault(),c(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:f.clientX-m.left,y:f.clientY-m.top}}else d.current={x:f.clientX-i.x,y:f.clientY-i.y};n?.()},[t,i.x,i.y,n]),E=de(f=>{if(!t||!a)return;const b=f.clientX-d.current.x,m=f.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(b,_)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[a,t]),g=de(()=>{!t||!a||(c(!1),r?.())},[a,r]);return H(()=>{if(!t)return;const f=h.current;if(f)return f.addEventListener("mousedown",p),()=>{f.removeEventListener("mousedown",p)}},[t,p]),H(()=>{if(a)return document.addEventListener("mousemove",E),document.addEventListener("mouseup",g),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",g),document.body.style.cursor="",document.body.style.userSelect=""}},[a,E,g]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Jo="#6B5CE0",cm="#F0F0F0",Br={background:cm,backgroundImage:void 0,primary:Jo,textColor:"black"},dm="rgba(0, 0, 0, 0.4)",um="24px";function hm(e){if(e==="dark")return"white";if(e==="light")return"black"}function mm(e){const t=e?.primary??e?.primaryColor??Br.primary,n=e?.textColor??hm(e?.mode);return{background:e?.background??Br.background,backgroundImage:e?.backgroundImage??Br.backgroundImage,primary:t,primaryColor:t,textColor:n??Br.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function pm(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const c=(o+i)/2;if(o!==i){const h=o-i;switch(a=c>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(c*100);return`${s} ${a}% ${d}%`}function fm(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,c=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(c=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),c=Math.round(c*100);const h=Math.round(d*100);return`${a} ${c}% ${h}%`}function gm(e){const t=e.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(!t)throw new Error("Invalid HSL format");return`${t[1]} ${t[2]}% ${t[3]}%`}function Qo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return pm(t);if(t.startsWith("rgb"))return fm(t);if(t.startsWith("hsl"))return gm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Il(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Il(e)>.5?"0 0% 9%":"0 0% 98%"}function _m(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return"0 0% 96%";const n=t[1],r=Math.max(0,parseInt(t[2],10)-5);return`${n} ${r}% 96%`}function Em(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return{50:"262 83% 98%",100:"262 83% 96%",200:"262 83% 92%",300:"262 83% 85%",400:"262 83% 75%",500:"262 83% 58%",600:"262 83% 50%",700:"262 83% 40%",800:"262 83% 30%",900:"262 83% 20%"};const n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);return{50:`${n} ${Math.max(0,r-20)}% ${Math.min(98,o+40)}%`,100:`${n} ${Math.max(0,r-15)}% ${Math.min(96,o+35)}%`,200:`${n} ${Math.max(0,r-10)}% ${Math.min(92,o+30)}%`,300:`${n} ${Math.max(0,r-5)}% ${Math.min(85,o+20)}%`,400:`${n} ${r}% ${Math.min(75,o+10)}%`,500:`${n} ${r}% ${o}%`,600:`${n} ${Math.min(100,r+5)}% ${Math.max(50,o-10)}%`,700:`${n} ${Math.min(100,r+10)}% ${Math.max(40,o-20)}%`,800:`${n} ${Math.min(100,r+15)}% ${Math.max(30,o-30)}%`,900:`${n} ${Math.min(100,r+20)}% ${Math.max(20,o-40)}%`}}function Ml(e,t){const n=t.primary??Jo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,g)=>{const f=e instanceof ShadowRoot?e.host:e;f instanceof HTMLElement&&f.style.setProperty(E,g)};let c;try{c=Qo(n)}catch{c=Qo(Jo)}a("--primary",c),a("--primary-foreground",es(c)),a("--ring",c),a("--border-primary",c);const d=Em(c);for(const[E,g]of Object.entries(d))a(`--primary-${E}`,g);const h=es(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const E=i?"#191919":"#F0F0F0";try{a("--background",Qo(E))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${c} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",_m(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${c})`),a("--header-stroke",`hsl(${c} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${c} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${c} / 0.3)`)),s&&!o){const E=Il(h)>.5;a("--header-tagline",E?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",c):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${p}-${E})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",c),a("--accent-foreground",es(c)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",um),a("--theme-background-overlay",dm),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function tn({className:e,style:t}){return l("div",{className:U("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function ts(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Pl(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(ts,{}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[l("div",{className:"px-2 pt-2 pb-1",children:l(tn,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(tn,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(tn,{className:"h-9 w-9 rounded-full"}),l(tn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function ym(){const e=[{role:Ne.ASSISTANT,size:"h-16 w-[70%]"},{role:Ne.USER,size:"h-9 w-[45%]"},{role:Ne.ASSISTANT,size:"h-24 w-[75%]"},{role:Ne.USER,size:"h-9 w-[35%]"},{role:Ne.ASSISTANT,size:"h-16 w-[65%]"}];return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(ts,{}),e.map((t,n)=>l("div",{className:U("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:l(tn,{className:U("rounded-lg",t.size)})},n))]})}function Sm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return l("div",{"aria-hidden":"true",children:[l(ts,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(tn,{className:U("h-5 rounded-md",t[r%t.length])}),l(tn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function bm(e,t=[]){let n=[];function r(i,s){const a=bt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[c]||a,b=ae(()=>g,Object.values(g));return l(f.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[c]||a,g=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,vm(o,...t)]}function vm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var wm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=wm.reduce((e,t)=>{const n=hl(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Dl={exports:{}},rs={};const Nm=Wd(Oo);var Ll;function Cm(){if(Ll)return rs;Ll=1;var e=Nm;function t(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,p){var E=p(),g=r({inst:{value:E,getSnapshot:p}}),f=g[0].inst,b=g[1];return i(function(){f.value=E,f.getSnapshot=p,c(f)&&b({inst:f})},[u,E,p]),o(function(){return c(f)&&b({inst:f}),u(function(){c(f)&&b({inst:f})})},[u]),s(E),E}function c(u){var p=u.getSnapshot;u=u.value;try{var E=p();return!n(u,E)}catch{return!0}}function d(u,p){return p()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return rs.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,rs}var Ul;function xm(){return Ul||(Ul=1,Dl.exports=Cm()),Dl.exports}var Tm=xm();function km(){return Tm.useSyncExternalStore(Om,()=>!0,()=>!1)}function Om(){return()=>{}}var os="Avatar",[Rm]=bm(os),[Am,Fl]=Rm(os),Vl=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=V("idle");return l(Am,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(ns.span,{...r,ref:t})})});Vl.displayName=os;var jl="AvatarImage",zl=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Fl(jl,n),a=Im(r,i),c=jt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Zt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(ns.img,{...i,ref:t,src:r}):null});zl.displayName=jl;var $l="AvatarFallback",Yl=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Fl($l,n),[s,a]=V(r===void 0);return H(()=>{if(r!==void 0){const c=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(c)}},[r]),s&&i.imageLoadingStatus!=="loaded"?l(ns.span,{...o,ref:t}):null});Yl.displayName=$l;function Hl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Im(e,{referrerPolicy:t,crossOrigin:n}){const r=km(),o=q(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=V(()=>Hl(i,e));return Zt(()=>{a(Hl(i,e))},[i,e]),Zt(()=>{const c=u=>()=>{a(u)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Bl=Vl,Gl=zl,Wl=Yl;const ss=ee(({className:e,...t},n)=>l(Bl,{ref:n,className:U("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Bl.displayName;const Kl=ee(({className:e,...t},n)=>l(Gl,{ref:n,className:U("aspect-square h-full w-full",e),...t}));Kl.displayName=Gl.displayName;const is=ee(({className:e,...t},n)=>l(Wl,{ref:n,className:U("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Wl.displayName;const ql=bt(!1);function Mm({enabled:e,children:t}){return l(ql.Provider,{value:e,children:t})}function Pm(){return vt(ql)}const Xl="(max-width: 768px), (pointer: coarse)",Zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Dm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Xl)?.matches??!1,t=Zl.test(navigator?.userAgent??"");return e||t}function Jl(){const[e,t]=V(Dm);return H(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Xl),r=Zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Lm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:c=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Jl(),p=Pm(),E=j(C=>C.displayMode)==="side_panel",g=p&&!u&&!E,f=j(C=>C.displayMode)==="full",b=j(C=>C.initialDisplayMode)==="full",m=!f&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",_=j(C=>C.connectionStatus),y=j(C=>C.level)==="user",[k,x]=V(!1),w=q(null),T=ae(()=>a===I.VOICE_AGENT_STATE.CONNECTED||a===I.VOICE_AGENT_STATE.CONNECTING||a===I.VOICE_AGENT_STATE.LISTENING||a===I.VOICE_AGENT_STATE.SPEAKING||a===I.VOICE_AGENT_STATE.THINKING,[a]),S=de(()=>{k||(x(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,x(!1)},6e3),s())},[k,s]);H(()=>{_===ge.CONNECTED&&(x(!1),w.current&&clearTimeout(w.current))},[_]);const v=(()=>{switch(_){case ge.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case ge.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case ge.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return l("div",{className:"px-6 py-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative flex-shrink-0",children:[l(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?l("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):l("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),l("div",{className:U("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,_===ge.CONNECTING&&"animate-pulse")})]}),l("div",{className:"flex flex-col",children:[r?l("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):l("p",{className:U("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",m),children:n||"Health Assist"}),l("div",{className:"flex items-center gap-1.5",children:l("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),l("div",{className:U("flex items-center",!g&&"gap-1"),children:[!T&&!y&&l(Ee,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:S,disabled:k,className:U("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",m),children:l(dr,{className:"w-5 h-5"})}),h&&y&&l(Ee,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:U("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:l(yh,{className:"w-5 h-5"})}),g&&l(Ee,{onClick:d,type:"button",variant:"ghost",size:"icon",title:f?"Exit fullscreen":"Enter fullscreen",className:U("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:f?l(Oh,{className:"w-8 h-8"}):l(wh,{className:"w-8 h-8"})}),(t||!b)&&l(Ee,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:U("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:l(Cn,{className:"w-8 h-8"})})]})]})})}const as=ee(({className:e,...t},n)=>l("textarea",{className:U("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:n,...t}));as.displayName="Textarea";function Ql({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=V(!1),[s,a]=V(""),c=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";H(()=>{if(c){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,c]),H(()=>{i(!1)},[e]);const h=()=>c?"text-green-600":"text-text-secondary",u=p=>{if(p===0)return"0 B";const E=1024,g=["B","KB","MB","GB"],f=Math.floor(Math.log(p)/Math.log(E));return`${(p/Math.pow(E,f)).toFixed(1)} ${g[f]}`.toLowerCase()};return!c||o?l("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[l("div",{className:`flex-shrink-0 ${h()}`,children:l(_l,{className:"h-5 w-5"})}),l("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&l("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&l("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:l(Cn,{className:"h-3 w-3"})})]}):l("div",{className:`relative group flex-shrink-0 ${r}`,children:[l("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&l("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:l(Cn,{className:"h-3 w-3"})})]})}function ls({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return l("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return l(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&l("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return l(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),ec=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Um=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},tc=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),Fm=tt(()=>ec().then(e=>({default:e.ElicitationInput})));function Vm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:c,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:E,allowed:g,showStartNewChatButton:f,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:x,showAttention:w}){const T=q(null),S=q(null),v=w?l("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,C=e.trim().length>0||a,L=!g||g.includes(I.SYNAPSE_CONVERSATION.AUDIO),X=!g||g.includes(I.SYNAPSE_CONVERSATION.VOICE),G=C||!L,he=C,pe=!g||g.includes(I.SYNAPSE_CONVERSATION.FILE),se=(d||p!==ye.IDLE)&&!s,_e=U("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":se?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),F=A=>{const B=Array.from(A.target.files||[]);B.length>0&&r(B)},le=()=>{d||(T.current&&(T.current.value=""),T.current?.click())},Re=A=>{A.key==="Enter"&&!A.shiftKey&&he&&!d&&(A.preventDefault(),n())},te=A=>{A.style.height="auto",A.style.overflow="hidden";const B=A.scrollHeight,re=x?20:28,Se=120,W=Math.max(re,Math.min(B,Se));A.style.height=W+"px",B>Se?A.style.overflow="auto":A.style.overflow="hidden"},J=A=>{te(A.currentTarget)};return H(()=>{S.current&&te(S.current)},[e]),H(()=>{d||S.current?.focus()},[d]),f&&b?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:b,className:U("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[l("span",{children:"Start new chat"}),l(dr,{className:"w-5 h-5","aria-hidden":!0})]})}):l(me,{children:y?l(Ze,{fallback:l(Pl,{}),children:l(Fm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):x?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ls,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:T,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:l(as,{ref:S,onInput:J,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:U("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),l("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[l("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:pe&&p===ye.IDLE&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:U("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(yl,{className:"w-6 h-6",strokeWidth:1.5})})}),l("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className:U("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(Sl,{className:"w-4 h-4"})}):L&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:U("h-10 w-10 shrink-0 p-2",_e),title:"Start recording","aria-label":"Start recording",children:l(Ko,{className:"w-6 h-6",strokeWidth:1.5})}),G&&!s?l(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:U("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:l(cs,{className:"w-4 h-4 text-primary-foreground"})}):L&&X&&!s&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:T,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ls,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(as,{ref:S,onInput:J,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:U("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center shrink-0",children:pe&&p===ye.IDLE&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:U("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(yl,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className:U("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(Sl,{className:"w-4 h-4"})}):G?l(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:U("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:l(cs,{className:"w-4 h-4 text-primary-foreground"})}):L&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:U("h-10 w-10 shrink-0",_e),title:"Start recording","aria-label":"Start recording",children:l(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),L&&X&&!s&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const jm=Xt(Vm),nc=bt(null),rc=nc.Provider;function zm(){const e=vt(nc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function $m({message:e,onDismiss:t}){return l(me,{children:[l("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),l("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:l("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[l("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),l("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:l(Cn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Ym(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=de(()=>{t(null)},[t]);return H(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l($m,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?l("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:l("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Hm="Before we begin",Bm=e=>`A quick note on how ${e} works and handles your information.`,Gm=e=>[`This assistant is powered by AI. Replies are generated automatically and can be wrong, so please check anything important before you act on it. Don't use it in an urgent or emergency situation \u2014 contact ${e} directly or call your local emergency number.`,`To help you, ${e} and our authorised technology partners process what you share here \u2014 your contact details and your messages \u2014 under contractual and security safeguards, on secure servers. We use it only to provide this service, and keep it only as long as needed or as the law requires.`];function Wm(e,t){return(Array.isArray(e)?e:e.split(/\n\s*\n|\n/)).map(n=>String(n??"").replace(/\{\{\s*name\s*\}\}/gi,t).trim()).filter(Boolean)}const oc=(e,t)=>{if(t){const n=Wm(t,e);if(n.length)return n}return Gm(e)},Km="I agree and consent",qm="By continuing, you consent to the above.",Xm="Continue";function sc({botName:e,consentContent:t,isFullScreen:n}){return l(me,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:U("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Hm}),l("p",{className:U("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Bm(e)})]}),l("div",{className:U("overflow-y-auto rounded-lg border border-border-subtle flex flex-col",n?"max-h-[340px] p-4 gap-4":"max-h-[180px] p-3 gap-3"),tabIndex:0,role:"region","aria-label":"Consent details",children:oc(e,t).map((r,o)=>l("p",{className:U("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function Zm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(ds,{isOpen:e,onClose:t,children:l("div",{className:U("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?l(sc,{botName:n,consentContent:o,isFullScreen:s}):l("div",{className:"flex flex-col gap-2",children:[l("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),oc(n,o).map((a,c)=>l("p",{className:U("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(Ee,{onClick:t,className:U("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Jm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=V(!1);return e?l(ds,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:U("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[l(sc,{botName:t,consentContent:n,isFullScreen:o}),l("div",{className:"flex flex-col gap-1.5",children:[l("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[l("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),l("div",{"aria-hidden":"true",className:U("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&l("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:U("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Km})]}),l("p",{className:U("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:qm})]}),l(Ee,{disabled:!i,onClick:()=>i&&r(),className:U("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Xm})]})}):null}const Qm=tt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),ep=tt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),tp=tt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),np=tt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),rp=tt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),op=[{label:"Took longer than expected",value:"took_longer"},{label:"Asking too many questions",value:"too_many_questions"},{label:"Irrelevant response",value:"irrelevant_response"},{label:"Other",value:"other"}],sp=[{Icon:Qm,label:"Bad",score:1},{Icon:ep,label:"Poor",score:2},{Icon:tp,label:"Okay",score:3},{Icon:np,label:"Good",score:4},{Icon:rp,label:"Great!",score:5}];function ip(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function ap({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=V(null),[d,h]=V(new Set),[u,p]=V(!1),E=s&&a!==null?ip(a,t):t.form?.default?.length?t.form.default:op,g=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},f=_=>{c(_),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(ds,{isOpen:e,onClose:o,children:l("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[l("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),l("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[l("div",{className:"flex flex-col gap-1",children:[t.title&&l("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&l("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&l("div",{className:"flex items-center justify-between gap-1",children:sp.map(({Icon:_,label:y,score:k})=>{const x=a===k,w=a!==null&&!x;return l("button",{onClick:()=>f(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[l("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${w?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:l(Ze,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(_,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${x?"text-primary/50 font-medium":w?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&E.length>0&&l("div",{className:"flex flex-col gap-2",children:E.map(_=>l("div",{onClick:()=>g(_.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(_.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:_.label},_.value))}),l(Ee,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),l("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>p(_=>!_),children:[l("div",{className:"relative w-3 h-3 shrink-0",children:l("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&l("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),l("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function ic({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:c,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:E,activeElicitation:g,voiceAgentState:f,theme:b,feedbackModal:m,consentModal:_}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:w,tagline:T,iconUrl:S,onStartNewSession:v,showStartNewChatButton:C,onToggleDisplayMode:L,onOpenSessionDrawer:X}=zm(),[G,he]=V(!1),[pe,se]=V(!1),[_e,F]=V(!1),le=q(null),Re=j(z=>z.level),te=c,J=te==="full",A=te==="side_panel",B=q(null),[re,Se]=V("");H(()=>{B.current!==null&&B.current!==te&&Se(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),B.current=te},[te]);const W=ae(()=>mm(b),[b]),Ae=j(z=>z.setIsMobile),$e=!!E,ie=de(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);mt(()=>{if(!le.current)return;const z=te==="full"?{...W,headerTinted:!1}:W;Ml(le.current,z),te==="full"&&!W.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),Ml(le.current,W))},[W,te]),H(()=>{const z=()=>{const Ie=window?.innerWidth??0,be=navigator?.userAgent?.toLowerCase()??"",Le=Ie<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(be);he(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),mt(()=>{if(!e||!G||!le.current)return;const z=le.current;let Ie=null,be=null,Le=null,qe=window.visualViewport?.offsetTop??0,Ue=0;const gt=2,ut=80;if(window.visualViewport){const je=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,Te=window.visualViewport.offsetTop;Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Te}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Ge}px`,z.style.maxHeight=`${Ge}px`,z.style.minHeight=`${Ge}px`,be&&clearTimeout(be),be=setTimeout(()=>{z.style.transition=""},100)})}},nt=()=>{je()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,Te=Date.now();Math.abs(Ge-qe)<gt||Te-Ue<ut||(Ue=Te,qe=Ge,Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",nt),window.visualViewport.addEventListener("scroll",Be),je(),()=>{Ie&&cancelAnimationFrame(Ie),be&&clearTimeout(be),Le&&clearTimeout(Le),window.visualViewport?.removeEventListener("resize",nt),window.visualViewport?.removeEventListener("scroll",Be),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const je=()=>{z&&(z.style.transition="none",z.style.top="0",z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height="100svh",z.style.maxHeight="100svh",setTimeout(()=>{z.style.transition=""},100))};return window.addEventListener("resize",je),je(),()=>{window.removeEventListener("resize",je),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),H(()=>{if(e&&!(A&&d==="push")){const z=le.current,Ie=window.scrollY,be=document.body.style.cssText,Le=document.documentElement.style.overflow,qe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ie}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",qe>0&&!G&&(document.body.style.paddingRight=`${qe}px`);let Ue=0;const gt=je=>{Ue=je.touches[0].clientY},ut=je=>{if(je.touches.length!==1)return;const nt=Ue-je.touches[0].clientY;Ue=je.touches[0].clientY;let Be=je.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:Te,scrollHeight:Bt,clientHeight:_t}=Be,an=Te<=0&&nt<0,ln=Te+_t>=Bt-1&&nt>0;if(!an&&!ln)return;break}Be=Be.parentElement}je.preventDefault()};return z&&(z.addEventListener("touchstart",gt,{passive:!0}),z.addEventListener("touchmove",ut,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",gt),z.removeEventListener("touchmove",ut)),document.body.style.cssText=be,document.documentElement.style.overflow=Le,window.scrollTo(0,Ie)}}},[e,G,A,d]),H(()=>{if(!(!A||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,A,d,h,u,p]);const{position:Pe,elementRef:De}=lm({enabled:e&&!G&&!J&&!A});H(()=>{le.current&&(De.current=le.current)},[De]);const Ct=U("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!J&&!A?"transition-all duration-300":"",G?"w-screen h-[100svh]":J?"w-screen h-screen":A?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Ht=U("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",W.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":J?"rounded-none border-0 flex-row":A?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return l("div",{ref:le,"data-mode":te,className:Ct,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...J&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...J&&!e&&{display:"none"},...A&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...A&&!e&&{display:"none"},...!G&&!J&&!A&&{left:`${Pe.x}px`,top:`${Pe.y}px`,bottom:"auto",right:"auto"},...G&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:W.backgroundImage?"transparent":"hsl(var(--background))"}},children:[l("style",{children:`
2
2
  /* Isolate widget from host website styles */
3
3
  .synapse-chat-widget-container,
4
4
  .synapse-chat-widget-container *,
@@ -35,23 +35,23 @@ var qc=Object.defineProperty;var Xc=(e,t,n)=>t in e?qc(e,t,{enumerable:!0,config
35
35
  .synapse-chat-widget-container [data-radix-scroll-area-viewport] {
36
36
  overscroll-behavior: contain;
37
37
  }
38
- `}),c(en,{className:Ht,"data-text-color":W.textColor,style:G?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[c("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:re}),!W.backgroundImage&&c("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),W.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${W.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),W.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:W.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),c(Zm,{isOpen:_e,onClose:()=>F(!1),botName:x,explicitDisclaimer:b?.explicitDisclaimer,consentContent:b?.consentContent,isFullScreen:J}),_?.isOpen&&c(Jm,{isOpen:!0,botName:x,consentContent:b?.consentContent,onAccept:_.onAccept,isFullScreen:J}),m?.isOpen&&c(ap,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),J&&n,Re==="user"&&!J&&r,c("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[c("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...J?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!J&&!A&&{cursor:e?"grab":"default"}},children:c(Lm,{onClose:y,showCloseButton:k,title:x,titleImg:w,tagline:T,iconUrl:S,startNewConversation:v,voiceAgentState:f,headerTinted:J?!1:W.headerTinted,onToggleDisplayMode:L,onOpenSessionDrawer:J?void 0:X})}),(()=>{const z=J&&!!o,Ie=s&&f===I.VOICE_AGENT_STATE.IDLE?c(Ze,{fallback:c(Pl,{}),children:c(jm,{value:s.value,onChange:s.onChange,onSend:$e?ie:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||$e&&pe,isMobile:G,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:W,onStartNewChat:v,showStartNewChatButton:C,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:E,activeElicitationState:g,isFullScreen:J&&!z,showAttention:s.showAttention})}):null,be={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Le=c(me,{children:[i&&a==="development"&&c("div",{className:"px-6 flex justify-center items-center",children:c("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),J?c("div",{onClick:()=>F(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:c("span",{className:"text-[10px] leading-[14px]",style:be,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):b?.explicitDisclaimer?c("div",{onClick:()=>F(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c("div",{className:"flex justify-center items-center gap-1",children:[c("span",{className:"text-[10px] leading-[14px]",style:be,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:be,children:"Eka Care"})]}),c("span",{className:"text-[10px] leading-[14px]",style:be,children:["AI can make mistakes. ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):c("div",{onClick:()=>F(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c(me,{children:[c("span",{className:"text-[10px] leading-[14px]",style:be,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:be,children:"Eka Care"})]}),c(El,{className:"w-3 h-3"})]})]}),qe=o&&J?o({composer:z?Ie:null,composerFooter:z?Le:null}):null;return c(me,{children:[c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[qe??t,c(Ym,{})]}),s&&!z&&c("div",{className:U("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[c("div",{className:U(J&&"max-w-2xl mx-auto w-full"),children:Ie}),Le]})]})})()]})]})]})}function lp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function cp(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),o=new Date(e.getFullYear(),e.getMonth(),e.getDate());return o.getTime()===n.getTime()?"Today":o.getTime()===r.getTime()?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}function dp(e){const t=new Date(e.c_at),n=cp(t),r=lp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function up(){return c("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function hp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=dp(e);return c("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[c("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),c("div",{className:"flex items-center gap-2 w-full min-w-0",children:[c("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&c(up,{})]})]})}function ac({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?c(Sm,{}):e.length===0?c("div",{className:"flex items-center justify-center h-full px-4 text-center",children:c("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):c(me,{children:e.map(o=>c(hp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function lc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:l,onClose:d}=e;return c(me,{children:[c("div",{className:U("absolute inset-0 z-[60] transition-opacity duration-200",l?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),c("div",{className:U("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",l?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:"flex items-center justify-between",children:[c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:c(Cn,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),c("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(ac,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return c("div",{id:"synapse-session-sidebar","data-collapsed":s,className:U("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:U("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:c(Ch,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?c("button",{type:"button",onClick:o,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:c(dr,{className:"w-6 h-6"})}):c("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&c("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(ac,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function mp(){const e=new Date().getHours();return e>=5&&e<12?"Good morning. How are you feeling today?":e>=12&&e<17?"Good afternoon. How are you feeling right now?":e>=17&&e<21?"Good evening. How are you doing this evening?":"Up late? I'm here whenever you need me."}const pp=180;function fp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=l=>{const d=l.label||l.value||"";d&&n({message:l.value||d,messageId:Date.now().toString()})};return c("div",{className:"flex-1 flex flex-col overflow-y-auto",children:c("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[c("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=pp&&c("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:mp()}),e&&c("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&c("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((l,d)=>{const h=l.label||l.value||"";return h?c("button",{type:"button",onClick:()=>a(l),disabled:r,className:U("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&c("div",{children:[o,i]})]})})}const nn={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Tn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function gp(e,t){return`${e}:${t}`}function cc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function dc(){const[e,t]=V(typeof navigator<"u"?navigator.onLine:!0);return H(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const uc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_p=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Ep=e=>{const t=new Date(e),n=t.toLocaleDateString(void 0,{weekday:"short"}),r=t.toLocaleDateString(void 0,{day:"2-digit"}),o=t.toLocaleDateString(void 0,{month:"short"});return{weekday:n,dayNum:r,month:o}},yp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},hc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Sp=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===I.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),l=n||a,d=n&&r?wp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:hc(l,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const l=a.date?s.findIndex(d=>d.date===a.date):-1;if(l===-1)s.push({...a});else{const d=s[l];s[l]={...d,...uc(a),slots:a.slots??d.slots}}}return s},bp=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,l=s.end_date||o.end_date;r[i]={...s,...uc(o),availability:Sp({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:l,format:n})}}}return r},mc=e=>!!e&&Array.isArray(e.doctors),vp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!mc(e)||!mc(t))return e;const r=e.format||t.format;return{...t,doctors:bp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},wp=(e,t)=>{const n=new Date(e),r=new Date(t),o=Math.round((r.getTime()-n.getTime())/(1e3*60*60*24));return o>=0?o+1:3},pc=(e,t)=>`${e}::${t}`,Np=e=>e<1e12?e*1e3:e,Cp=(e,t)=>`${e}::${t}::answer`,xp=e=>!!e?.tool_id&&!!e?.component;function Tp(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(xp),i=r.timestamp?Qt(Np(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Ne.USER?Ne.USER:Ne.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>pc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[pc(r.id,s.tool_id)]={tool_id:s.tool_id,messageId:r.id,component:s.component,input:s.input,active:!1,disabled:!0,...s.answer&&{answer:s.answer}},s.answer&&t.push({id:Cp(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const kp=Math.round(Al/(1024*1024)),fc=(e,t=0)=>e.length+t>Rl?{title:`You can only upload up to ${Rl} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Al?{title:`Total file size limit of ${kp} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,gc="initial-bot-message",rn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Op=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,l]=V([]),d=q([]),[h,u]=V(!1),[p,E]=V(!1),g=q(new Map),f=q(0),[b,m]=V(!1),_=q([]),y=q(null),k=q({}),x=q({}),w=q(null),T=tm(),S=q(null),{isOnline:v}=dc(),C=q(!1),L=q([]),X=j(N=>N.agentId),G=j(N=>N.sessionId),he=j(N=>N.isStreaming),pe=j(N=>N.isWaitingForResponse),se=j(N=>N.initialMessage),_e=j(N=>N.userId),F=j(N=>N.fileUploadPerSession),{setSessionId:le,setRefreshToken:Re,setSessToken:te,setLevel:J,setError:A,setConnectionStatus:B,setShowRetryButton:re,setStartNewConnection:Se,setIsStreaming:W,setIsWaitingForResponse:Ae,setProgressMessage:$e,setRecordingStatus:ie,clearSession:Pe,clearUser:De,addMessageToSession:Ct,getMessagesForSession:Ht,setMessagesForSession:z,updateMessageInSession:Ie,setUserId:be,setFileUploadPerSession:Le,setToastMessage:qe,upsertElicitationState:Ue,setElicitationState:gt,setInitialMessage:ut,setSessionInitialMessage:je}=j.getState();H(()=>{if(!v)A({title:"No internet connection",description:"Please check your internet connection."}),B(ge.NOT_CONNECTED);else if(!b)B(ge.CONNECTING);else if(Te())B(ge.CONNECTED),_t();else{const{showRetryButton:N,startNewConnection:O,error:P}=j.getState();(N||O||P)&&!Te()&&_t(),w.current!==null&&!O&&!On()&&nt(j.getState().sessionId||void 0)}},[v,b]),H(()=>{G&&(l(N=>{const O=new Set(N.map(M=>M.id)),P=[...N];for(const M of Ht(G)||[])O.has(M.id)||(O.add(M.id),P.push(M));return P}),_.current=[])},[G]),H(()=>{if(m(!1),!X)return;const N=new I.SynapseSDK({agentId:X,...o&&{authToken:o},...j.getState().refreshToken&&{refreshToken:j.getState().refreshToken},...j.getState().sessToken&&{sessToken:j.getState().sessToken},...j.getState().level&&{level:j.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:_e,callbacks:{onError:O=>{if(gr(O),typeof navigator<"u"&&!navigator.onLine){B(ge.NOT_CONNECTED),A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),cn()):wr();return}case I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:wr();return;case I.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:A(null),B(ge.NOT_CONNECTED),Se(!0);return;case I.SYNAPSE_RECOVERY_REASON.RETRY_LATER:B(ge.CONNECTING);return}switch(O.code){case I.SynapseErrorCode.API:case I.SynapseErrorCode.SESSION:{const P=O;P.status===404||P?.context?.status===404?Se(!0):(B(ge.NOT_CONNECTED),A({title:"Something went wrong!",description:rn(O)}),re(!0));break}case I.SynapseErrorCode.RECORDING:A({title:"Recording failed",description:rn(O)});break;case I.SynapseErrorCode.CONNECTION:Te()||(B(ge.NOT_CONNECTED),f.current<2?(f.current=f.current+1,nt(j.getState().sessionId||void 0)):(re(!0),A({title:"Trying to connect...",description:rn(O)})));break;default:A({title:"Something went wrong",description:rn(O)}),re(!0);break}},onTokenExchange:O=>{const P=j.getState().userId;(O?.user_id&&P&&O.user_id!==P||O?.userid_change_detected)&&Pe(),O?.refresh_token&&Re(O.refresh_token),O?.sess_token&&te(O.sess_token),O?.level&&J(O.level),O?.user_id&&be(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=N,T(N),m(!0),()=>{m(!1),Bt(),y.current=null,T(null),S.current&&(clearTimeout(S.current),S.current=null)}},[X,e,o]),H(()=>{d.current=a},[a]),H(()=>{const N=d.current[d.current.length-1];!N?.role||!G||(N?.role===Ne.USER&&!N.isStored?(l(O=>{const P=[...O];return P[P.length-1]={...N,isStored:!0},P}),Ct(G,{...N,isStored:!0})):!he&&!N.isStored&&(l(O=>{const P=[...O];return P[P.length-1]={...N,isStored:!0},P}),Ct(G,{...N,isStored:!0})))},[a,he]),H(()=>()=>{const N=d.current[d.current.length-1],O=j.getState().sessionId;N&&!N?.isStored&&O&&((j.getState().chats[O]||[]).some(P=>P.id===N.id)||Ct(O,{...N,isStored:!0}))},[]),H(()=>(S.current&&(clearTimeout(S.current),S.current=null),pe&&!he?S.current=setTimeout(()=>{Ae(!1),S.current=null},3e4):he&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[pe,he,Ae]);const nt=async N=>{w.current=performance.now();try{const O=await y.current?.startSession(N?{session_id:N}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===N),le(O.session_id)),O?.user_id&&be(O.user_id),O?.initial_message){ut(O.initial_message);const P=O.session_id||N;P&&je(P,O.initial_message)}O?.error?.msg&&qe(O.error.msg)}catch(O){if(O?.reason)return;const P=O;P.status===404||P.context?.status==404?(A(null),B(ge.NOT_CONNECTED),Se(!0)):(A({title:"Connection Lost!",description:rn(O)}),re(!0))}},Be=async N=>{const O=j.getState().chats[N];if(O?.length)return l(O),O;const P=g.current.get(N);if(P)return P;const M=(async()=>{try{const K=await y.current?.getSessionMessages(N);if(!K?.length)return[];const{messages:oe,elicitations:ce}=Tp(K);return Object.keys(ce).length&&gt({...j.getState().elicitationState,...ce}),z(N,oe),l(oe),oe}catch{return[]}finally{g.current.delete(N)}})();g.current.set(N,M),E(!0);try{return await M}finally{E(!1)}},Ge=async({forceNewSession:N=!1,sessionId:O}={})=>{try{if(!y.current){A({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),N){B(ge.CONNECTING),l([]),await Pe(),await y?.current?.endSession(),_t(),await nt(),yr();return}const P=j.getState()?.sessionId,M=O||P||void 0;M!==P&&(Bt(),l([]),M&&await Be(M)),await nt(M),yr()}catch{}finally{u(!1)}},Te=()=>y.current?.isConnected()??!1,Bt=()=>{y.current?.endSession()},_t=()=>{f.current=0;const{showRetryButton:N,startNewConnection:O,error:P}=j.getState();N&&re(!1),O&&Se(!1),P&&A(null)},an=()=>{Rn(nn.CONNECTION_ESTABLISHED)},ln=()=>{let N;try{N=y.current?.getSessionConfig()?.session_id}catch{N=void 0}return N||j.getState().sessionId||void 0},On=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Rn=(N,O={})=>{const P=ln();!P||k.current[N]===P||(k.current[N]=P,cc(N,{sessionId:P,resumed:x.current[P]??!1,...O}))},Qr=(N,O={})=>{const P=ln();cc(N,{...P&&{sessionId:P},...O})},Dt=(N,O,P={})=>{Qr(nn.SESSION_ERROR,{reason:gp(N,O),...P})},gr=N=>{if(Te())return;const O=N?.code,P=[I.SynapseErrorCode.RECORDING,I.SynapseErrorCode.FILE,I.SynapseErrorCode.MESSAGE,I.SynapseErrorCode.VALIDATION,I.SynapseErrorCode.CONFIGURATION,I.SynapseErrorCode.STORE];if(O&&P.includes(O))return;const M=typeof N?.status=="number"?N.status:void 0,K=N?.error,oe=typeof K?.code=="string"?K.code:typeof K?.type=="string"?K.type:void 0,ce={...M!==void 0&&{status:M}};if(N?.reason===I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||N?.reason===I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===I.SynapseErrorCode.AUTH||M===401||M===403){Dt(Tn.AUTH,N?.reason??oe??O??"auth_error",ce);return}const ue=O===I.SynapseErrorCode.API&&M===void 0;if(O===I.SynapseErrorCode.CONNECTION||M===0||ue){Dt(Tn.CONNECTION,N?.reason??oe??(ue?"timeout":O)??"connection_error",ce);return}Dt(Tn.SESSION,N?.reason??oe??O??"session_error",ce)},_r=N=>{switch(N){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Dt(Tn.SESSION,N);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Dt(Tn.CONNECTION,N);return}},Gt=()=>{Rn(nn.FIRST_MESSAGE_SENT)},eo=[nn.CONNECTION_ESTABLISHED,nn.FIRST_MESSAGE_SENT,nn.FIRST_BOT_REPLY],to=()=>{for(const N of eo)delete k.current[N];Te()&&On()&&an()},Er=N=>{N!==gc&&Rn(nn.FIRST_BOT_REPLY,{messageId:N})},yr=()=>{const N=y.current;if(!N)return;for(const[P,M]of L.current)N.off(P,M);L.current=[];const O=(P,M)=>{N.on(P,M),L.current.push([P,M])};O(I.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,P=>{const M=P;if(M.data?.text&&M.messageId){const K=j.getState();K.isStreaming||(Ae(!1),W(!0),_t()),K.connectionStatus!==ge.CONNECTED&&Te()&&B(ge.CONNECTED);const oe=M.data.text,ce=M.messageId,ue=C.current;C.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&Er(ce),l(We=>{const Ce=We[We.length-1];if(Ce&&Ce.id===ce&&Ce.role===Ne.ASSISTANT){const ke=[...We],Qe=ue&&Ce.content.length>0&&!/\s$/.test(Ce.content)&&!/^\s/.test(oe)?`
38
+ `}),l(en,{className:Ht,"data-text-color":W.textColor,style:G?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[l("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:re}),!W.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),W.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${W.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),W.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:W.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(Zm,{isOpen:_e,onClose:()=>F(!1),botName:x,explicitDisclaimer:b?.explicitDisclaimer,consentContent:b?.consentContent,isFullScreen:J}),_?.isOpen&&l(Jm,{isOpen:!0,botName:x,consentContent:b?.consentContent,onAccept:_.onAccept,isFullScreen:J}),m?.isOpen&&l(ap,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),J&&n,Re==="user"&&!J&&r,l("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[l("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...J?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!J&&!A&&{cursor:e?"grab":"default"}},children:l(Lm,{onClose:y,showCloseButton:k,title:x,titleImg:w,tagline:T,iconUrl:S,startNewConversation:v,voiceAgentState:f,headerTinted:J?!1:W.headerTinted,onToggleDisplayMode:L,onOpenSessionDrawer:J?void 0:X})}),(()=>{const z=J&&!!o,Ie=s&&f===I.VOICE_AGENT_STATE.IDLE?l(Ze,{fallback:l(Pl,{}),children:l(jm,{value:s.value,onChange:s.onChange,onSend:$e?ie:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||$e&&pe,isMobile:G,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:W,onStartNewChat:v,showStartNewChatButton:C,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:E,activeElicitationState:g,isFullScreen:J&&!z,showAttention:s.showAttention})}):null,be={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Le=l(me,{children:[i&&a==="development"&&l("div",{className:"px-6 flex justify-center items-center",children:l("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),J?l("div",{onClick:()=>F(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:l("span",{className:"text-[10px] leading-[14px]",style:be,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):b?.explicitDisclaimer?l("div",{onClick:()=>F(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:be,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:be,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:be,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>F(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&l(me,{children:[l("span",{className:"text-[10px] leading-[14px]",style:be,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:be,children:"Eka Care"})]}),l(El,{className:"w-3 h-3"})]})]}),qe=o&&J?o({composer:z?Ie:null,composerFooter:z?Le:null}):null;return l(me,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[qe??t,l(Ym,{})]}),s&&!z&&l("div",{className:U("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:U(J&&"max-w-2xl mx-auto w-full"),children:Ie}),Le]})]})})()]})]})]})}function lp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function cp(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),o=new Date(e.getFullYear(),e.getMonth(),e.getDate());return o.getTime()===n.getTime()?"Today":o.getTime()===r.getTime()?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}function dp(e){const t=new Date(e.c_at),n=cp(t),r=lp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function up(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function hp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=dp(e);return l("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),l("div",{className:"flex items-center gap-2 w-full min-w-0",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&l(up,{})]})]})}function ac({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?l(Sm,{}):e.length===0?l("div",{className:"flex items-center justify-center h-full px-4 text-center",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):l(me,{children:e.map(o=>l(hp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function lc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:c,onClose:d}=e;return l(me,{children:[l("div",{className:U("absolute inset-0 z-[60] transition-opacity duration-200",c?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),l("div",{className:U("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",c?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:"flex items-center justify-between",children:[l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:l(Cn,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[l("div",{className:"pr-2 shrink-0",children:l(dr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),l("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:l(ac,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return l("div",{id:"synapse-session-sidebar","data-collapsed":s,className:U("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:U("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:l(Ch,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?l("button",{type:"button",onClick:o,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:l(dr,{className:"w-6 h-6"})}):l("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[l("div",{className:"pr-2 shrink-0",children:l(dr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&l("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:l(ac,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function mp(){const e=new Date().getHours();return e>=5&&e<12?"Good morning. How are you feeling today?":e>=12&&e<17?"Good afternoon. How are you feeling right now?":e>=17&&e<21?"Good evening. How are you doing this evening?":"Up late? I'm here whenever you need me."}const pp=180;function fp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=c=>{const d=c.label||c.value||"";d&&n({message:c.value||d,messageId:Date.now().toString()})};return l("div",{className:"flex-1 flex flex-col overflow-y-auto",children:l("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[l("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=pp&&l("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:mp()}),e&&l("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&l("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((c,d)=>{const h=c.label||c.value||"";return h?l("button",{type:"button",onClick:()=>a(c),disabled:r,className:U("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&l("div",{children:[o,i]})]})})}const nn={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Tn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function gp(e,t){return`${e}:${t}`}function cc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function dc(){const[e,t]=V(typeof navigator<"u"?navigator.onLine:!0);return H(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const uc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_p=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Ep=e=>{const t=new Date(e),n=t.toLocaleDateString(void 0,{weekday:"short"}),r=t.toLocaleDateString(void 0,{day:"2-digit"}),o=t.toLocaleDateString(void 0,{month:"short"});return{weekday:n,dayNum:r,month:o}},yp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},hc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Sp=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===I.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),c=n||a,d=n&&r?wp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:hc(c,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const c=a.date?s.findIndex(d=>d.date===a.date):-1;if(c===-1)s.push({...a});else{const d=s[c];s[c]={...d,...uc(a),slots:a.slots??d.slots}}}return s},bp=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,c=s.end_date||o.end_date;r[i]={...s,...uc(o),availability:Sp({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},mc=e=>!!e&&Array.isArray(e.doctors),vp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!mc(e)||!mc(t))return e;const r=e.format||t.format;return{...t,doctors:bp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},wp=(e,t)=>{const n=new Date(e),r=new Date(t),o=Math.round((r.getTime()-n.getTime())/(1e3*60*60*24));return o>=0?o+1:3},pc=(e,t)=>`${e}::${t}`,Np=e=>e<1e12?e*1e3:e,Cp=(e,t)=>`${e}::${t}::answer`,xp=e=>!!e?.tool_id&&!!e?.component;function Tp(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(xp),i=r.timestamp?Qt(Np(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Ne.USER?Ne.USER:Ne.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>pc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[pc(r.id,s.tool_id)]={tool_id:s.tool_id,messageId:r.id,component:s.component,input:s.input,active:!1,disabled:!0,...s.answer&&{answer:s.answer}},s.answer&&t.push({id:Cp(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const kp=Math.round(Al/(1024*1024)),fc=(e,t=0)=>e.length+t>Rl?{title:`You can only upload up to ${Rl} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Al?{title:`Total file size limit of ${kp} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,gc="initial-bot-message",rn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Op=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=V([]),d=q([]),[h,u]=V(!1),[p,E]=V(!1),g=q(new Map),f=q(0),[b,m]=V(!1),_=q([]),y=q(null),k=q({}),x=q({}),w=q(null),T=tm(),S=q(null),{isOnline:v}=dc(),C=q(!1),L=q([]),X=j(N=>N.agentId),G=j(N=>N.sessionId),he=j(N=>N.isStreaming),pe=j(N=>N.isWaitingForResponse),se=j(N=>N.initialMessage),_e=j(N=>N.userId),F=j(N=>N.fileUploadPerSession),{setSessionId:le,setRefreshToken:Re,setSessToken:te,setLevel:J,setError:A,setConnectionStatus:B,setShowRetryButton:re,setStartNewConnection:Se,setIsStreaming:W,setIsWaitingForResponse:Ae,setProgressMessage:$e,setRecordingStatus:ie,clearSession:Pe,clearUser:De,addMessageToSession:Ct,getMessagesForSession:Ht,setMessagesForSession:z,updateMessageInSession:Ie,setUserId:be,setFileUploadPerSession:Le,setToastMessage:qe,upsertElicitationState:Ue,setElicitationState:gt,setInitialMessage:ut,setSessionInitialMessage:je}=j.getState();H(()=>{if(!v)A({title:"No internet connection",description:"Please check your internet connection."}),B(ge.NOT_CONNECTED);else if(!b)B(ge.CONNECTING);else if(Te())B(ge.CONNECTED),_t();else{const{showRetryButton:N,startNewConnection:O,error:P}=j.getState();(N||O||P)&&!Te()&&_t(),w.current!==null&&!O&&!On()&&nt(j.getState().sessionId||void 0)}},[v,b]),H(()=>{G&&(c(N=>{const O=new Set(N.map(M=>M.id)),P=[...N];for(const M of Ht(G)||[])O.has(M.id)||(O.add(M.id),P.push(M));return P}),_.current=[])},[G]),H(()=>{if(m(!1),!X)return;const N=new I.SynapseSDK({agentId:X,...o&&{authToken:o},...j.getState().refreshToken&&{refreshToken:j.getState().refreshToken},...j.getState().sessToken&&{sessToken:j.getState().sessToken},...j.getState().level&&{level:j.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:_e,callbacks:{onError:O=>{if(gr(O),typeof navigator<"u"&&!navigator.onLine){B(ge.NOT_CONNECTED),A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),cn()):wr();return}case I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:wr();return;case I.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:A(null),B(ge.NOT_CONNECTED),Se(!0);return;case I.SYNAPSE_RECOVERY_REASON.RETRY_LATER:B(ge.CONNECTING);return}switch(O.code){case I.SynapseErrorCode.API:case I.SynapseErrorCode.SESSION:{const P=O;P.status===404||P?.context?.status===404?Se(!0):(B(ge.NOT_CONNECTED),A({title:"Something went wrong!",description:rn(O)}),re(!0));break}case I.SynapseErrorCode.RECORDING:A({title:"Recording failed",description:rn(O)});break;case I.SynapseErrorCode.CONNECTION:Te()||(B(ge.NOT_CONNECTED),f.current<2?(f.current=f.current+1,nt(j.getState().sessionId||void 0)):(re(!0),A({title:"Trying to connect...",description:rn(O)})));break;default:A({title:"Something went wrong",description:rn(O)}),re(!0);break}},onTokenExchange:O=>{const P=j.getState().userId;(O?.user_id&&P&&O.user_id!==P||O?.userid_change_detected)&&Pe(),O?.refresh_token&&Re(O.refresh_token),O?.sess_token&&te(O.sess_token),O?.level&&J(O.level),O?.user_id&&be(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=N,T(N),m(!0),()=>{m(!1),Bt(),y.current=null,T(null),S.current&&(clearTimeout(S.current),S.current=null)}},[X,e,o]),H(()=>{d.current=a},[a]),H(()=>{const N=d.current[d.current.length-1];!N?.role||!G||(N?.role===Ne.USER&&!N.isStored?(c(O=>{const P=[...O];return P[P.length-1]={...N,isStored:!0},P}),Ct(G,{...N,isStored:!0})):!he&&!N.isStored&&(c(O=>{const P=[...O];return P[P.length-1]={...N,isStored:!0},P}),Ct(G,{...N,isStored:!0})))},[a,he]),H(()=>()=>{const N=d.current[d.current.length-1],O=j.getState().sessionId;N&&!N?.isStored&&O&&((j.getState().chats[O]||[]).some(P=>P.id===N.id)||Ct(O,{...N,isStored:!0}))},[]),H(()=>(S.current&&(clearTimeout(S.current),S.current=null),pe&&!he?S.current=setTimeout(()=>{Ae(!1),S.current=null},3e4):he&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[pe,he,Ae]);const nt=async N=>{w.current=performance.now();try{const O=await y.current?.startSession(N?{session_id:N}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===N),le(O.session_id)),O?.user_id&&be(O.user_id),O?.initial_message){ut(O.initial_message);const P=O.session_id||N;P&&je(P,O.initial_message)}O?.error?.msg&&qe(O.error.msg)}catch(O){if(O?.reason)return;const P=O;P.status===404||P.context?.status==404?(A(null),B(ge.NOT_CONNECTED),Se(!0)):(A({title:"Connection Lost!",description:rn(O)}),re(!0))}},Be=async N=>{const O=j.getState().chats[N];if(O?.length)return c(O),O;const P=g.current.get(N);if(P)return P;const M=(async()=>{try{const K=await y.current?.getSessionMessages(N);if(!K?.length)return[];const{messages:oe,elicitations:ce}=Tp(K);return Object.keys(ce).length&&gt({...j.getState().elicitationState,...ce}),z(N,oe),c(oe),oe}catch{return[]}finally{g.current.delete(N)}})();g.current.set(N,M),E(!0);try{return await M}finally{E(!1)}},Ge=async({forceNewSession:N=!1,sessionId:O}={})=>{try{if(!y.current){A({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),N){B(ge.CONNECTING),c([]),await Pe(),await y?.current?.endSession(),_t(),await nt(),yr();return}const P=j.getState()?.sessionId,M=O||P||void 0;M!==P&&(Bt(),c([]),M&&await Be(M)),await nt(M),yr()}catch{}finally{u(!1)}},Te=()=>y.current?.isConnected()??!1,Bt=()=>{y.current?.endSession()},_t=()=>{f.current=0;const{showRetryButton:N,startNewConnection:O,error:P}=j.getState();N&&re(!1),O&&Se(!1),P&&A(null)},an=()=>{Rn(nn.CONNECTION_ESTABLISHED)},ln=()=>{let N;try{N=y.current?.getSessionConfig()?.session_id}catch{N=void 0}return N||j.getState().sessionId||void 0},On=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Rn=(N,O={})=>{const P=ln();!P||k.current[N]===P||(k.current[N]=P,cc(N,{sessionId:P,resumed:x.current[P]??!1,...O}))},Qr=(N,O={})=>{const P=ln();cc(N,{...P&&{sessionId:P},...O})},Dt=(N,O,P={})=>{Qr(nn.SESSION_ERROR,{reason:gp(N,O),...P})},gr=N=>{if(Te())return;const O=N?.code,P=[I.SynapseErrorCode.RECORDING,I.SynapseErrorCode.FILE,I.SynapseErrorCode.MESSAGE,I.SynapseErrorCode.VALIDATION,I.SynapseErrorCode.CONFIGURATION,I.SynapseErrorCode.STORE];if(O&&P.includes(O))return;const M=typeof N?.status=="number"?N.status:void 0,K=N?.error,oe=typeof K?.code=="string"?K.code:typeof K?.type=="string"?K.type:void 0,ce={...M!==void 0&&{status:M}};if(N?.reason===I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||N?.reason===I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===I.SynapseErrorCode.AUTH||M===401||M===403){Dt(Tn.AUTH,N?.reason??oe??O??"auth_error",ce);return}const ue=O===I.SynapseErrorCode.API&&M===void 0;if(O===I.SynapseErrorCode.CONNECTION||M===0||ue){Dt(Tn.CONNECTION,N?.reason??oe??(ue?"timeout":O)??"connection_error",ce);return}Dt(Tn.SESSION,N?.reason??oe??O??"session_error",ce)},_r=N=>{switch(N){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Dt(Tn.SESSION,N);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Dt(Tn.CONNECTION,N);return}},Gt=()=>{Rn(nn.FIRST_MESSAGE_SENT)},eo=[nn.CONNECTION_ESTABLISHED,nn.FIRST_MESSAGE_SENT,nn.FIRST_BOT_REPLY],to=()=>{for(const N of eo)delete k.current[N];Te()&&On()&&an()},Er=N=>{N!==gc&&Rn(nn.FIRST_BOT_REPLY,{messageId:N})},yr=()=>{const N=y.current;if(!N)return;for(const[P,M]of L.current)N.off(P,M);L.current=[];const O=(P,M)=>{N.on(P,M),L.current.push([P,M])};O(I.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,P=>{const M=P;if(M.data?.text&&M.messageId){const K=j.getState();K.isStreaming||(Ae(!1),W(!0),_t()),K.connectionStatus!==ge.CONNECTED&&Te()&&B(ge.CONNECTED);const oe=M.data.text,ce=M.messageId,ue=C.current;C.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&Er(ce),c(We=>{const Ce=We[We.length-1];if(Ce&&Ce.id===ce&&Ce.role===Ne.ASSISTANT){const ke=[...We],Qe=ue&&Ce.content.length>0&&!/\s$/.test(Ce.content)&&!/^\s/.test(oe)?`
39
39
 
40
- `:"";return ke[ke.length-1]={...Ce,content:Ce.content+Qe+oe},ke}else return[...We,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]})}}),O(I.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{C.current=!1,W(!1),$e(null),Ae(!1)}),O(I.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{_t(),B(ge.CONNECTED),an()}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,P=>{C.current=!0;const M=P;if(!M?.messageId||!M?.data||!M?.data?.details?.component||!M?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:K,data:oe}=M,ce=oe.tool_id,ue=`${K}::${ce}`,Me=j.getState().elicitationState[ue],We=oe.details?.component,Ce=M?.data?.details?._meta?.tool_result,ke=oe.details?.input,Qe=vp(Me?.input,ke,We);let xt=M.data.details?._meta?.disp_toast_msg;const Tt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case I.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Q=M?.data?.details?.input||{},at=Tt.reduce((Lt,Rt)=>(Q[Rt]!==void 0&&(Lt[Rt]=Q[Rt]),Lt),{}),Xe={...Me?.server_input||{},...at},ht=Tt.filter(Lt=>!Xe[Lt]),Ot=M.data.details?._meta?.mcp_meta_fields||[];Ue(ue,{tool_id:ce,active:!0,disabled:!1,input:Qe,server_input:Xe,messageId:K,required:Tt,component:We,pattern:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.pattern,minLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.minLength,maxLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.maxLength,type:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.type,disp_toast_msg:M.data.details?._meta?.disp_toast_msg,description:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.description,tool_result:Ce,orientation:M.data.details?._meta?.orientation,...Ot.length&&{mcp_meta_fields:Ot},...ht?{toolSelectionNames:ht}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case I.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(ue,{...Me||{},tool_id:ce,disabled:!0,active:eh(We),messageId:K,component:We,input:Qe,tool_result:Ce,send_to_llm:!0});break}case I.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(ue,{...Me||{},tool_id:ce,active:!1,messageId:K,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:Ce,disabled:!0});break}default:Ue(ue,{tool_id:ce,disabled:!1,active:!1,messageId:K,tool_result:Ce,input:Qe,component:We})}xt&&qe(xt);const Et=M?.data?.details?._meta?.user_hint;l(Q=>{let at=Q[Q.length-1]?.id===K?Q.length-1:Q.findIndex?.(Xe=>Xe.id===K);if(at==-1){const Xe={id:K,content:M.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[ue],isResponseFromTool:!0,isStored:!1,...Et?{userHint:Et}:{}};return[...Q,Xe]}else{const Xe={...Q[at],isResponseFromTool:!0,tool_keys:[...new Set([...Q[at].tool_keys||[],ue])],...Et?{userHint:Et}:{}};Q[at]=Xe;const ht=j.getState().sessionId;ht&&Ie(ht,K,Xe)}return[...Q]});const kt=M?.data?.details?._meta?.disp_message,rt=j.getState().elicitationState;if((!rt[ue]?.active||rt[ue]?.send_to_llm)&&(kt||Object.keys(Ce||{}).length))try{Wt({message:kt||"",tool_result:Ce,toolCalled:!0,tool_key:ue})}catch{}}),O(I.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,P=>{if(P?.reason===I.DisconnectionReason.CLIENT_CLOSED)return;const M=P;Dt(Tn.CONNECTION,M?.reason??"unknown",{...typeof M?.code=="number"&&{closeCode:M.code}}),w.current=performance.now();const K=typeof navigator<"u"&&!navigator.onLine;if(B(ge.NOT_CONNECTED),K){A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),re(!1);return}f.current<2?(f.current=f.current+1,re(!0),A({title:"Something went wrong!",description:"Please try again."})):(A({title:"Something went wrong!",description:"Please start a new Chat."}),Se(!0))}),O(I.SYNAPSE_REALTIME_EVENTS.ERROR,P=>{const M=P?.data?.code;switch(_r(M),M){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:Se(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:A({title:"Session not found",description:"Please start a new chat from onError callback"}),Se(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:cn();return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case I.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(f.current<1){f.current++,In();return}A({title:"Error parsing request",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:A({title:"Request timed out",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;default:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return}}),O(I.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async P=>{const M=P;M?.data?.text&&(l(K=>[...K,{id:Date.now().toString(),content:M.data.text||"",role:Ne.USER,timestamp:Qt(Date.now()),isStored:!0}]),ie(ye.IDLE)),W(!1),Ae(!1),$e(null)}),O(I.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,P=>{C.current=!0;const M=P;M.data?.text&&(Ae(!1),$e(M.data.text))}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_START,P=>{C.current=!0;const M=P;if(M.data?.name&&M.messageId){const K=M.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===K&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:`Calling tool: ${M.data.name}...`};const Me=j.getState().sessionId;return Me&&Ie(Me,K,{toolCallStatus:`Calling tool: ${M.data.name}...`}),ue}return oe})}}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_END,P=>{C.current=!0;const M=P;if(M.data?.name&&M.messageId){const K=M.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===K&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Ie(Me,K,{toolCallStatus:"Tool call completed."}),ue}return oe})}})},Wt=async({message:N,files:O,audio:P,toolCalled:M,selectedComponent:K,resend:oe,tool_declined:ce,tool_result:ue,tool_key:Me})=>{const We=j.getState().elicitationState,Ce=Object.values(We).some(ke=>ke.active);if(!(!M&&(!O||O.length===0)&&!N?.trim()&&!P?.audio&&!K&&!Ce&&!ue&&!Object.keys(ue||{}).length)){if(O&&O.length>0){const ke=fc(O);if(ke){A(ke);return}}if(O&&O.length>0&&O.length+F>Zo){const ke=Zo-F;A({title:`You can only upload up to ${Zo} files per session`,description:`${ke<=0?"Maximum file upload limit reached":`You have ${ke} file${ke===1?"":"s"} upload${ke===1?"":"s"} left`}`});return}else O&&O.length&&Le(F+O.length);A(null),re(!1),Te()&&B(ge.CONNECTED);try{const ke=a.length<=2&&_.current.length==1?_.current:null;let Qe=null,xt=null;const Tt=a.length-1,Et=Tt>=0?a[Tt]:null,kt=j.getState().elicitationState,rt=Me||null,Q=rt?kt[rt]:void 0,at=Q?.component===I.SYNAPSE_COMPONENTS.DOCTOR_CARD||Q?.component===I.SYNAPSE_COMPONENTS.CARD?!!Q&&!ue&&!!Q.active:!!Q?.active,Xe=!!(O||[]).length||!!P?.audio||!!ce||!at||!M,ht=K?K.label:void 0,Ot=Q?.component===I.SYNAPSE_COMPONENTS.PILL&&typeof ht=="string"?ht:null;if(!Xe&&at&&rt&&Q?.messageId){const Fe=Q.toolSelectionNames?.length?Q.toolSelectionNames:Q.required?.filter(Oe=>!Q.server_input?.[Oe])??[],D=Fe.reduce((Oe,we)=>{if(K){const Mn=K[we];Mn!==void 0&&(Oe[we]=Mn)}else Fe.length===1&&(Oe[we]=N);return Oe},{}),ve=Q.mcp_meta_fields?.reduce((Oe,we)=>(Fe.includes(we)?Oe[we]=D[we]:Q.server_input?.[we]&&(Oe[we]=Q.server_input[we]),oe&&!Oe.is_resend&&(Oe.is_resend=oe),Oe),{}),Ye=Object.keys(Q.server_input||{})?.reduce((Oe,we)=>{const Mn=!Object.keys(ve||{})?.includes(we),ws=!!Q.server_input?.[we];return(oe?Mn&&ws:Mn&&Q.required?.includes(we)&&ws)&&(Oe[we]=Q.server_input?.[we]),Oe},{}),yt=oe?{}:(Q.required||Fe).reduce((Oe,we)=>(Object.keys(ve||{}).includes(we)||(D[we]!==void 0?Oe[we]=D[we]:K&&K[we]!==void 0&&(Oe[we]=K[we])),Oe),{}),Kt={...Ye||{},...yt,...Object.keys(ve||{}).length&&{mcp_meta_fields:ve}};if(!Object.keys(Kt).length)return;await Ue(rt,{...Q,server_input:{...Q.server_input||{},...Kt}});try{await An(Q.tool_id,Q.messageId,Kt),Qe=!0}catch(Oe){await y.current?.sendMessage({tool_result:{...Q.tool_result,error:`Tool call failed: ${rn(Oe)}`}}),xt="Tool call failed",Ue(rt,{...Q,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${rn(Oe)}`}})}}else{const Fe=Et?.id,D=Fe?Object.entries(We).filter(([Ye,yt])=>{const[Kt]=Ye.split("::");return Kt===Fe&&yt.active}):[],ve=ue??Q?.tool_result;await y.current?.sendMessage({message:N??"",files:O,audio:P,...ke&&{initial_prompts:ke},...ce||D.length>0?{tool_declined:!0,tool_id:Q?.tool_id||""}:{},...ve&&{tool_result:ve}})}(N||O&&O.length>0||P?.audio||Ot||xt)&&(Qe||Gt(),l(Fe=>{if(Qe)return Fe;const D=Fe.length===0&&se?.text?[{id:gc,content:se.text,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]:[];return[...Fe,...D,{id:Date.now().toString(),content:Ot||xt||N||"",files:O||[],audio:P,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]}),Qe||Ae(!0),Qe=null);const Lt=j.getState().elicitationState,Rt=new Set;rt&&Rt.add(rt),Et?.tool_keys?.forEach(Fe=>Rt.add(Fe)),Rt.forEach(Fe=>{const D=Lt[Fe];D&&Ue(Fe,{...D,...Xe&&{active:!1,disabled:!0},...Fe===rt?{response_value:{...D?.response_value||{},label:Ot||N||""}}:{}})})}catch{}}},Sr=N=>N.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(N.type)?(A({title:`File type not supported: ${N.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):N.size>3*1024*1024?(A({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,no=async()=>{try{await y.current?.startRecording({onChunks:async N=>{ie(ye.PROCESSING),await Wt({audio:N}),ie(ye.TRANSCRIBING)},onError(N){ie(ye.IDLE)}}),ie(ye.LISTENING)}catch(N){throw ie(ye.IDLE),N}},br=()=>{y.current?.endRecording()},An=async(N,O,P)=>{try{if(!Te())throw new Error("Not connected to the server");await y.current?.callTool(N,O,P)}catch(M){throw M}},cn=async()=>{_t(),await Pe(),await Ge({forceNewSession:!0})},vr=async()=>{await Ge({forceNewSession:!0})},wr=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),B(ge.NOT_CONNECTED),A({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},In=async()=>{if(Te()){B(ge.CONNECTED);const N=d.current[d.current.length-1];if(N&&N.role===Ne.USER)try{y.current?.sendMessage({message:N.content,files:N.files||[],messageId:N.id,audio:N.audio})}catch{}}else if(B(ge.NOT_CONNECTED),f.current<2){f.current++;const{sessionId:N}=j.getState();await nt(N)}else f.current===2?(f.current++,re(!0),A({title:"Trying to connect..."})):(A({title:"Something went wrong!",description:"Please start a new chat."}),Se(!0))};return{sendMessage:Wt,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Bt,isReady:b,startRecording:no,stopRecording:br,getPastSessions:async()=>{try{const N=await y.current?.getPastSessions();return!N||!N?.data?.length?[]:N.data}catch{return[]}},handleRetry:In,isValidFile:Sr,handleStartNewConnection:cn,startNewChat:vr,callTool:An,handleInitialTaskClick:async N=>{const{message:O}=N;if(!se?.suggestions?.length||!O)return;const P=se.suggestions.find(K=>K.value===O);if(_.current=[{role:"assistant",text:`${se.text} ${P?.response||""}`}],!P||!P.response){await Wt(N);return}Gt(),l(K=>[...K,{id:Date.now().toString(),content:O,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]),Ae(!0),await th(1e3),Ae(!1);const M=Date.now().toString();Er(M),l(K=>[...K,{id:M,content:P.response||"Please try again",role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(N,O,P)=>{if(Te())try{await y.current?.sendMessageFeedback(O,N,P)}catch{}},sendSessionFeedback:async(N,O)=>{if(!(!Te()||!N?.length&&!O))try{await y.current?.sendSessionFeedback(N,O)}catch{}},clearElicitationState:async(N,O)=>{const P=j.getState().elicitationState,M=N?P[N]:void 0;try{await Wt({message:O||"User aborted elicitation",tool_declined:!0,tool_result:M?.tool_result,tool_key:N})}catch{}finally{N&&M&&Ue(N,{...M,active:!1,disabled:!0})}},markWidgetOpened:to}};function Ke(e){const t=q(e);return H(()=>{t.current=e}),de(((...n)=>t.current(...n)),[])}function Rp(e){return e==="full"?I.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?I.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":I.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Ap=32,Ip=100,Mp=320;function Pp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Dp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=q(null),i=q(null),[s,a]=V(!1),l=q(null),d=q(!1),h=q("auto"),u=q(!0),p=de(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=de(b=>Pp()?"auto":b,[]),g=de(b=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(b)}),a(!1))},[p,E]),f=de(b=>{d.current=!0,h.current=b,l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,d.current&&(d.current=!1,g(h.current))}))},[g]);return H(()=>()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),d.current=!1},[]),H(()=>{e&&f(t||n?"auto":"smooth")},[e,t,n,f]),H(()=>{if(!e||!u.current)return;const b=setTimeout(()=>f("auto"),Mp);return()=>clearTimeout(b)},[r,e,f]),H(()=>{let b=!1,m=null,_=null,y=0;const k=()=>{if(b)return;const x=p(),w=i.current?.parentElement;if(!x||!w){requestAnimationFrame(k);return}const T=()=>{const{scrollTop:C,scrollHeight:L,clientHeight:X}=x;return L-C-X<=Ap};u.current=!0;let S=0;const v=()=>{if(S>0){S--;return}u.current=T()};x.addEventListener("scroll",v,{passive:!0}),_=()=>x.removeEventListener("scroll",v),m=new ResizeObserver(()=>{if(!u.current)return;const C=Date.now();C-y<Ip||(y=C,S++,f("auto"))}),m.observe(w)};return k(),()=>{b=!0,m?.disconnect(),_?.()}},[p,f]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:g,scheduleScrollToBottom:f}}const us="eka-medassist-agent-config",_c="feedback_hidden",hs="upfront_consent_accepted",Lp=4e3;function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function Ec(e,t){try{const n=localStorage.getItem(us),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(us,JSON.stringify(r))}catch{}}function Up({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:l}=nm(),d=Ke(()=>{r===I.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==I.VOICE_AGENT_STATE.IDLE,[u,p]=V(""),[E,g]=V(!1),[f,b]=V(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=de(()=>b(D=>D==="full"?"widget":"full"),[]),_=Jl()?"mobile":f,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??om,sm),im),x=n.sidePanelMode??"push",[w,T]=V([]),S=q(!1),[v,C]=V(!1),[L,X]=V(!1),[G,he]=V(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=q(null),se=j(D=>D.startNewConnection),_e=j(D=>D.showRetryButton),F=j(D=>D.clearError),le=j(D=>D.error),Re=j(D=>D.connectionStatus),te=j(D=>D.recordingStatus),J=j(D=>D.isWaitingForResponse),A=j(D=>D.isStreaming),B=j(D=>D.setError),re=j(D=>D.sessionId),Se=j(D=>D.initialMessage),W=j(D=>D.sessionInitialMessages),Ae=j(D=>D.elicitationState),$e=j(D=>D.level),{incomingMessages:ie,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:Ct,markWidgetOpened:Ht,startSession:z,startNewChat:Ie,isReady:be,startRecording:Le,stopRecording:qe,handleRetry:Ue,isValidFile:gt,sendMessageFeedback:ut,clearElicitationState:je,sendSessionFeedback:nt,getPastSessions:Be}=Op({environment:n.environment,connectionType:n.connectionType,baseUrl:n.baseUrl?n.baseUrl:void 0,context:n?.context,...n?.authToken&&{authToken:n.authToken},...n?.force&&{force:n.force},channel:Rp(n.displayMode)}),Ge=Ke(Ue),Te=Ke(ut),Bt=Ke(je),_t=Ke(D=>{z({sessionId:D})}),an=Ke(()=>{Ie()}),[ln,On]=V(!1),[Rn,Qr]=V([]),[Dt,gr]=V(!0),_r=q(Be);H(()=>{_r.current=Be});const Gt=de(async()=>{gr(!0);try{const D=await _r.current();Qr(D)}catch{}finally{gr(!1)}},[]),eo=de(async()=>{On(!0),await Gt()},[Gt]),to=de(()=>{On(!1)},[]),[Er,yr]=V(!1),Wt=de(()=>yr(D=>!D),[]);H(()=>{_!=="full"||$e!=="user"||Gt()},[_,$e,re,Gt]),H(()=>{if(t){if(pe.current!==t){const D=j.getState();qh(t),Jh(t),D.setAgentId(t),n.force&&D.clearSession(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(D.setDisplayMode(n.displayMode),D.setInitialDisplayMode(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&D.setContext(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&D.setInitialMessage(n.initialMessage),pe.current=t}e&&be&&!S.current&&(S.current=!0,z({forceNewSession:!1}))}},[e,be,t]),H(()=>{e&&Ht()},[e]),H(()=>{Um([ec])},[]),H(()=>()=>{s()},[]),H(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||he(!0)},[n.theme?.upfrontConsent,t]);const Sr=de(()=>{Ec(t,hs),he(!1)},[t]),no=Ke(()=>{n.feedback&&!ms(t,_c)?X(!0):n.onClose()}),br=Ke(async(D,ve)=>{await nt(D,ve),X(!1),n.onClose()}),An=Ke(()=>{X(!1),n.onClose()}),cn=Ke(()=>{Ec(t,_c),X(!1),n.onClose()}),vr=de(()=>{X(!1)},[]),wr=ie.length>0,In=ie.length===1,N=ae(()=>{const D=ie[ie.length-1],ve=D?.tool_keys?.[D.tool_keys.length-1];if(!ve)return null;const Ye=Ae[ve];return Ye?.active?{...Ye,tool_key:ve}:null},[ie,Ae]),O=ae(()=>(re?W[re]:void 0)??Se??n?.initialMessage??null,[re,W,Se,n?.initialMessage]),P=ae(()=>!!O?.text||!!O?.suggestions?.length,[O]),M=ae(()=>P&&ie?.length===0&&!Pe,[ie,P,Pe]),K=ae(()=>N?N.component===I.SYNAPSE_COMPONENTS.MOBILE||N.component===I.SYNAPSE_COMPONENTS.OTP||N.component===I.SYNAPSE_COMPONENTS.EMAIL:!1,[N]),{scrollAreaRef:oe,messagesEndRef:ce,showScrollButton:ue,scrollToBottom:Me}=Dp({messageCount:ie.length,isStreaming:A,isFirstMessage:In,resolvedMode:_}),We=Re===ge.CONNECTED,Ce=J||A,ke=!Ce&&We&&!le&&!h&&!E&&te===ye.IDLE&&!v&&u.trim().length===0,[Qe,xt]=V(!1);H(()=>{if(!ke){xt(!1);return}const D=setTimeout(()=>xt(!0),Lp);return()=>clearTimeout(D)},[ke]);const Tt=ae(()=>te===ye.IDLE?null:te===ye.LISTENING?"Listening...":te===ye.PROCESSING?"Processing...":te===ye.TRANSCRIBING?"Transcribing...":null,[te]),Et=Tt&&te!==ye.IDLE?Tt:J||A?"Please wait for the response...":"Type a reply\u2026",kt=Ke(async(D,ve)=>{if(Ce)return;const Ye=ve?Ct:De,yt=D?.message??u;w.length>0?(await Ye({files:w,message:yt.trim()}),T([]),C(!1)):yt.trim()?await Ye({...D,message:yt.trim()}):D?.resend?await Ye(D):D&&await Ye(D),p(""),g(!1),C(!1)}),rt=Ke(D=>kt(D,M)),Q=Ke(D=>kt(D,!0)),at=Ke(D=>{if(D&&D.length>0){const ve=D.filter(yt=>gt(yt));if(ve.length===0)return;const Ye=fc(ve,w.length);if(Ye){B(Ye);return}D=ve}T(ve=>(C((ve?.length??0)+(D?.length??0)>0),[...ve,...D]))}),Xe=de(D=>{T(ve=>{const Ye=ve.filter((yt,Kt)=>Kt!==D);return C(Ye.length>0),Ye})},[]),ht=Ke(async()=>{if(E)await qe(),g(!1);else{if(Ce)return;try{await Le(),g(!0)}catch{}}}),Ot=Ke(D=>{p(D)}),Lt=ae(()=>({value:u,onChange:Ot,onSend:kt,onFileChange:at,onRemoveFile:Xe,onRecording:ht,isRecording:E,hasAttachment:v,attachmentFiles:w,isDisabled:Ce,placeholder:Et,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d,showAttention:Qe}),[u,Ot,kt,at,Xe,ht,E,v,w,Ce,Et,te,n.allowed,h,d,Qe]),Rt=ae(()=>n.feedback?{isOpen:L,config:n.feedback,onSubmit:br,onSkip:An,onClose:vr,onDontShowAgain:cn}:void 0,[n.feedback,L,br,An,vr,cn]),Fe=ae(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Sr}:void 0,[n.theme?.upfrontConsent,G,Sr]);return{showScrollButton:ue,toggleDisplayMode:m,resolvedMode:_,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:ce,startNewConnection:se,showRetryButton:_e,clearError:F,error:le,sessionId:re,activeElicitation:N,inConversation:wr,isFirstMessage:In,isEmptyChat:M,isAuthComponent:K,isConnected:We,isComposerDisabled:Ce,isLoadingSessionMessages:Pe,initialMessage:O,incomingMessages:ie,sendMessageFeedback:Te,clearElicitationState:Bt,handleRetry:Ge,handleChatSendMessage:rt,handleEmptyStateSendMessage:Q,handleSelectSession:_t,handleStartNewChat:an,scrollToBottom:Me,handleClose:no,chatComposerProps:Lt,feedbackModalProps:Rt,consentModalProps:Fe,isSessionDrawerOpen:ln,pastSessions:Rn,isLoadingPastSessions:Dt,openSessionDrawer:eo,closeSessionDrawer:to,userLevel:$e,isSidebarCollapsed:Er,toggleSidebar:Wt,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:l}}function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},on.apply(this,arguments)}const Fp=["children","options"],yc=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce((e,t)=>(e[t.toLowerCase()]=t,e),{class:"className",for:"htmlFor"}),Sc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Vp=["style","script","pre"],jp=["src","href","data","formAction","srcDoc","action"],zp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,$p=/\n{2,}$/,bc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Yp=/^ *> ?/gm,Hp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Bp=/^ {2,}\n/,Gp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,vc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,wc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Wp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,Kp=/^(?:\n *)*\n/,qp=/\r\n?/g,Xp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Zp=/^\[\^([^\]]+)]/,Jp=/\f/g,Qp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,ef=/^\s*?\[(x|\s)\]/,Nc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,xc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,tf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Tc=/^<!--[\s\S]*?(?:-->)/,nf=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,rf=/^\{.*\}$/,of=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,sf=/^<([^ >]+[:@\/][^ >]+)>/,af=/-([a-z])?/gi,kc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,lf=/^[^\n]+(?: \n|\n{2,})/,cf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,df=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,uf=/^\[([^\]]*)\] ?\[([^\]]*)\]/,hf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,mf=/\t/g,pf=/(^ *\||\| *$)/g,ff=/^ *:-+: *$/,gf=/^ *:-+ *$/,_f=/^ *-+: *$/,Gr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Wr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Ef=RegExp(`^([*_])\\1${Gr(1)}${Wr}\\1\\1(?!\\1)`),yf=RegExp(`^([*_])${Gr(0)}${Wr}\\1(?!\\1)`),Sf=RegExp(`^(==)${Gr(0)}${Wr}\\1`),bf=RegExp(`^(~~)${Gr(0)}${Wr}\\1`),vf=/^(:[a-zA-Z0-9-_]+:)/,wf=/^\\([^0-9A-Za-z\s])/,Nf=/\\([^0-9A-Za-z\s])/g,Cf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,xf=/^\n+/,Tf=/^([ \t]*)/,kf=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Oc(e){return"( *)("+(e===1?gs:_s)+") +"}const Rc=Oc(1),Ac=Oc(2);function Ic(e){return RegExp("^"+(e===1?Rc:Ac))}const Of=Ic(1),Rf=Ic(2);function Mc(e){return RegExp("^"+(e===1?Rc:Ac)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Af=Mc(1),If=Mc(2);function Pc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Dc=Pc(1),Lc=Pc(2);function Uc(e,t){const n=t===1,r=n?Dc:Lc,o=n?Af:If,i=n?Of:Rf;return{t:s=>i.test(s),o:kn(function(s,a){const l=kf.exec(a.prevCapture);return l&&(a.list||!a.inline&&!a.simple)?r.exec(s=l[1]+s):null}),i:1,u(s,a,l){const d=n?+s[2]:void 0,h=s[0].replace($p,`
40
+ `:"";return ke[ke.length-1]={...Ce,content:Ce.content+Qe+oe},ke}else return[...We,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]})}}),O(I.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{C.current=!1,W(!1),$e(null),Ae(!1)}),O(I.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{_t(),B(ge.CONNECTED),an()}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,P=>{C.current=!0;const M=P;if(!M?.messageId||!M?.data||!M?.data?.details?.component||!M?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:K,data:oe}=M,ce=oe.tool_id,ue=`${K}::${ce}`,Me=j.getState().elicitationState[ue],We=oe.details?.component,Ce=M?.data?.details?._meta?.tool_result,ke=oe.details?.input,Qe=vp(Me?.input,ke,We);let xt=M.data.details?._meta?.disp_toast_msg;const Tt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case I.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Q=M?.data?.details?.input||{},at=Tt.reduce((Lt,Rt)=>(Q[Rt]!==void 0&&(Lt[Rt]=Q[Rt]),Lt),{}),Xe={...Me?.server_input||{},...at},ht=Tt.filter(Lt=>!Xe[Lt]),Ot=M.data.details?._meta?.mcp_meta_fields||[];Ue(ue,{tool_id:ce,active:!0,disabled:!1,input:Qe,server_input:Xe,messageId:K,required:Tt,component:We,pattern:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.pattern,minLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.minLength,maxLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.maxLength,type:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.type,disp_toast_msg:M.data.details?._meta?.disp_toast_msg,description:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.description,tool_result:Ce,orientation:M.data.details?._meta?.orientation,...Ot.length&&{mcp_meta_fields:Ot},...ht?{toolSelectionNames:ht}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case I.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(ue,{...Me||{},tool_id:ce,disabled:!0,active:eh(We),messageId:K,component:We,input:Qe,tool_result:Ce,send_to_llm:!0});break}case I.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(ue,{...Me||{},tool_id:ce,active:!1,messageId:K,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:Ce,disabled:!0});break}default:Ue(ue,{tool_id:ce,disabled:!1,active:!1,messageId:K,tool_result:Ce,input:Qe,component:We})}xt&&qe(xt);const Et=M?.data?.details?._meta?.user_hint;c(Q=>{let at=Q[Q.length-1]?.id===K?Q.length-1:Q.findIndex?.(Xe=>Xe.id===K);if(at==-1){const Xe={id:K,content:M.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[ue],isResponseFromTool:!0,isStored:!1,...Et?{userHint:Et}:{}};return[...Q,Xe]}else{const Xe={...Q[at],isResponseFromTool:!0,tool_keys:[...new Set([...Q[at].tool_keys||[],ue])],...Et?{userHint:Et}:{}};Q[at]=Xe;const ht=j.getState().sessionId;ht&&Ie(ht,K,Xe)}return[...Q]});const kt=M?.data?.details?._meta?.disp_message,rt=j.getState().elicitationState;if((!rt[ue]?.active||rt[ue]?.send_to_llm)&&(kt||Object.keys(Ce||{}).length))try{Wt({message:kt||"",tool_result:Ce,toolCalled:!0,tool_key:ue})}catch{}}),O(I.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,P=>{if(P?.reason===I.DisconnectionReason.CLIENT_CLOSED)return;const M=P;Dt(Tn.CONNECTION,M?.reason??"unknown",{...typeof M?.code=="number"&&{closeCode:M.code}}),w.current=performance.now();const K=typeof navigator<"u"&&!navigator.onLine;if(B(ge.NOT_CONNECTED),K){A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),re(!1);return}f.current<2?(f.current=f.current+1,re(!0),A({title:"Something went wrong!",description:"Please try again."})):(A({title:"Something went wrong!",description:"Please start a new Chat."}),Se(!0))}),O(I.SYNAPSE_REALTIME_EVENTS.ERROR,P=>{const M=P?.data?.code;switch(_r(M),M){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:Se(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:A({title:"Session not found",description:"Please start a new chat from onError callback"}),Se(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:cn();return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case I.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(f.current<1){f.current++,In();return}A({title:"Error parsing request",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:A({title:"Request timed out",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;default:A({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return}}),O(I.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async P=>{const M=P;M?.data?.text&&(c(K=>[...K,{id:Date.now().toString(),content:M.data.text||"",role:Ne.USER,timestamp:Qt(Date.now()),isStored:!0}]),ie(ye.IDLE)),W(!1),Ae(!1),$e(null)}),O(I.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,P=>{C.current=!0;const M=P;M.data?.text&&(Ae(!1),$e(M.data.text))}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_START,P=>{C.current=!0;const M=P;if(M.data?.name&&M.messageId){const K=M.messageId;c(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===K&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:`Calling tool: ${M.data.name}...`};const Me=j.getState().sessionId;return Me&&Ie(Me,K,{toolCallStatus:`Calling tool: ${M.data.name}...`}),ue}return oe})}}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_END,P=>{C.current=!0;const M=P;if(M.data?.name&&M.messageId){const K=M.messageId;c(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===K&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Ie(Me,K,{toolCallStatus:"Tool call completed."}),ue}return oe})}})},Wt=async({message:N,files:O,audio:P,toolCalled:M,selectedComponent:K,resend:oe,tool_declined:ce,tool_result:ue,tool_key:Me})=>{const We=j.getState().elicitationState,Ce=Object.values(We).some(ke=>ke.active);if(!(!M&&(!O||O.length===0)&&!N?.trim()&&!P?.audio&&!K&&!Ce&&!ue&&!Object.keys(ue||{}).length)){if(O&&O.length>0){const ke=fc(O);if(ke){A(ke);return}}if(O&&O.length>0&&O.length+F>Zo){const ke=Zo-F;A({title:`You can only upload up to ${Zo} files per session`,description:`${ke<=0?"Maximum file upload limit reached":`You have ${ke} file${ke===1?"":"s"} upload${ke===1?"":"s"} left`}`});return}else O&&O.length&&Le(F+O.length);A(null),re(!1),Te()&&B(ge.CONNECTED);try{const ke=a.length<=2&&_.current.length==1?_.current:null;let Qe=null,xt=null;const Tt=a.length-1,Et=Tt>=0?a[Tt]:null,kt=j.getState().elicitationState,rt=Me||null,Q=rt?kt[rt]:void 0,at=Q?.component===I.SYNAPSE_COMPONENTS.DOCTOR_CARD||Q?.component===I.SYNAPSE_COMPONENTS.CARD?!!Q&&!ue&&!!Q.active:!!Q?.active,Xe=!!(O||[]).length||!!P?.audio||!!ce||!at||!M,ht=K?K.label:void 0,Ot=Q?.component===I.SYNAPSE_COMPONENTS.PILL&&typeof ht=="string"?ht:null;if(!Xe&&at&&rt&&Q?.messageId){const Fe=Q.toolSelectionNames?.length?Q.toolSelectionNames:Q.required?.filter(Oe=>!Q.server_input?.[Oe])??[],D=Fe.reduce((Oe,we)=>{if(K){const Mn=K[we];Mn!==void 0&&(Oe[we]=Mn)}else Fe.length===1&&(Oe[we]=N);return Oe},{}),ve=Q.mcp_meta_fields?.reduce((Oe,we)=>(Fe.includes(we)?Oe[we]=D[we]:Q.server_input?.[we]&&(Oe[we]=Q.server_input[we]),oe&&!Oe.is_resend&&(Oe.is_resend=oe),Oe),{}),Ye=Object.keys(Q.server_input||{})?.reduce((Oe,we)=>{const Mn=!Object.keys(ve||{})?.includes(we),ws=!!Q.server_input?.[we];return(oe?Mn&&ws:Mn&&Q.required?.includes(we)&&ws)&&(Oe[we]=Q.server_input?.[we]),Oe},{}),yt=oe?{}:(Q.required||Fe).reduce((Oe,we)=>(Object.keys(ve||{}).includes(we)||(D[we]!==void 0?Oe[we]=D[we]:K&&K[we]!==void 0&&(Oe[we]=K[we])),Oe),{}),Kt={...Ye||{},...yt,...Object.keys(ve||{}).length&&{mcp_meta_fields:ve}};if(!Object.keys(Kt).length)return;await Ue(rt,{...Q,server_input:{...Q.server_input||{},...Kt}});try{await An(Q.tool_id,Q.messageId,Kt),Qe=!0}catch(Oe){await y.current?.sendMessage({tool_result:{...Q.tool_result,error:`Tool call failed: ${rn(Oe)}`}}),xt="Tool call failed",Ue(rt,{...Q,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${rn(Oe)}`}})}}else{const Fe=Et?.id,D=Fe?Object.entries(We).filter(([Ye,yt])=>{const[Kt]=Ye.split("::");return Kt===Fe&&yt.active}):[],ve=ue??Q?.tool_result;await y.current?.sendMessage({message:N??"",files:O,audio:P,...ke&&{initial_prompts:ke},...ce||D.length>0?{tool_declined:!0,tool_id:Q?.tool_id||""}:{},...ve&&{tool_result:ve}})}(N||O&&O.length>0||P?.audio||Ot||xt)&&(Qe||Gt(),c(Fe=>{if(Qe)return Fe;const D=Fe.length===0&&se?.text?[{id:gc,content:se.text,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]:[];return[...Fe,...D,{id:Date.now().toString(),content:Ot||xt||N||"",files:O||[],audio:P,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]}),Qe||Ae(!0),Qe=null);const Lt=j.getState().elicitationState,Rt=new Set;rt&&Rt.add(rt),Et?.tool_keys?.forEach(Fe=>Rt.add(Fe)),Rt.forEach(Fe=>{const D=Lt[Fe];D&&Ue(Fe,{...D,...Xe&&{active:!1,disabled:!0},...Fe===rt?{response_value:{...D?.response_value||{},label:Ot||N||""}}:{}})})}catch{}}},Sr=N=>N.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(N.type)?(A({title:`File type not supported: ${N.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):N.size>3*1024*1024?(A({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,no=async()=>{try{await y.current?.startRecording({onChunks:async N=>{ie(ye.PROCESSING),await Wt({audio:N}),ie(ye.TRANSCRIBING)},onError(N){ie(ye.IDLE)}}),ie(ye.LISTENING)}catch(N){throw ie(ye.IDLE),N}},br=()=>{y.current?.endRecording()},An=async(N,O,P)=>{try{if(!Te())throw new Error("Not connected to the server");await y.current?.callTool(N,O,P)}catch(M){throw M}},cn=async()=>{_t(),await Pe(),await Ge({forceNewSession:!0})},vr=async()=>{await Ge({forceNewSession:!0})},wr=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),B(ge.NOT_CONNECTED),A({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},In=async()=>{if(Te()){B(ge.CONNECTED);const N=d.current[d.current.length-1];if(N&&N.role===Ne.USER)try{y.current?.sendMessage({message:N.content,files:N.files||[],messageId:N.id,audio:N.audio})}catch{}}else if(B(ge.NOT_CONNECTED),f.current<2){f.current++;const{sessionId:N}=j.getState();await nt(N)}else f.current===2?(f.current++,re(!0),A({title:"Trying to connect..."})):(A({title:"Something went wrong!",description:"Please start a new chat."}),Se(!0))};return{sendMessage:Wt,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Bt,isReady:b,startRecording:no,stopRecording:br,getPastSessions:async()=>{try{const N=await y.current?.getPastSessions();return!N||!N?.data?.length?[]:N.data}catch{return[]}},handleRetry:In,isValidFile:Sr,handleStartNewConnection:cn,startNewChat:vr,callTool:An,handleInitialTaskClick:async N=>{const{message:O}=N;if(!se?.suggestions?.length||!O)return;const P=se.suggestions.find(K=>K.value===O);if(_.current=[{role:"assistant",text:`${se.text} ${P?.response||""}`}],!P||!P.response){await Wt(N);return}Gt(),c(K=>[...K,{id:Date.now().toString(),content:O,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]),Ae(!0),await th(1e3),Ae(!1);const M=Date.now().toString();Er(M),c(K=>[...K,{id:M,content:P.response||"Please try again",role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(N,O,P)=>{if(Te())try{await y.current?.sendMessageFeedback(O,N,P)}catch{}},sendSessionFeedback:async(N,O)=>{if(!(!Te()||!N?.length&&!O))try{await y.current?.sendSessionFeedback(N,O)}catch{}},clearElicitationState:async(N,O)=>{const P=j.getState().elicitationState,M=N?P[N]:void 0;try{await Wt({message:O||"User aborted elicitation",tool_declined:!0,tool_result:M?.tool_result,tool_key:N})}catch{}finally{N&&M&&Ue(N,{...M,active:!1,disabled:!0})}},markWidgetOpened:to}};function Ke(e){const t=q(e);return H(()=>{t.current=e}),de(((...n)=>t.current(...n)),[])}function Rp(e){return e==="full"?I.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?I.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":I.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Ap=32,Ip=100,Mp=320;function Pp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Dp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=q(null),i=q(null),[s,a]=V(!1),c=q(null),d=q(!1),h=q("auto"),u=q(!0),p=de(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=de(b=>Pp()?"auto":b,[]),g=de(b=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(b)}),a(!1))},[p,E]),f=de(b=>{d.current=!0,h.current=b,c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null,d.current&&(d.current=!1,g(h.current))}))},[g]);return H(()=>()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),d.current=!1},[]),H(()=>{e&&f(t||n?"auto":"smooth")},[e,t,n,f]),H(()=>{if(!e||!u.current)return;const b=setTimeout(()=>f("auto"),Mp);return()=>clearTimeout(b)},[r,e,f]),H(()=>{let b=!1,m=null,_=null,y=0;const k=()=>{if(b)return;const x=p(),w=i.current?.parentElement;if(!x||!w){requestAnimationFrame(k);return}const T=()=>{const{scrollTop:C,scrollHeight:L,clientHeight:X}=x;return L-C-X<=Ap};u.current=!0;let S=0;const v=()=>{if(S>0){S--;return}u.current=T()};x.addEventListener("scroll",v,{passive:!0}),_=()=>x.removeEventListener("scroll",v),m=new ResizeObserver(()=>{if(!u.current)return;const C=Date.now();C-y<Ip||(y=C,S++,f("auto"))}),m.observe(w)};return k(),()=>{b=!0,m?.disconnect(),_?.()}},[p,f]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:g,scheduleScrollToBottom:f}}const us="eka-medassist-agent-config",_c="feedback_hidden",hs="upfront_consent_accepted",Lp=4e3;function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function Ec(e,t){try{const n=localStorage.getItem(us),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(us,JSON.stringify(r))}catch{}}function Up({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=nm(),d=Ke(()=>{r===I.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==I.VOICE_AGENT_STATE.IDLE,[u,p]=V(""),[E,g]=V(!1),[f,b]=V(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=de(()=>b(D=>D==="full"?"widget":"full"),[]),_=Jl()?"mobile":f,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??om,sm),im),x=n.sidePanelMode??"push",[w,T]=V([]),S=q(!1),[v,C]=V(!1),[L,X]=V(!1),[G,he]=V(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=q(null),se=j(D=>D.startNewConnection),_e=j(D=>D.showRetryButton),F=j(D=>D.clearError),le=j(D=>D.error),Re=j(D=>D.connectionStatus),te=j(D=>D.recordingStatus),J=j(D=>D.isWaitingForResponse),A=j(D=>D.isStreaming),B=j(D=>D.setError),re=j(D=>D.sessionId),Se=j(D=>D.initialMessage),W=j(D=>D.sessionInitialMessages),Ae=j(D=>D.elicitationState),$e=j(D=>D.level),{incomingMessages:ie,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:Ct,markWidgetOpened:Ht,startSession:z,startNewChat:Ie,isReady:be,startRecording:Le,stopRecording:qe,handleRetry:Ue,isValidFile:gt,sendMessageFeedback:ut,clearElicitationState:je,sendSessionFeedback:nt,getPastSessions:Be}=Op({environment:n.environment,connectionType:n.connectionType,baseUrl:n.baseUrl?n.baseUrl:void 0,context:n?.context,...n?.authToken&&{authToken:n.authToken},...n?.force&&{force:n.force},channel:Rp(n.displayMode)}),Ge=Ke(Ue),Te=Ke(ut),Bt=Ke(je),_t=Ke(D=>{z({sessionId:D})}),an=Ke(()=>{Ie()}),[ln,On]=V(!1),[Rn,Qr]=V([]),[Dt,gr]=V(!0),_r=q(Be);H(()=>{_r.current=Be});const Gt=de(async()=>{gr(!0);try{const D=await _r.current();Qr(D)}catch{}finally{gr(!1)}},[]),eo=de(async()=>{On(!0),await Gt()},[Gt]),to=de(()=>{On(!1)},[]),[Er,yr]=V(!1),Wt=de(()=>yr(D=>!D),[]);H(()=>{_!=="full"||$e!=="user"||Gt()},[_,$e,re,Gt]),H(()=>{if(t){if(pe.current!==t){const D=j.getState();qh(t),Jh(t),D.setAgentId(t),n.force&&D.clearSession(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(D.setDisplayMode(n.displayMode),D.setInitialDisplayMode(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&D.setContext(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&D.setInitialMessage(n.initialMessage),pe.current=t}e&&be&&!S.current&&(S.current=!0,z({forceNewSession:!1}))}},[e,be,t]),H(()=>{e&&Ht()},[e]),H(()=>{Um([ec])},[]),H(()=>()=>{s()},[]),H(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||he(!0)},[n.theme?.upfrontConsent,t]);const Sr=de(()=>{Ec(t,hs),he(!1)},[t]),no=Ke(()=>{n.feedback&&!ms(t,_c)?X(!0):n.onClose()}),br=Ke(async(D,ve)=>{await nt(D,ve),X(!1),n.onClose()}),An=Ke(()=>{X(!1),n.onClose()}),cn=Ke(()=>{Ec(t,_c),X(!1),n.onClose()}),vr=de(()=>{X(!1)},[]),wr=ie.length>0,In=ie.length===1,N=ae(()=>{const D=ie[ie.length-1],ve=D?.tool_keys?.[D.tool_keys.length-1];if(!ve)return null;const Ye=Ae[ve];return Ye?.active?{...Ye,tool_key:ve}:null},[ie,Ae]),O=ae(()=>(re?W[re]:void 0)??Se??n?.initialMessage??null,[re,W,Se,n?.initialMessage]),P=ae(()=>!!O?.text||!!O?.suggestions?.length,[O]),M=ae(()=>P&&ie?.length===0&&!Pe,[ie,P,Pe]),K=ae(()=>N?N.component===I.SYNAPSE_COMPONENTS.MOBILE||N.component===I.SYNAPSE_COMPONENTS.OTP||N.component===I.SYNAPSE_COMPONENTS.EMAIL:!1,[N]),{scrollAreaRef:oe,messagesEndRef:ce,showScrollButton:ue,scrollToBottom:Me}=Dp({messageCount:ie.length,isStreaming:A,isFirstMessage:In,resolvedMode:_}),We=Re===ge.CONNECTED,Ce=J||A,ke=!Ce&&We&&!le&&!h&&!E&&te===ye.IDLE&&!v&&u.trim().length===0,[Qe,xt]=V(!1);H(()=>{if(!ke){xt(!1);return}const D=setTimeout(()=>xt(!0),Lp);return()=>clearTimeout(D)},[ke]);const Tt=ae(()=>te===ye.IDLE?null:te===ye.LISTENING?"Listening...":te===ye.PROCESSING?"Processing...":te===ye.TRANSCRIBING?"Transcribing...":null,[te]),Et=Tt&&te!==ye.IDLE?Tt:J||A?"Please wait for the response...":"Type a reply\u2026",kt=Ke(async(D,ve)=>{if(Ce)return;const Ye=ve?Ct:De,yt=D?.message??u;w.length>0?(await Ye({files:w,message:yt.trim()}),T([]),C(!1)):yt.trim()?await Ye({...D,message:yt.trim()}):D?.resend?await Ye(D):D&&await Ye(D),p(""),g(!1),C(!1)}),rt=Ke(D=>kt(D,M)),Q=Ke(D=>kt(D,!0)),at=Ke(D=>{if(D&&D.length>0){const ve=D.filter(yt=>gt(yt));if(ve.length===0)return;const Ye=fc(ve,w.length);if(Ye){B(Ye);return}D=ve}T(ve=>(C((ve?.length??0)+(D?.length??0)>0),[...ve,...D]))}),Xe=de(D=>{T(ve=>{const Ye=ve.filter((yt,Kt)=>Kt!==D);return C(Ye.length>0),Ye})},[]),ht=Ke(async()=>{if(E)await qe(),g(!1);else{if(Ce)return;try{await Le(),g(!0)}catch{}}}),Ot=Ke(D=>{p(D)}),Lt=ae(()=>({value:u,onChange:Ot,onSend:kt,onFileChange:at,onRemoveFile:Xe,onRecording:ht,isRecording:E,hasAttachment:v,attachmentFiles:w,isDisabled:Ce,placeholder:Et,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d,showAttention:Qe}),[u,Ot,kt,at,Xe,ht,E,v,w,Ce,Et,te,n.allowed,h,d,Qe]),Rt=ae(()=>n.feedback?{isOpen:L,config:n.feedback,onSubmit:br,onSkip:An,onClose:vr,onDontShowAgain:cn}:void 0,[n.feedback,L,br,An,vr,cn]),Fe=ae(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Sr}:void 0,[n.theme?.upfrontConsent,G,Sr]);return{showScrollButton:ue,toggleDisplayMode:m,resolvedMode:_,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:ce,startNewConnection:se,showRetryButton:_e,clearError:F,error:le,sessionId:re,activeElicitation:N,inConversation:wr,isFirstMessage:In,isEmptyChat:M,isAuthComponent:K,isConnected:We,isComposerDisabled:Ce,isLoadingSessionMessages:Pe,initialMessage:O,incomingMessages:ie,sendMessageFeedback:Te,clearElicitationState:Bt,handleRetry:Ge,handleChatSendMessage:rt,handleEmptyStateSendMessage:Q,handleSelectSession:_t,handleStartNewChat:an,scrollToBottom:Me,handleClose:no,chatComposerProps:Lt,feedbackModalProps:Rt,consentModalProps:Fe,isSessionDrawerOpen:ln,pastSessions:Rn,isLoadingPastSessions:Dt,openSessionDrawer:eo,closeSessionDrawer:to,userLevel:$e,isSidebarCollapsed:Er,toggleSidebar:Wt,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c}}function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},on.apply(this,arguments)}const Fp=["children","options"],yc=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce((e,t)=>(e[t.toLowerCase()]=t,e),{class:"className",for:"htmlFor"}),Sc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Vp=["style","script","pre"],jp=["src","href","data","formAction","srcDoc","action"],zp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,$p=/\n{2,}$/,bc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Yp=/^ *> ?/gm,Hp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Bp=/^ {2,}\n/,Gp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,vc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,wc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Wp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,Kp=/^(?:\n *)*\n/,qp=/\r\n?/g,Xp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Zp=/^\[\^([^\]]+)]/,Jp=/\f/g,Qp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,ef=/^\s*?\[(x|\s)\]/,Nc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,xc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,tf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Tc=/^<!--[\s\S]*?(?:-->)/,nf=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,rf=/^\{.*\}$/,of=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,sf=/^<([^ >]+[:@\/][^ >]+)>/,af=/-([a-z])?/gi,kc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,lf=/^[^\n]+(?: \n|\n{2,})/,cf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,df=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,uf=/^\[([^\]]*)\] ?\[([^\]]*)\]/,hf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,mf=/\t/g,pf=/(^ *\||\| *$)/g,ff=/^ *:-+: *$/,gf=/^ *:-+ *$/,_f=/^ *-+: *$/,Gr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Wr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Ef=RegExp(`^([*_])\\1${Gr(1)}${Wr}\\1\\1(?!\\1)`),yf=RegExp(`^([*_])${Gr(0)}${Wr}\\1(?!\\1)`),Sf=RegExp(`^(==)${Gr(0)}${Wr}\\1`),bf=RegExp(`^(~~)${Gr(0)}${Wr}\\1`),vf=/^(:[a-zA-Z0-9-_]+:)/,wf=/^\\([^0-9A-Za-z\s])/,Nf=/\\([^0-9A-Za-z\s])/g,Cf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,xf=/^\n+/,Tf=/^([ \t]*)/,kf=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Oc(e){return"( *)("+(e===1?gs:_s)+") +"}const Rc=Oc(1),Ac=Oc(2);function Ic(e){return RegExp("^"+(e===1?Rc:Ac))}const Of=Ic(1),Rf=Ic(2);function Mc(e){return RegExp("^"+(e===1?Rc:Ac)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Af=Mc(1),If=Mc(2);function Pc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Dc=Pc(1),Lc=Pc(2);function Uc(e,t){const n=t===1,r=n?Dc:Lc,o=n?Af:If,i=n?Of:Rf;return{t:s=>i.test(s),o:kn(function(s,a){const c=kf.exec(a.prevCapture);return c&&(a.list||!a.inline&&!a.simple)?r.exec(s=c[1]+s):null}),i:1,u(s,a,c){const d=n?+s[2]:void 0,h=s[0].replace($p,`
41
41
  `).match(o);let u=!1;return{items:h.map(function(p,E){const g=i.exec(p)[0].length,f=RegExp("^ {1,"+g+"}","gm"),b=p.replace(f,"").replace(i,""),m=E===h.length-1,_=b.indexOf(`
42
42
 
43
- `)!==-1||m&&u;u=_;const y=l.inline,k=l.list;let x;l.list=!0,_?(l.inline=!1,x=mr(b)+`
43
+ `)!==-1||m&&u;u=_;const y=c.inline,k=c.list;let x;c.list=!0,_?(c.inline=!1,x=mr(b)+`
44
44
 
45
- `):(l.inline=!0,x=mr(b));const w=a(x,l);return l.inline=y,l.list=k,w}),ordered:n,start:d}},l:(s,a,l)=>e(s.ordered?"ol":"ul",{key:l.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,l))}))}}const Mf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Pf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function Fc(e){return typeof e=="string"}function mr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Kr(e,t){return e.startsWith(t)}function Df(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Kr(e,n[r]))return!0;return!1}return n(e,t)}function pr(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function Lf(e){return _f.test(e)?"right":ff.test(e)?"center":gf.test(e)?"left":null}function Vc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const l=i[i.length-1];l.push.apply(l,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((l,d,h)=>{l.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=l}),a(),n.inTable=o,i}function Uf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(pf,"").split("|").map(Lf):[],o=e[3]?(function(s,a,l){return s.trim().split(`
46
- `).map(function(d){return Vc(d,a,l,!0)})})(e[3],t,n):[],i=Vc(e[1],t,n,!!o.length);return n.inline=!1,o.length?{align:r,cells:o,header:i,type:"25"}:{children:i,type:"21"}}function jc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function kn(e){return e.inline=1,e}function sn(e){return kn(function(t,n){return n.inline?e.exec(t):null})}function Yt(e){return kn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Pt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function qr(e){return kn(function(t){return e.exec(t)})}const Ff=/(javascript|vbscript|data(?!:image)):/i;function Vf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Ff.test(t))return null}catch{return null}return e}function Nt(e){return e&&e.replace(Nf,"$1")}function Xr(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!0,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function jf(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!1,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function zf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Es=(e,t,n)=>({children:Xr(t,e[2],n)});function ys(){return{}}function Ss(){return null}function $f(...e){return e.filter(Boolean).join(" ")}function bs(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function Yf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?on({},Sc,t.namedCodesToUnicode):Sc;const n=t.slugify||pr,r=t.sanitizer||Vf,o=t.createElement||et,i=[bc,vc,wc,t.enforceAtxHeadings?Cc:Nc,xc,kc,Dc,Lc],s=[...i,lf,ps,Tc,fs];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function l(m,_,...y){const k=bs(t.overrides,m+".props",{});return o((function(x,w){const T=bs(w,x);return T?typeof T=="function"||typeof T=="object"&&"render"in T?T:bs(w,x+".component",x):x})(m,t.overrides),on({},_,k,{className:$f(_?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(Qp,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=hf.test(m)===!1);const y=f(g(_?m:mr(m).replace(xf,"")+`
45
+ `):(c.inline=!0,x=mr(b));const w=a(x,c);return c.inline=y,c.list=k,w}),ordered:n,start:d}},l:(s,a,c)=>e(s.ordered?"ol":"ul",{key:c.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,c))}))}}const Mf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Pf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function Fc(e){return typeof e=="string"}function mr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Kr(e,t){return e.startsWith(t)}function Df(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Kr(e,n[r]))return!0;return!1}return n(e,t)}function pr(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function Lf(e){return _f.test(e)?"right":ff.test(e)?"center":gf.test(e)?"left":null}function Vc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const c=i[i.length-1];c.push.apply(c,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((c,d,h)=>{c.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=c}),a(),n.inTable=o,i}function Uf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(pf,"").split("|").map(Lf):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
+ `).map(function(d){return Vc(d,a,c,!0)})})(e[3],t,n):[],i=Vc(e[1],t,n,!!o.length);return n.inline=!1,o.length?{align:r,cells:o,header:i,type:"25"}:{children:i,type:"21"}}function jc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function kn(e){return e.inline=1,e}function sn(e){return kn(function(t,n){return n.inline?e.exec(t):null})}function Yt(e){return kn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Pt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function qr(e){return kn(function(t){return e.exec(t)})}const Ff=/(javascript|vbscript|data(?!:image)):/i;function Vf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Ff.test(t))return null}catch{return null}return e}function Nt(e){return e&&e.replace(Nf,"$1")}function Xr(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!0,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function jf(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!1,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function zf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Es=(e,t,n)=>({children:Xr(t,e[2],n)});function ys(){return{}}function Ss(){return null}function $f(...e){return e.filter(Boolean).join(" ")}function bs(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function Yf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?on({},Sc,t.namedCodesToUnicode):Sc;const n=t.slugify||pr,r=t.sanitizer||Vf,o=t.createElement||et,i=[bc,vc,wc,t.enforceAtxHeadings?Cc:Nc,xc,kc,Dc,Lc],s=[...i,lf,ps,Tc,fs];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function c(m,_,...y){const k=bs(t.overrides,m+".props",{});return o((function(x,w){const T=bs(w,x);return T?typeof T=="function"||typeof T=="object"&&"render"in T?T:bs(w,x+".component",x):x})(m,t.overrides),on({},_,k,{className:$f(_?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(Qp,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=hf.test(m)===!1);const y=f(g(_?m:mr(m).replace(xf,"")+`
47
47
 
48
- `,{inline:_}));for(;Fc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(_?"span":"div");let x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?l("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(zp);return y?y.reduce(function(k,x){const w=x.indexOf("=");if(w!==-1){const T=(function(L){return L.indexOf("-")!==-1&&L.match(nf)===null&&(L=L.replace(af,function(X,G){return G.toUpperCase()})),L})(x.slice(0,w)).trim(),S=(function(L){const X=L[0];return(X==='"'||X==="'")&&L.length>=2&&L[L.length-1]===X?L.slice(1,-1):L})(x.slice(w+1).trim()),v=yc[T]||T;if(v==="ref")return k;const C=k[v]=(function(L,X,G,he){return X==="style"?(function(pe){const se=[];let _e="",F=!1,le=!1,Re="";if(!pe)return se;for(let J=0;J<pe.length;J++){const A=pe[J];if(A!=='"'&&A!=="'"||F||(le?A===Re&&(le=!1,Re=""):(le=!0,Re=A)),A==="("&&_e.endsWith("url")?F=!0:A===")"&&F&&(F=!1),A!==";"||le||F)_e+=A;else{const B=_e.trim();if(B){const re=B.indexOf(":");if(re>0){const Se=B.slice(0,re).trim(),W=B.slice(re+1).trim();se.push([Se,W])}}_e=""}}const te=_e.trim();if(te){const J=te.indexOf(":");if(J>0){const A=te.slice(0,J).trim(),B=te.slice(J+1).trim();se.push([A,B])}}return se})(G).reduce(function(pe,[se,_e]){return pe[se.replace(/(-[a-z])/g,F=>F[1].toUpperCase())]=he(_e,L,se),pe},{}):jp.indexOf(X)!==-1?he(Nt(G),L,X):(G.match(rf)&&(G=Nt(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,T,S,r);typeof C=="string"&&(ps.test(C)||fs.test(C))&&(k[v]=d(C.trim()))}else x!=="style"&&(k[yc[x]||x]=!0);return k},{}):null}const u=[],p={},E={0:{t:[">"],o:Pt(bc),i:1,u(m,_,y){const[,k,x]=m[0].replace(Yp,"").match(Hp);return{alert:k,children:_(x,y)}},l(m,_,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),pr),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),l("blockquote",k,_(m.children,y))}},1:{t:[" "],o:qr(Bp),i:1,u:ys,l:(m,_,y)=>l("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Pt(Gp),i:1,u:ys,l:(m,_,y)=>l("hr",{key:y.key})},3:{t:[" "],o:Pt(wc),i:0,u:m=>({lang:void 0,text:Nt(mr(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>l("pre",{key:y.key},l("code",on({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Pt(vc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Yt(Wp),i:3,u:m=>({text:Nt(m[2])}),l:(m,_,y)=>l("code",{key:y.key},m.text)},6:{t:["[^"],o:Pt(Xp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Ss},7:{t:["[^"],o:sn(Zp),i:1,u:m=>({target:"#"+n(m[1],pr),text:m[1]}),l:(m,_,y)=>l("a",{key:y.key,href:r(m.target,"a","href")},l("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:sn(ef),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,_,y)=>l("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Pt(t.enforceAtxHeadings?Cc:Nc),i:1,u:(m,_,y)=>({children:Xr(_,m[2],y),id:n(m[2],pr),level:m[1].length}),l:(m,_,y)=>l("h"+m.level,{id:m.id,key:y.key},_(m.children,y))},10:{t:m=>{const _=m.indexOf(`
49
- `);return _>0&&_<m.length-1&&(m[_+1]==="="||m[_+1]==="-")},o:Pt(xc),i:1,u:(m,_,y)=>({children:Xr(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:qr(ps),i:1,u(m,_,y){const[,k]=m[3].match(Tf),x=RegExp("^"+k,"gm"),w=m[3].replace(x,""),T=a(s,w)?zf:Xr,S=m[1].toLowerCase(),v=Vp.indexOf(S)!==-1,C=(v?S:m[1]).trim(),L={attrs:h(C,m[2]),noInnerParse:v,tag:C};if(y.inAnchor=y.inAnchor||S==="a",v)L.text=m[3];else{const X=y.inHTML;y.inHTML=!0,L.children=T(_,w,y),y.inHTML=X}return y.inAnchor=!1,L},l:(m,_,y)=>l(m.tag,on({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:qr(fs),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>l(m.tag,on({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:qr(Tc),i:1,u:()=>({}),l:Ss},14:{t:["!["],o:Yt(Pf),i:1,u:m=>({alt:Nt(m[1]),target:Nt(m[2]),title:Nt(m[3])}),l:(m,_,y)=>l("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:sn(Mf),i:3,u:(m,_,y)=>({children:jf(_,m[1],y),target:Nt(m[2]),title:Nt(m[3])}),l:(m,_,y)=>l("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},_(m.children,y))},16:{t:["<"],o:sn(sf),i:0,u(m){let _=m[1],y=!1;return _.indexOf("@")!==-1&&_.indexOf("//")===-1&&(y=!0,_=_.replace("mailto:","")),{children:[{text:_,type:"27"}],target:y?"mailto:"+_:_,type:"15"}}},17:{t:(m,_)=>!_.inAnchor&&!t.disableAutoLink&&(Kr(m,"http://")||Kr(m,"https://")),o:sn(of),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Uc(l,1),33:Uc(l,2),19:{t:[`
48
+ `,{inline:_}));for(;Fc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(_?"span":"div");let x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?c("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(zp);return y?y.reduce(function(k,x){const w=x.indexOf("=");if(w!==-1){const T=(function(L){return L.indexOf("-")!==-1&&L.match(nf)===null&&(L=L.replace(af,function(X,G){return G.toUpperCase()})),L})(x.slice(0,w)).trim(),S=(function(L){const X=L[0];return(X==='"'||X==="'")&&L.length>=2&&L[L.length-1]===X?L.slice(1,-1):L})(x.slice(w+1).trim()),v=yc[T]||T;if(v==="ref")return k;const C=k[v]=(function(L,X,G,he){return X==="style"?(function(pe){const se=[];let _e="",F=!1,le=!1,Re="";if(!pe)return se;for(let J=0;J<pe.length;J++){const A=pe[J];if(A!=='"'&&A!=="'"||F||(le?A===Re&&(le=!1,Re=""):(le=!0,Re=A)),A==="("&&_e.endsWith("url")?F=!0:A===")"&&F&&(F=!1),A!==";"||le||F)_e+=A;else{const B=_e.trim();if(B){const re=B.indexOf(":");if(re>0){const Se=B.slice(0,re).trim(),W=B.slice(re+1).trim();se.push([Se,W])}}_e=""}}const te=_e.trim();if(te){const J=te.indexOf(":");if(J>0){const A=te.slice(0,J).trim(),B=te.slice(J+1).trim();se.push([A,B])}}return se})(G).reduce(function(pe,[se,_e]){return pe[se.replace(/(-[a-z])/g,F=>F[1].toUpperCase())]=he(_e,L,se),pe},{}):jp.indexOf(X)!==-1?he(Nt(G),L,X):(G.match(rf)&&(G=Nt(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,T,S,r);typeof C=="string"&&(ps.test(C)||fs.test(C))&&(k[v]=d(C.trim()))}else x!=="style"&&(k[yc[x]||x]=!0);return k},{}):null}const u=[],p={},E={0:{t:[">"],o:Pt(bc),i:1,u(m,_,y){const[,k,x]=m[0].replace(Yp,"").match(Hp);return{alert:k,children:_(x,y)}},l(m,_,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),pr),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,_(m.children,y))}},1:{t:[" "],o:qr(Bp),i:1,u:ys,l:(m,_,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Pt(Gp),i:1,u:ys,l:(m,_,y)=>c("hr",{key:y.key})},3:{t:[" "],o:Pt(wc),i:0,u:m=>({lang:void 0,text:Nt(mr(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>c("pre",{key:y.key},c("code",on({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Pt(vc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Yt(Wp),i:3,u:m=>({text:Nt(m[2])}),l:(m,_,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:Pt(Xp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Ss},7:{t:["[^"],o:sn(Zp),i:1,u:m=>({target:"#"+n(m[1],pr),text:m[1]}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href")},c("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:sn(ef),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,_,y)=>c("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Pt(t.enforceAtxHeadings?Cc:Nc),i:1,u:(m,_,y)=>({children:Xr(_,m[2],y),id:n(m[2],pr),level:m[1].length}),l:(m,_,y)=>c("h"+m.level,{id:m.id,key:y.key},_(m.children,y))},10:{t:m=>{const _=m.indexOf(`
49
+ `);return _>0&&_<m.length-1&&(m[_+1]==="="||m[_+1]==="-")},o:Pt(xc),i:1,u:(m,_,y)=>({children:Xr(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:qr(ps),i:1,u(m,_,y){const[,k]=m[3].match(Tf),x=RegExp("^"+k,"gm"),w=m[3].replace(x,""),T=a(s,w)?zf:Xr,S=m[1].toLowerCase(),v=Vp.indexOf(S)!==-1,C=(v?S:m[1]).trim(),L={attrs:h(C,m[2]),noInnerParse:v,tag:C};if(y.inAnchor=y.inAnchor||S==="a",v)L.text=m[3];else{const X=y.inHTML;y.inHTML=!0,L.children=T(_,w,y),y.inHTML=X}return y.inAnchor=!1,L},l:(m,_,y)=>c(m.tag,on({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:qr(fs),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>c(m.tag,on({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:qr(Tc),i:1,u:()=>({}),l:Ss},14:{t:["!["],o:Yt(Pf),i:1,u:m=>({alt:Nt(m[1]),target:Nt(m[2]),title:Nt(m[3])}),l:(m,_,y)=>c("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:sn(Mf),i:3,u:(m,_,y)=>({children:jf(_,m[1],y),target:Nt(m[2]),title:Nt(m[3])}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},_(m.children,y))},16:{t:["<"],o:sn(sf),i:0,u(m){let _=m[1],y=!1;return _.indexOf("@")!==-1&&_.indexOf("//")===-1&&(y=!0,_=_.replace("mailto:","")),{children:[{text:_,type:"27"}],target:y?"mailto:"+_:_,type:"15"}}},17:{t:(m,_)=>!_.inAnchor&&!t.disableAutoLink&&(Kr(m,"http://")||Kr(m,"https://")),o:sn(of),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Uc(c,1),33:Uc(c,2),19:{t:[`
50
50
  `],o:Pt(Kp),i:3,u:ys,l:()=>`
51
51
  `},21:{o:kn(function(m,_){if(_.inline||_.simple||_.inHTML&&m.indexOf(`
52
52
 
53
53
  `)===-1&&_.prevCapture.indexOf(`
54
54
 
55
55
  `)===-1)return null;let y="",k=0;for(;;){const w=m.indexOf(`
56
- `,k),T=m.slice(k,w===-1?void 0:w+1);if(a(i,T)||(y+=T,w===-1||!T.trim()))break;k=w+1}const x=mr(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,_,y)=>l("p",{key:y.key},_(m.children,y))},22:{t:["["],o:sn(cf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:Yt(df),i:0,u:m=>({alt:m[1]?Nt(m[1]):void 0,ref:m[2]}),l:(m,_,y)=>p[m.ref]?l("img",{key:y.key,alt:m.alt,src:r(p[m.ref].target,"img","src"),title:p[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:sn(uf),i:0,u:(m,_,y)=>({children:_(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,_,y)=>p[m.ref]?l("a",{key:y.key,href:r(p[m.ref].target,"a","href"),title:p[m.ref].title},_(m.children,y)):l("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Pt(kc),i:1,u:Uf,l(m,_,y){const k=m;return l("table",{key:y.key},l("thead",null,l("tr",null,k.header.map(function(x,w){return l("th",{key:w,style:jc(k,w)},_(x,y))}))),l("tbody",null,k.cells.map(function(x,w){return l("tr",{key:w},x.map(function(T,S){return l("td",{key:S,style:jc(k,S)},_(T,y))}))})))}},27:{o:kn(function(m,_){let y;return Kr(m,":")&&(y=vf.exec(m)),y||Cf.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(tf,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Yt(Ef),i:2,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>l("strong",{key:y.key},_(m.children,y))},29:{t:m=>{const _=m[0];return(_==="*"||_==="_")&&m[1]!==_},o:Yt(yf),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>l("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:Yt(wf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Yt(Sf),i:3,u:Es,l:(m,_,y)=>l("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:Yt(bf),i:3,u:Es,l:(m,_,y)=>l("del",{key:y.key},_(m.children,y))}};t.disableParsingRawHTML===!0&&(delete E[11],delete E[13]);const g=(function(m){var _=Object.keys(m);function y(k,x){var w=[];if(x.prevCapture=x.prevCapture||"",k.trim())for(;k;)for(var T=0;T<_.length;){var S=_[T],v=m[S];if(!v.t||Df(k,x,v.t)){var C=v.o(k,x);if(C&&C[0]){k=k.substring(C[0].length);var L=v.u(C,y,x);x.prevCapture+=C[0],L.type||(L.type=S),w.push(L);break}T++}else T++}return x.prevCapture="",w}return _.sort(function(k,x){return m[k].i-m[x].i||(k<x?-1:1)}),function(k,x){return y((function(w){return w.replace(qp,`
57
- `).replace(Jp,"").replace(mf," ")})(k),x)}})(E),f=(function(m,_){return function y(k,x={}){if(Array.isArray(k)){const w=x.key,T=[];let S=!1;for(let v=0;v<k.length;v++){x.key=v;const C=y(k[v],x),L=Fc(C);L&&S?T[T.length-1]+=C:C!==null&&T.push(C),S=L}return x.key=w,T}return(function(w,T,S){const v=m[w.type].l;return _?_(()=>v(w,T,S),w,T,S):v(w,T,S)})(k,y,x)}})(E,t.renderRule),b=d(e);return u.length?l("div",null,b,l("footer",{key:"footer"},u.map(function(m){return l("div",{id:n(m.identifier,pr),key:m.identifier},m.identifier,f(g(m.footnote,{inline:!0})))}))):b}const Hf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,l={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(l[s]=o[s]);return l})(e,Fp);return Ft(Yf(t??"",n),r)},Bf={disableParsingRawHTML:!0,forceBlock:!0};function Gf({children:e}){return c(Hf,{options:Bf,children:e})}const Zr=Xt(Gf);function zc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?c("div",{onClick:i?void 0:o,className:U("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&c("span",{className:s?"text-primary-foreground":"text-primary",children:r}),c("span",{className:"block whitespace-normal",children:e})]}):null}const Wf=tt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Kf=tt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),qf=tt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),Xf=tt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Zf=tt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function He({className:e}){return c("div",{className:U("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function fr({variant:e}){return e==="pill"?c("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[c(Jr,{}),c(He,{className:"h-8 w-20 rounded-full"}),c(He,{className:"h-8 w-24 rounded-full"}),c(He,{className:"h-8 w-16 rounded-full"})]}):e==="media"?c("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[c(Jr,{}),c(He,{className:"h-24 w-full rounded-lg"}),c("div",{className:"mt-3 space-y-2",children:[c(He,{className:"h-3 w-3/4 rounded"}),c(He,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?c("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[c(Jr,{}),c(He,{className:"h-3 w-32 rounded mb-3"}),c("div",{className:"space-y-2",children:[c(He,{className:"h-9 w-full rounded-lg"}),c(He,{className:"h-9 w-full rounded-lg"}),c(He,{className:"h-9 w-full rounded-lg"})]}),c(He,{className:"mt-4 h-9 w-full rounded-lg"})]}):c("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[c(Jr,{}),c("div",{className:"flex items-center gap-3",children:[c(He,{className:"h-10 w-10 rounded-full"}),c("div",{className:"flex-1 space-y-2",children:[c(He,{className:"h-3 w-3/4 rounded"}),c(He,{className:"h-3 w-1/2 rounded"})]})]}),c("div",{className:"mt-4 space-y-2",children:[c(He,{className:"h-3 w-full rounded"}),c(He,{className:"h-3 w-5/6 rounded"})]}),c(He,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Jr(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Jf({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=V([]),[a,l]=V({}),[d,h]=V(!1),[u,p]=V(5),E=n.component,g=n.disabled,f=ae(()=>n.input,[n.input]);H(()=>{E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD&&f?.doctor_details&&l(f.doctor_details)},[E,f?.doctor_details]),H(()=>{n.disabled||(h(!1),p(5),s([]))},[f,n.disabled]);const b=async v=>{h(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},m=async(v,C,L,X=!0)=>{await r({toolCalled:X,selectedComponent:v,selected_id:v.doctor_id,message:C,tool_key:t,messageId:e,...L&&{tool_result:L}})},_=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const v=E===I.SYNAPSE_COMPONENTS.MULTI&&f?.options;return v?Array.isArray(v)?v.map((C,L)=>({id:`option-${L}`,label:C.label,value:C.value})):Object.keys(v).map((C,L)=>({id:`option-${L}`,label:C,value:C})):[]},x=ae(()=>{if(E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return f?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[E,f?.doctors]);if(!E)return null;const w=E===I.SYNAPSE_COMPONENTS.PILL?f?.options:void 0,T=E===I.SYNAPSE_COMPONENTS.CARD?f?.cards:void 0,S=E===I.SYNAPSE_COMPONENTS.MEDIA_CARD?f?.media_card:void 0;return c("div",{className:"flex justify-end",children:[w&&c("div",{className:`flex ${w.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[w.slice(0,u).map((v,C)=>c(zc,{disabled:g||o||d,text:v?.label||"",onClick:()=>b(v),className:"cursor-pointer"},C)),w.length>u&&c("button",{type:"button",disabled:g||o||d,onClick:()=>p(v=>v+5),className:U("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[c(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,w.length-u)," more"]})]}),E===I.SYNAPSE_COMPONENTS.MULTI&&f?.options&&c(Ze,{fallback:c(fr,{variant:"input"}),children:c("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[c("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),c(Wf,{options:k(),selectedValues:i,onSelectionChange:s,disabled:g||o}),c(Ee,{onClick:y,disabled:i.length===0||g||o,className:U("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),x&&x.length>0?c(Ze,{fallback:c(fr,{variant:"card"}),children:c(Kf,{count:x.length>1?x.length+1:x.length,renderItem:(v,C)=>{if(x.length>1&&v===x.length&&n?.hide_show_more!==!0)return c("button",{type:"button",onClick:_,disabled:o||g,className:U("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[c("span",{className:U("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:c(jh,{className:"w-4 h-4 text-primary"})}),c("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const L=x[v];return c(Ze,{fallback:c(fr,{variant:"card"}),children:c(qf,{doctor:L,doctorDetails:a?.[L.doctor_id],disabled:o,onSelect:m,isActive:C})},L.doctor_id)}})}):null,T&&c(Ze,{fallback:c(fr,{variant:"card"}),children:c(Xf,{cards:T,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:g||o})}),S&&c(Ze,{fallback:c(fr,{variant:"media"}),children:c("div",{className:"mt-3",children:c(Zf,{card:S})})})]})}function $c({userFeedback:e,onToggleFeedback:t}){if(e===I.USER_FEEDBACK.NONE)return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c("div",{className:"flex items-center gap-1",children:[c(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.LIKE),children:c(bl,{className:"h-3 w-3"})}),c(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.DISLIKE),children:c(vl,{className:"h-3 w-3"})})]})});if(e===I.USER_FEEDBACK.LIKE||e===I.USER_FEEDBACK.DISLIKE){const n=e===I.USER_FEEDBACK.LIKE?bl:vl;return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:c(n,{className:"h-3 w-3"})})})}return null}function Qf({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:l,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:p,onClearElicitationState:E,isAuthComponent:g,isFullScreen:f}){const b=t===Ne.USER,[m,_]=V(I.USER_FEEDBACK.NONE),y=j(w=>w.isStreaming),k=w=>{_(w),u(w,e)},x=!!(n?.trim()||r&&r.length>0||d||i||a);return c(me,{children:[x&&c("div",{className:U("flex",b?"justify-end":"justify-start"),children:c("div",{className:U("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":f?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":U("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),f&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&c("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&c("div",{className:U("markdown-content",f&&!b?"text-base leading-6":"text-sm"),children:c(Zr,{children:`${n} ${!b&&y&&o?"...":""}`})}),r&&r.length>0&&c("div",{className:"mt-2",children:c(ls,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!y&&o&&(n||m!==I.USER_FEEDBACK.NONE)&&c($c,{userFeedback:m,onToggleFeedback:k}),g&&o&&s?.length?c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Ee,{variant:"link",size:"sm",className:"h-6 px-0 text-[12px] font-medium text-primary border-b border-dashed border-primary rounded-none bg-transparent no-underline hover:no-underline hover:bg-transparent active:bg-transparent focus-visible:bg-transparent rounded-none",onClick:()=>{const w=s[s.length-1];w&&l[w]?.active&&E(w,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(w=>{const T=l[w];return T?c(Jf,{messageId:e,tool_key:w,entry:T,onSendMessage:h,disabled:p||T.disabled},w):null}),a&&!b&&c("div",{className:"flex justify-start",children:c("div",{className:U("flex gap-3 flex-row",f?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",f&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:c("div",{className:U("markdown-content",f?"text-base leading-6":"text-sm"),children:c(Zr,{children:a})})}),!y&&o&&c($c,{userFeedback:m,onToggleFeedback:k})]})})})]})}const eg=Xt(Qf);function tg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){if(!e&&!t?.length)return null;const i=s=>{const a=s.value||s.label||"";a&&n({message:a})};return c(me,{children:[e&&c("div",{className:"flex justify-start",children:c("div",{className:U("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:c(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",o&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:c("div",{className:U("markdown-content",o?"text-base leading-6":"text-sm"),children:c(Zr,{children:e})})})})}),t&&t.length>0&&c("div",{className:"flex justify-end",children:c("div",{className:U("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>c(zc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}const ng=[];function rg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const l=j(u=>u.isWaitingForResponse),d=j(u=>u.elicitationState),h=j(u=>u.progressMessage);return e.length===0&&!h?c(tg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):c(me,{children:[(e&&e.length>0||h)&&c(me,{children:e.map((u,p)=>c("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:p===e.length-1?"last-message":void 0,children:c(eg,{id:u.id,role:u.role,content:u.content,files:u.files||ng,toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,onSendMessage:t,isLastMessage:p===e.length-1,progressMessage:p===e.length-1?h:null,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),l&&c(sg,{})]})}const og=Xt(rg);function sg(){return c("div",{children:c("div",{className:"flex justify-start",children:c("div",{className:"flex gap-3",children:c(en,{className:"px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",children:c("div",{className:"flex items-center gap-1.5","aria-label":"Bot is typing",children:[0,1,2].map(e=>c("span",{className:"w-2 h-2 rounded-full bg-foreground animate-pulse",style:{animationDelay:`${e*150}ms`}},e))})})})})})}function Yc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=dc(),[l,d]=V(!0);return H(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?c("div",{className:U("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:c("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?c("div",{className:U("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),c("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),c("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[c("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!l||!s&&!i?.title&&a?null:c("div",{className:U("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),c("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&c("div",{className:"flex-shrink-0",children:c("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const ig=tt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function ag({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:l,showRetryButton:d,clearError:h,error:u,sessionId:p,activeElicitation:E,isAuthComponent:g,isConnected:f,inConversation:b,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:x,sendMessageFeedback:w,clearElicitationState:T,handleRetry:S,scrollToBottom:v,chatComposerProps:C,isComposerDisabled:L,voiceAgentState:X,isMuted:G,isVoiceAgentActive:he,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:_e,handleClose:F,isSessionDrawerOpen:le,pastSessions:Re,isLoadingPastSessions:te,openSessionDrawer:J,closeSessionDrawer:A,userLevel:B,isSidebarCollapsed:re,toggleSidebar:Se,feedbackModalProps:W,consentModalProps:Ae,handleChatSendMessage:$e,handleEmptyStateSendMessage:ie,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:Ct,sidePanelWidth:Ht,side:z,onSidePanelPushChange:Ie}=Up({isOpen:e,agentId:t,config:n});H(()=>{x.length||v("auto")},[x.length,v]);const be=ae(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=ae(()=>o==="full"&&B==="user"?c(lc,{variant:"sidebar",sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:Se,isLoading:te}):void 0,[o,B,Re,p,Pe,De,re,Se,te]),qe=ae(()=>({onRetry:S,showRetryButton:d,startNewConnection:l,clearError:h,error:u,isConnected:f}),[S,d,l,h,u,f]),Ue=ae(()=>({onClose:F,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:De,showStartNewChatButton:l,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:J}),[F,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,l,n.resize,r,J]),gt=ae(()=>c(lc,{variant:"drawer",isOpen:le,onClose:A,sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:te}),[le,A,Re,p,Pe,De,te]);return c(Mm,{enabled:!!n.resize,children:c(rc,{value:Ue,children:c(ic,{isOpen:e,feedbackModal:W,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:Ct,sidePanelWidth:Ht,side:z,onSidePanelPushChange:Ie,theme:n.theme,isAuthComponent:g,activeElicitation:E,voiceAgentState:X,chatComposer:C,sessionDrawer:gt,sidebar:Le,fullScreenEmptyState:_?ut=>c(fp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ie,disabled:L,composer:ut.composer,composerFooter:ut.composerFooter,connectionBanner:c(Yc,{...qe})}):void 0,children:he?c(Ze,{fallback:c(Hc,{}),children:c(ig,{state:X,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:_e,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):c(Ze,{fallback:c(Hc,{}),children:c("div",{className:U("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[c("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:c(cl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[c("div",{className:"flex-1"}),c("div",{className:U("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?c(ym,{}):c(me,{children:[m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:be}),c(og,{messages:x,onSendMessage:$e,onToggleFeedback:w,onClearElicitationState:T,isAuthComponent:g,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!f})]}),c("div",{ref:s})]})]})}),a&&c("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:c(Ee,{onClick:()=>v("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:c(Wo,{className:"w-5 h-5 text-text-primary"})})}),c(Yc,{className:"mt-2",...qe})]})})})})})}function Hc(){return c("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[c("div",{className:"flex-1 p-6 space-y-4",children:[c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),c("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Bc(e){return!!e&&e.startsWith("ResizeObserver loop")}function vs(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);try{return new Error(JSON.stringify(e))}catch{return new Error("Unknown error")}}class lg extends lt{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:vs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?c(ug,{error:this.state.error,componentStack:this.state.componentStack,title:this.props.title,titleImg:this.props.titleImg,iconUrl:this.props.iconUrl,onClose:this.props.onClose,showCloseButton:this.props.showCloseButton,environment:this.props.environment,displayMode:this.props.displayMode,theme:this.props.theme}):this.props.children}}function cg({error:e}){throw e}function dg(e){const[t,n]=V(null);return H(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Bc(i?.message)||Bc(i?.error?.message)||(i?.error?n(vs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(vs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),c(lg,{...e,children:t?c(cg,{error:t}):e.children})}function ug({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:l}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ae(()=>l?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[l?.textColor]),E=ae(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return c(rc,{value:E,children:c(ic,{isOpen:!0,environment:u,mode:a??"widget",theme:l,children:c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:c("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:c("div",{className:"w-full max-w-[320px] text-center",children:[c("div",{className:"mx-auto mb-4 grid place-items-center",children:c("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:c(Uh,{className:"h-8 w-8",style:{color:l?.primary??"hsl(var(--primary))"}})})}),c("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),c("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),c("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",p].join(" "),children:e?.message||String(e)}),c("div",{className:"mt-5 flex items-center justify-center gap-3",children:c(Ee,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:l?.primary??void 0},children:[c(Ih,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function hg({agentId:e,config:t}){const[n,r]=V(t.displayMode==="full");H(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return c(dg,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:c(Qh,{children:c(ag,{isOpen:n,agentId:e,config:{...t,environment:t.environment??"production",onClose:o,title:t.title??"Medi Clinic",iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",theme:t.theme}})})})}const Gc=(e,t,n)=>{const r=n||{},o=yd(e);return o.render(c(me,{children:c(hg,{agentId:t,config:r})})),o},mg=e=>{try{const t=sessionStorage.getItem(ur(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Wc=e=>{const{refreshToken:t,sessToken:n}=mg(e.agentId);return t&&n?Promise.resolve(null):I.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Kc=e=>I.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Gc,window.fetchAgentConfig=Kc,window.prefetchAuth=Wc);export{q as A,Ee as B,Wo as C,ee as D,_l as F,El as I,Ko as M,Xt as N,pn as P,Oo as R,cs as S,ae as T,Cn as X,mt as _,I as a,U as b,ze as c,V as d,me as e,Zt as f,Kc as fetchAgentConfig,Si as g,fn as h,Vt as i,zt as j,Ep as k,xl as l,ss as m,Kl as n,is as o,_p as p,Wc as prefetchAuth,de as q,kl as r,Gc as renderMedAssist,Zr as s,hc as t,c as u,en as v,yp as w,Tl as x,H as y,Ol as z};
56
+ `,k),T=m.slice(k,w===-1?void 0:w+1);if(a(i,T)||(y+=T,w===-1||!T.trim()))break;k=w+1}const x=mr(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,_,y)=>c("p",{key:y.key},_(m.children,y))},22:{t:["["],o:sn(cf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:Yt(df),i:0,u:m=>({alt:m[1]?Nt(m[1]):void 0,ref:m[2]}),l:(m,_,y)=>p[m.ref]?c("img",{key:y.key,alt:m.alt,src:r(p[m.ref].target,"img","src"),title:p[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:sn(uf),i:0,u:(m,_,y)=>({children:_(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,_,y)=>p[m.ref]?c("a",{key:y.key,href:r(p[m.ref].target,"a","href"),title:p[m.ref].title},_(m.children,y)):c("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Pt(kc),i:1,u:Uf,l(m,_,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(x,w){return c("th",{key:w,style:jc(k,w)},_(x,y))}))),c("tbody",null,k.cells.map(function(x,w){return c("tr",{key:w},x.map(function(T,S){return c("td",{key:S,style:jc(k,S)},_(T,y))}))})))}},27:{o:kn(function(m,_){let y;return Kr(m,":")&&(y=vf.exec(m)),y||Cf.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(tf,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Yt(Ef),i:2,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("strong",{key:y.key},_(m.children,y))},29:{t:m=>{const _=m[0];return(_==="*"||_==="_")&&m[1]!==_},o:Yt(yf),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:Yt(wf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Yt(Sf),i:3,u:Es,l:(m,_,y)=>c("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:Yt(bf),i:3,u:Es,l:(m,_,y)=>c("del",{key:y.key},_(m.children,y))}};t.disableParsingRawHTML===!0&&(delete E[11],delete E[13]);const g=(function(m){var _=Object.keys(m);function y(k,x){var w=[];if(x.prevCapture=x.prevCapture||"",k.trim())for(;k;)for(var T=0;T<_.length;){var S=_[T],v=m[S];if(!v.t||Df(k,x,v.t)){var C=v.o(k,x);if(C&&C[0]){k=k.substring(C[0].length);var L=v.u(C,y,x);x.prevCapture+=C[0],L.type||(L.type=S),w.push(L);break}T++}else T++}return x.prevCapture="",w}return _.sort(function(k,x){return m[k].i-m[x].i||(k<x?-1:1)}),function(k,x){return y((function(w){return w.replace(qp,`
57
+ `).replace(Jp,"").replace(mf," ")})(k),x)}})(E),f=(function(m,_){return function y(k,x={}){if(Array.isArray(k)){const w=x.key,T=[];let S=!1;for(let v=0;v<k.length;v++){x.key=v;const C=y(k[v],x),L=Fc(C);L&&S?T[T.length-1]+=C:C!==null&&T.push(C),S=L}return x.key=w,T}return(function(w,T,S){const v=m[w.type].l;return _?_(()=>v(w,T,S),w,T,S):v(w,T,S)})(k,y,x)}})(E,t.renderRule),b=d(e);return u.length?c("div",null,b,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,pr),key:m.identifier},m.identifier,f(g(m.footnote,{inline:!0})))}))):b}const Hf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,c={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(c[s]=o[s]);return c})(e,Fp);return Ft(Yf(t??"",n),r)},Bf={disableParsingRawHTML:!0,forceBlock:!0};function Gf({children:e}){return l(Hf,{options:Bf,children:e})}const Zr=Xt(Gf);function zc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?l("div",{onClick:i?void 0:o,className:U("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&l("span",{className:s?"text-primary-foreground":"text-primary",children:r}),l("span",{className:"block whitespace-normal",children:e})]}):null}const Wf=tt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Kf=tt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),qf=tt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),Xf=tt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Zf=tt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function He({className:e}){return l("div",{className:U("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function fr({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(Jr,{}),l(He,{className:"h-8 w-20 rounded-full"}),l(He,{className:"h-8 w-24 rounded-full"}),l(He,{className:"h-8 w-16 rounded-full"})]}):e==="media"?l("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[l(Jr,{}),l(He,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(He,{className:"h-3 w-3/4 rounded"}),l(He,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?l("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[l(Jr,{}),l(He,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(He,{className:"h-9 w-full rounded-lg"}),l(He,{className:"h-9 w-full rounded-lg"}),l(He,{className:"h-9 w-full rounded-lg"})]}),l(He,{className:"mt-4 h-9 w-full rounded-lg"})]}):l("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[l(Jr,{}),l("div",{className:"flex items-center gap-3",children:[l(He,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(He,{className:"h-3 w-3/4 rounded"}),l(He,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(He,{className:"h-3 w-full rounded"}),l(He,{className:"h-3 w-5/6 rounded"})]}),l(He,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Jr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Jf({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=V([]),[a,c]=V({}),[d,h]=V(!1),[u,p]=V(5),E=n.component,g=n.disabled,f=ae(()=>n.input,[n.input]);H(()=>{E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD&&f?.doctor_details&&c(f.doctor_details)},[E,f?.doctor_details]),H(()=>{n.disabled||(h(!1),p(5),s([]))},[f,n.disabled]);const b=async v=>{h(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},m=async(v,C,L,X=!0)=>{await r({toolCalled:X,selectedComponent:v,selected_id:v.doctor_id,message:C,tool_key:t,messageId:e,...L&&{tool_result:L}})},_=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const v=E===I.SYNAPSE_COMPONENTS.MULTI&&f?.options;return v?Array.isArray(v)?v.map((C,L)=>({id:`option-${L}`,label:C.label,value:C.value})):Object.keys(v).map((C,L)=>({id:`option-${L}`,label:C,value:C})):[]},x=ae(()=>{if(E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return f?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[E,f?.doctors]);if(!E)return null;const w=E===I.SYNAPSE_COMPONENTS.PILL?f?.options:void 0,T=E===I.SYNAPSE_COMPONENTS.CARD?f?.cards:void 0,S=E===I.SYNAPSE_COMPONENTS.MEDIA_CARD?f?.media_card:void 0;return l("div",{className:"flex justify-end",children:[w&&l("div",{className:`flex ${w.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[w.slice(0,u).map((v,C)=>l(zc,{disabled:g||o||d,text:v?.label||"",onClick:()=>b(v),className:"cursor-pointer"},C)),w.length>u&&l("button",{type:"button",disabled:g||o||d,onClick:()=>p(v=>v+5),className:U("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[l(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,w.length-u)," more"]})]}),E===I.SYNAPSE_COMPONENTS.MULTI&&f?.options&&l(Ze,{fallback:l(fr,{variant:"input"}),children:l("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[l("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),l(Wf,{options:k(),selectedValues:i,onSelectionChange:s,disabled:g||o}),l(Ee,{onClick:y,disabled:i.length===0||g||o,className:U("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),x&&x.length>0?l(Ze,{fallback:l(fr,{variant:"card"}),children:l(Kf,{count:x.length>1?x.length+1:x.length,renderItem:(v,C)=>{if(x.length>1&&v===x.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:_,disabled:o||g,className:U("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[l("span",{className:U("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(jh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const L=x[v];return l(Ze,{fallback:l(fr,{variant:"card"}),children:l(qf,{doctor:L,doctorDetails:a?.[L.doctor_id],disabled:o,onSelect:m,isActive:C})},L.doctor_id)}})}):null,T&&l(Ze,{fallback:l(fr,{variant:"card"}),children:l(Xf,{cards:T,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:g||o})}),S&&l(Ze,{fallback:l(fr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(Zf,{card:S})})})]})}function $c({userFeedback:e,onToggleFeedback:t}){if(e===I.USER_FEEDBACK.NONE)return l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.LIKE),children:l(bl,{className:"h-3 w-3"})}),l(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.DISLIKE),children:l(vl,{className:"h-3 w-3"})})]})});if(e===I.USER_FEEDBACK.LIKE||e===I.USER_FEEDBACK.DISLIKE){const n=e===I.USER_FEEDBACK.LIKE?bl:vl;return l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(Ee,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(n,{className:"h-3 w-3"})})})}return null}function Qf({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:c,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:p,onClearElicitationState:E,isAuthComponent:g,isFullScreen:f}){const b=t===Ne.USER,[m,_]=V(I.USER_FEEDBACK.NONE),y=j(w=>w.isStreaming),k=w=>{_(w),u(w,e)},x=!!(n?.trim()||r&&r.length>0||d||i||a);return l(me,{children:[x&&l("div",{className:U("flex",b?"justify-end":"justify-start"),children:l("div",{className:U("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":f?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":U("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),f&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:U("markdown-content",f&&!b?"text-base leading-6":"text-sm"),children:l(Zr,{children:`${n} ${!b&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l(ls,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!y&&o&&(n||m!==I.USER_FEEDBACK.NONE)&&l($c,{userFeedback:m,onToggleFeedback:k}),g&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(Ee,{variant:"link",size:"sm",className:"h-6 px-0 text-[12px] font-medium text-primary border-b border-dashed border-primary rounded-none bg-transparent no-underline hover:no-underline hover:bg-transparent active:bg-transparent focus-visible:bg-transparent rounded-none",onClick:()=>{const w=s[s.length-1];w&&c[w]?.active&&E(w,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(w=>{const T=c[w];return T?l(Jf,{messageId:e,tool_key:w,entry:T,onSendMessage:h,disabled:p||T.disabled},w):null}),a&&!b&&l("div",{className:"flex justify-start",children:l("div",{className:U("flex gap-3 flex-row",f?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",f&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:l("div",{className:U("markdown-content",f?"text-base leading-6":"text-sm"),children:l(Zr,{children:a})})}),!y&&o&&l($c,{userFeedback:m,onToggleFeedback:k})]})})})]})}const eg=Xt(Qf);function tg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){if(!e&&!t?.length)return null;const i=s=>{const a=s.value||s.label||"";a&&n({message:a})};return l(me,{children:[e&&l("div",{className:"flex justify-start",children:l("div",{className:U("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l(en,{className:U("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",o&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:l("div",{className:U("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Zr,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:U("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(zc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}const ng=[];function rg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const c=j(u=>u.isWaitingForResponse),d=j(u=>u.elicitationState),h=j(u=>u.progressMessage);return e.length===0&&!h?l(tg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):l(me,{children:[(e&&e.length>0||h)&&l(me,{children:e.map((u,p)=>l("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:p===e.length-1?"last-message":void 0,children:l(eg,{id:u.id,role:u.role,content:u.content,files:u.files||ng,toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,onSendMessage:t,isLastMessage:p===e.length-1,progressMessage:p===e.length-1?h:null,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),c&&l(sg,{})]})}const og=Xt(rg);function sg(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(en,{className:"px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",children:l("div",{className:"flex items-center gap-1.5","aria-label":"Bot is typing",children:[0,1,2].map(e=>l("span",{className:"w-2 h-2 rounded-full bg-foreground animate-pulse",style:{animationDelay:`${e*150}ms`}},e))})})})})})}function Yc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=dc(),[c,d]=V(!0);return H(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?l("div",{className:U("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:l("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?l("div",{className:U("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),l("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),l("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[l("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!c||!s&&!i?.title&&a?null:l("div",{className:U("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),l("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&l("div",{className:"flex-shrink-0",children:l("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const ig=tt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function ag({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:c,showRetryButton:d,clearError:h,error:u,sessionId:p,activeElicitation:E,isAuthComponent:g,isConnected:f,inConversation:b,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:x,sendMessageFeedback:w,clearElicitationState:T,handleRetry:S,scrollToBottom:v,chatComposerProps:C,isComposerDisabled:L,voiceAgentState:X,isMuted:G,isVoiceAgentActive:he,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:_e,handleClose:F,isSessionDrawerOpen:le,pastSessions:Re,isLoadingPastSessions:te,openSessionDrawer:J,closeSessionDrawer:A,userLevel:B,isSidebarCollapsed:re,toggleSidebar:Se,feedbackModalProps:W,consentModalProps:Ae,handleChatSendMessage:$e,handleEmptyStateSendMessage:ie,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:Ct,sidePanelWidth:Ht,side:z,onSidePanelPushChange:Ie}=Up({isOpen:e,agentId:t,config:n});H(()=>{x.length||v("auto")},[x.length,v]);const be=ae(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=ae(()=>o==="full"&&B==="user"?l(lc,{variant:"sidebar",sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:Se,isLoading:te}):void 0,[o,B,Re,p,Pe,De,re,Se,te]),qe=ae(()=>({onRetry:S,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:f}),[S,d,c,h,u,f]),Ue=ae(()=>({onClose:F,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:De,showStartNewChatButton:c,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:J}),[F,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,c,n.resize,r,J]),gt=ae(()=>l(lc,{variant:"drawer",isOpen:le,onClose:A,sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:te}),[le,A,Re,p,Pe,De,te]);return l(Mm,{enabled:!!n.resize,children:l(rc,{value:Ue,children:l(ic,{isOpen:e,feedbackModal:W,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:Ct,sidePanelWidth:Ht,side:z,onSidePanelPushChange:Ie,theme:n.theme,isAuthComponent:g,activeElicitation:E,voiceAgentState:X,chatComposer:C,sessionDrawer:gt,sidebar:Le,fullScreenEmptyState:_?ut=>l(fp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ie,disabled:L,composer:ut.composer,composerFooter:ut.composerFooter,connectionBanner:l(Yc,{...qe})}):void 0,children:he?l(Ze,{fallback:l(Hc,{}),children:l(ig,{state:X,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:_e,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l(Ze,{fallback:l(Hc,{}),children:l("div",{className:U("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[l("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:l(cl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[l("div",{className:"flex-1"}),l("div",{className:U("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?l(ym,{}):l(me,{children:[m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:be}),l(og,{messages:x,onSendMessage:$e,onToggleFeedback:w,onClearElicitationState:T,isAuthComponent:g,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!f})]}),l("div",{ref:s})]})]})}),a&&l("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:l(Ee,{onClick:()=>v("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:l(Wo,{className:"w-5 h-5 text-text-primary"})})}),l(Yc,{className:"mt-2",...qe})]})})})})})}function Hc(){return l("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[l("div",{className:"flex-1 p-6 space-y-4",children:[l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),l("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Bc(e){return!!e&&e.startsWith("ResizeObserver loop")}function vs(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);try{return new Error(JSON.stringify(e))}catch{return new Error("Unknown error")}}class lg extends lt{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:vs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(ug,{error:this.state.error,componentStack:this.state.componentStack,title:this.props.title,titleImg:this.props.titleImg,iconUrl:this.props.iconUrl,onClose:this.props.onClose,showCloseButton:this.props.showCloseButton,environment:this.props.environment,displayMode:this.props.displayMode,theme:this.props.theme}):this.props.children}}function cg({error:e}){throw e}function dg(e){const[t,n]=V(null);return H(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Bc(i?.message)||Bc(i?.error?.message)||(i?.error?n(vs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(vs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(lg,{...e,children:t?l(cg,{error:t}):e.children})}function ug({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:c}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ae(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]),E=ae(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return l(rc,{value:E,children:l(ic,{isOpen:!0,environment:u,mode:a??"widget",theme:c,children:l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:l("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:l("div",{className:"w-full max-w-[320px] text-center",children:[l("div",{className:"mx-auto mb-4 grid place-items-center",children:l("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:l(Uh,{className:"h-8 w-8",style:{color:c?.primary??"hsl(var(--primary))"}})})}),l("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),l("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),l("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",p].join(" "),children:e?.message||String(e)}),l("div",{className:"mt-5 flex items-center justify-center gap-3",children:l(Ee,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(Ih,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function hg({agentId:e,config:t}){const[n,r]=V(t.displayMode==="full");H(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(dg,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:l(Qh,{children:l(ag,{isOpen:n,agentId:e,config:{...t,environment:t.environment??"production",onClose:o,title:t.title??"Medi Clinic",iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",theme:t.theme}})})})}const Gc=(e,t,n)=>{const r=n||{},o=yd(e);return o.render(l(me,{children:l(hg,{agentId:t,config:r})})),o},mg=e=>{try{const t=sessionStorage.getItem(ur(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Wc=e=>{const{refreshToken:t,sessToken:n}=mg(e.agentId);return t&&n?Promise.resolve(null):I.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Kc=e=>I.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Gc,window.fetchAgentConfig=Kc,window.prefetchAuth=Wc);export{q as A,Ee as B,Wo as C,ee as D,_l as F,El as I,Ko as M,Xt as N,pn as P,Oo as R,cs as S,ae as T,Cn as X,mt as _,I as a,U as b,ze as c,V as d,me as e,Zt as f,Kc as fetchAgentConfig,Si as g,fn as h,Vt as i,zt as j,Ep as k,xl as l,ss as m,Kl as n,is as o,_p as p,Wc as prefetchAuth,de as q,kl as r,Gc as renderMedAssist,Zr as s,hc as t,l as u,en as v,yp as w,Tl as x,H as y,Ol as z};