@eka-care/medassist-widget 0.1.131 → 0.1.132-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.
- package/dist/medassist-widget.css +1 -1
- package/dist/medassist-widget.js +14 -14
- package/package.json +1 -1
package/dist/medassist-widget.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Pc=Object.defineProperty;var Dc=(e,t,n)=>t in e?Pc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var O=(e,t,n)=>Dc(e,typeof t!="symbol"?t+"":t,n);var xn,K,_s,Dt,Es,ys,Ss,qr,dr,Cn,vs,Xr,Jr,Zr,bs,ur={},hr=[],Lc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Tn=Array.isArray;function _t(e,t){for(var n in t)e[n]=t[n];return e}function Qr(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function qe(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?xn.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 kn(e,s,r,o,null)}function kn(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??++_s,__i:-1,__u:0};return o==null&&K.vnode!=null&&K.vnode(i),i}function ws(){return{current:null}}function ue(e){return e.children}function ot(e,t){this.props=e,this.context=t}function tn(e,t){if(t==null)return e.__?tn(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"?tn(e):null}function Fc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=_t({},t);i.__v=t.__v+1,K.vnode&&K.vnode(i),to(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??tn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Rs(r,i,o),t.__e=t.__=null,i.__e!=n&&Ns(i)}}function Ns(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}),Ns(e)}function eo(e){(!e.__d&&(e.__d=!0)&&Dt.push(e)&&!mr.__r++||Es!=K.debounceRendering)&&((Es=K.debounceRendering)||ys)(mr)}function mr(){try{for(var e,t=1;Dt.length;)Dt.length>t&&Dt.sort(Ss),e=Dt.shift(),t=Dt.length,Fc(e)}finally{Dt.length=mr.__r=0}}function xs(e,t,n,r,o,i,s,a,c,d,h){var u,f,E,p,g,S,m,_=r&&r.__k||hr,y=t.length;for(c=Uc(n,t,_,c,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(f=E.__i!=-1&&_[E.__i]||ur,E.__i=u,S=to(e,E,f,o,i,s,a,c,d,h),p=E.__e,E.ref&&f.ref!=E.ref&&(f.ref&&ro(f.ref,null,E),h.push(E.ref,E.__c||p,E)),g==null&&p!=null&&(g=p),(m=!!(4&E.__u))||f.__k===E.__k?(c=Cs(E,c,e,m),m&&f.__e&&(f.__e=null)):typeof E.type=="function"&&S!==void 0?c=S:p&&(c=p.nextSibling),E.__u&=-7);return n.__e=g,c}function Uc(e,t,n,r,o){var i,s,a,c,d,h=n.length,u=h,f=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]=kn(null,s,null,null,null):Tn(s)?s=e.__k[i]=kn(ue,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=kn(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+f,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=Vc(s,n,c,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?f--:o<h&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=c&&(d==c-1?f--:d==c+1?f++:(d>c?f--:f++,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=tn(a)),As(a,a));return r}function Cs(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=Cs(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=tn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function wt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Tn(e)?e.some(function(n){wt(n,t)}):t.push(e)),t}function Vc(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 Ts(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Lc.test(t)?n:n+"px"}function pr(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||Ts(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ts(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(vs,"$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[Cn]=r[Cn]:(n[Cn]=Xr,e.addEventListener(t,i?Zr:Jr,i)):e.removeEventListener(t,i?Zr:Jr,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 ks(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[dr]==null)t[dr]=Xr++;else if(t[dr]<n[Cn])return;return n(K.event?K.event(t):t)}}}function to(e,t,n,r,o,i,s,a,c,d){var h,u,f,E,p,g,S,m,_,y,k,T,x,N,v,b=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=K.__b)&&h(t);e:if(typeof b=="function")try{if(m=t.props,_=b.prototype&&b.prototype.render,y=(h=b.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?S=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new b(m,k):(t.__c=u=new ot(m,k),u.constructor=b,u.render=zc),y&&y.sub(u),u.state||(u.state={}),u.__n=r,f=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&b.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=_t({},u.__s)),_t(u.__s,b.getDerivedStateFromProps(m,u.__s))),E=u.props,p=u.state,u.__v=t,f)_&&b.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&b.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(R){R&&(R.__=t)}),hr.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,p,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,T=K.__r,x=0,_)u.state=u.__s,u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),hr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++x<25);u.state=u.__s,u.getChildContext!=null&&(r=_t(_t({},r),u.getChildContext())),_&&!f&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(E,p)),N=h!=null&&h.type===ue&&h.key==null?Os(h.props.children):h,a=xs(e,Tn(N)?N:[N],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),S&&(u.__E=u.__=null)}catch(R){if(t.__v=null,c||i!=null)if(R.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(v=i.length;v--;)Qr(i[v]);no(t)}else t.__e=n.__e,t.__k=n.__k,R.then||no(t);K.__e(R,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=jc(n.__e,t,n,r,o,i,s,c,d);return(h=K.diffed)&&h(t),128&t.__u?void 0:a}function no(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(no))}function Rs(e,t,n){for(var r=0;r<n.length;r++)ro(n[r],n[++r],n[++r]);K.__c&&K.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){K.__e(i,o.__v)}})}function Os(e){return typeof e!="object"||e==null||e.__b>0?e:Tn(e)?e.map(Os):e.constructor!==void 0?null:_t({},e)}function jc(e,t,n,r,o,i,s,a,c){var d,h,u,f,E,p,g,S=n.props||ur,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&&(K.__m&&K.__m(t,i),a=!1),i=null}if(_==null)S===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&xn.call(e.childNodes),!a&&i!=null)for(S={},d=0;d<e.attributes.length;d++)S[(E=e.attributes[d]).name]=E.value;for(d in S)E=S[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||pr(e,d,null,E,o);for(d in m)E=m[d],d=="children"?f=E:d=="dangerouslySetInnerHTML"?h=E:d=="value"?p=E:d=="checked"?g=E:a&&typeof E!="function"||S[d]===E||pr(e,d,E,S[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=""),xs(t.type=="template"?e.content:e,Tn(f)?f:[f],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&tn(n,0),a,c),i!=null)for(d=i.length;d--;)Qr(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&p==null?e.removeAttribute("value"):p!=null&&(p!==e[d]||_=="progress"&&!p||_=="option"&&p!=S[d])&&pr(e,d,p,S[d],o),d="checked",g!=null&&g!=e[d]&&pr(e,d,g,S[d],o))}return e}function ro(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){K.__e(o,n)}}function As(e,t,n){var r,o;if(K.unmount&&K.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ro(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){K.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&As(r[o],t,n||typeof e.type!="function");n||Qr(e.__e),e.__c=e.__=e.__e=void 0}function zc(e,t,n){return this.constructor(e,n)}function Rn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),K.__&&K.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],to(t,e=(!r&&n||t).__k=qe(ue,null,[e]),o||ur,ur,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?xn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Rs(i,e,s)}function Is(e,t){Rn(e,t,Is)}function Yc(e,t,n){var r,o,i,s,a=_t({},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?xn.call(arguments,2):n),kn(e.type,a,r||e.key,o||e.ref,null)}function Nt(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,eo(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"+bs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}xn=hr.slice,K={__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}},_s=0,ot.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=_t({},this.state),typeof e=="function"&&(e=e(_t({},n),this.props)),e&&_t(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),eo(this))},ot.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),eo(this))},ot.prototype.render=ue,Dt=[],ys=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ss=function(e,t){return e.__v.__b-t.__v.__b},mr.__r=0,qr=Math.random().toString(8),dr="__d"+qr,Cn="__a"+qr,vs=/(PointerCapture)$|Capture$/i,Xr=0,Jr=ks(!1),Zr=ks(!0),bs=0;var $c=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:--$c,__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 K.vnode&&K.vnode(d),d}var xt,me,oo,Ms,nn=0,Ps=[],we=K,Ds=we.__b,Ls=we.__r,Fs=we.diffed,Us=we.__c,Vs=we.unmount,js=we.__;function Bt(e,t){we.__h&&we.__h(me,e,nn||t),nn=0;var n=me.__H||(me.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function F(e){return nn=1,rn(Ys,e)}function rn(e,t,n){var r=Bt(xt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ys(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=me,!me.__f)){var o=function(a,c,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(f){return f.__c});if(h.every(function(f){return!f.__N}))return!i||i.call(this,a,c,d);var u=r.__c.props!==a;return h.some(function(f){if(f.__N){var E=f.__[0];f.__=f.__N,f.__N=void 0,E!==f.__[0]&&(u=!0)}}),i&&i.call(this,a,c,d)||u};me.__f=!0;var i=me.shouldComponentUpdate,s=me.componentWillUpdate;me.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)},me.shouldComponentUpdate=o}return r.__N||r.__}function Y(e,t){var n=Bt(xt++,3);!we.__s&&co(n.__H,t)&&(n.__=e,n.u=t,me.__H.__h.push(n))}function dt(e,t){var n=Bt(xt++,4);!we.__s&&co(n.__H,t)&&(n.__=e,n.u=t,me.__h.push(n))}function q(e){return nn=5,ye(function(){return{current:e}},[])}function so(e,t,n){nn=6,dt(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 ye(e,t){var n=Bt(xt++,7);return co(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function fe(e,t){return nn=8,ye(function(){return e},t)}function Ct(e){var t=me.context[e.__c],n=Bt(xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(me)),t.props.value):e.__}function io(e,t){we.useDebugValue&&we.useDebugValue(t?t(e):e)}function Hc(e){var t=Bt(xt++,10),n=F();return t.__=e,me.componentDidCatch||(me.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function ao(){var e=Bt(xt++,11);if(!e.__){for(var t=me.__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 Bc(){for(var e;e=Ps.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(fr),t.__h.some(lo),t.__h=[]}catch(n){t.__h=[],we.__e(n,e.__v)}}}we.__b=function(e){me=null,Ds&&Ds(e)},we.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),js&&js(e,t)},we.__r=function(e){Ls&&Ls(e),xt=0;var t=(me=e.__c).__H;t&&(oo===me?(t.__h=[],me.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(fr),t.__h.some(lo),t.__h=[],xt=0)),oo=me},we.diffed=function(e){Fs&&Fs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ps.push(t)!==1&&Ms===we.requestAnimationFrame||((Ms=we.requestAnimationFrame)||Gc)(Bc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),oo=me=null},we.__c=function(e,t){t.some(function(n){try{n.__h.some(fr),n.__h=n.__h.filter(function(r){return!r.__||lo(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],we.__e(r,n.__v)}}),Us&&Us(e,t)},we.unmount=function(e){Vs&&Vs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{fr(r)}catch(o){t=o}}),n.__H=void 0,t&&we.__e(t,n.__v))};var zs=typeof requestAnimationFrame=="function";function Gc(e){var t,n=function(){clearTimeout(r),zs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);zs&&(t=requestAnimationFrame(n))}function fr(e){var t=me,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),me=t}function lo(e){var t=me;e.__c=e.__(),me=t}function co(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Ys(e,t){return typeof t=="function"?t(e):t}function $s(e,t){for(var n in t)e[n]=t[n];return e}function uo(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 ho(e,t){var n=t(),r=F({t:{__:n,u:t}}),o=r[0].t,i=r[1];return dt(function(){o.__=n,o.u=t,mo(o)&&i({t:o})},[e,n,t]),Y(function(){return mo(o)&&i({t:o}),e(function(){mo(o)&&i({t:o})})},[e]),n}function mo(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 po(e){e()}function fo(e){return e}function go(){return[!1,po]}var _o=dt;function gr(e,t){this.props=e,this.context=t}function Eo(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:uo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,qe(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(gr.prototype=new ot).isPureReactComponent=!0,gr.prototype.shouldComponentUpdate=function(e,t){return uo(this.props,e)||uo(this.state,t)};var Hs=K.__b;K.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Hs&&Hs(e)};var Wc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Q(e){function t(n){var r=$s({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Wc,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Bs=function(e,t){return e==null?null:wt(wt(e).map(t))},et={map:Bs,forEach:Bs,count:function(e){return e?wt(e).length:0},only:function(e){var t=wt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:wt},Kc=K.__e;K.__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)}Kc(e,t,n,r)};var Gs=K.unmount;function Ws(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=$s({},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 Ws(r,t,n)})),e}function Ks(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ks(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 He(){this.__u=0,this.o=null,this.__b=null}function qs(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Xe(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?qe(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function on(){this.i=null,this.l=null}K.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Gs&&Gs(e)},(He.prototype=new ot).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=qs(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]=Ks(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)},He.prototype.componentWillUnmount=function(){this.o=[]},He.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]=Ws(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&qe(ue,null,e.fallback);return o&&(o.__u&=-33),[qe(ue,null,t.__a?null:e.children),o]};var Xs=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 qc(e){return this.getChildContext=function(){return e.context},e.children}function Xc(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Rn(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)}}}Rn(qe(qc,{context:t.context},e.__v),t.v)}function Js(e,t){var n=qe(Xc,{__v:e,h:t});return n.containerInfo=t,n}(on.prototype=new ot).__a=function(e){var t=this,n=qs(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Xs(t,e,r)):o()};n?n(i):i()}},on.prototype.render=function(e){this.i=null,this.l=new Map;var t=wt(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},on.prototype.componentDidUpdate=on.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Xs(e,n,t)})};var Zs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Jc=/^(?: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]/,Zc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Qc=/[A-Z0-9]/g,ed=typeof document<"u",td=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function yo(e,t,n){return t.__k==null&&(t.textContent=""),Rn(e,t),typeof n=="function"&&n(),e?e.__c:null}function Qs(e,t,n){return Is(e,t),typeof n=="function"&&n(),e?e.__c:null}ot.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(ot.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ei=K.event;K.event=function(e){return ei&&(e=ei(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var So,nd={configurable:!0,get:function(){return this.class}},ti=K.vnode;K.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||ed&&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"||td(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":Zc.test(s)&&(s=c):c=s="oninput":i&&Jc.test(s)?s=s.replace(Qc,"-$&").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=wt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=wt(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",nd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=Zs,ti&&ti(e)};var ni=K.__r;K.__r=function(e){ni&&ni(e),So=e.__c};var ri=K.diffed;K.diffed=function(e){ri&&ri(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),So=null};var oi={ReactCurrentDispatcher:{current:{readContext:function(e){return So.__n[e.__c].props.value},useCallback:fe,useContext:Ct,useDebugValue:io,useDeferredValue:fo,useEffect:Y,useId:ao,useImperativeHandle:so,useInsertionEffect:_o,useLayoutEffect:dt,useMemo:ye,useReducer:rn,useRef:q,useState:F,useSyncExternalStore:ho,useTransition:go}}},rd="18.3.1";function si(e){return qe.bind(null,e)}function tt(e){return!!e&&e.$$typeof===Zs}function ii(e){return tt(e)&&e.type===ue}function ai(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Lt(e){return tt(e)?Yc.apply(null,arguments):e}function vo(e){return!!e.__k&&(Rn(null,e),!0)}function li(e){return e&&(e.base||e.nodeType===1&&e)||null}var ci=function(e,t){return e(t)},di=function(e,t){var n=K.debounceRendering;K.debounceRendering=function(o){return o()};var r=e(t);return K.debounceRendering=n,r},ui=tt,On={useState:F,useId:ao,useReducer:rn,useEffect:Y,useLayoutEffect:dt,useInsertionEffect:_o,useTransition:go,useDeferredValue:fo,useSyncExternalStore:ho,startTransition:po,useRef:q,useImperativeHandle:so,useMemo:ye,useCallback:fe,useContext:Ct,useDebugValue:io,version:"18.3.1",Children:et,render:yo,hydrate:Qs,unmountComponentAtNode:vo,createPortal:Js,createElement:qe,createContext:Nt,createFactory:si,cloneElement:Lt,createRef:ws,Fragment:ue,isValidElement:tt,isElement:ui,isFragment:ii,isMemo:ai,findDOMNode:li,Component:ot,PureComponent:gr,memo:Eo,forwardRef:Q,flushSync:di,unstable_batchedUpdates:ci,StrictMode:ue,Suspense:He,SuspenseList:on,lazy:Xe,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:oi};const bo=Object.freeze(Object.defineProperty({__proto__:null,Children:et,Component:ot,Fragment:ue,PureComponent:gr,StrictMode:ue,Suspense:He,SuspenseList:on,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:oi,cloneElement:Lt,createContext:Nt,createElement:qe,createFactory:si,createPortal:Js,createRef:ws,default:On,findDOMNode:li,flushSync:di,forwardRef:Q,hydrate:Qs,isElement:ui,isFragment:ii,isMemo:ai,isValidElement:tt,lazy:Xe,memo:Eo,render:yo,startTransition:po,unmountComponentAtNode:vo,unstable_batchedUpdates:ci,useCallback:fe,useContext:Ct,useDebugValue:io,useDeferredValue:fo,useEffect:Y,useErrorBoundary:Hc,useId:ao,useImperativeHandle:so,useInsertionEffect:_o,useLayoutEffect:dt,useMemo:ye,useReducer:rn,useRef:q,useState:F,useSyncExternalStore:ho,useTransition:go,version:rd},Symbol.toStringTag,{value:"Module"}));function od(e){return{render:function(t){yo(t,e)},unmount:function(){vo(e)}}}function hi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function wo(...e){return t=>{let n=!1;const r=e.map(o=>{const i=hi(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():hi(e[o],null)}}}}function Ft(...e){return fe(wo(...e),e)}function sd(e){const t=id(e),n=Q((r,o)=>{const{children:i,...s}=r,a=et.toArray(i),c=a.find(ld);if(c){const d=c.props.children,h=a.map(u=>u===c?et.count(d)>1?et.only(null):tt(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:tt(d)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function id(e){const t=Q((n,r)=>{const{children:o,...i}=n;if(tt(o)){const s=dd(o),a=cd(i,o.props);return o.type!==ue&&(a.ref=r?wo(r,s):s),Lt(o,a)}return et.count(o)>1?et.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ad=Symbol("radix.slottable");function ld(e){return tt(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ad}function cd(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 dd(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 ud=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],sn=ud.reduce((e,t)=>{const n=sd(`Primitive.${t}`),r=Q((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}},{}),Gt=globalThis?.document?dt:()=>{};function hd(e,t){return rn((n,r)=>t[n][r]??n,e)}var an=e=>{const{present:t,children:n}=e,r=md(t),o=typeof n=="function"?n({present:r.isPresent}):et.only(n),i=Ft(r.ref,pd(o));return typeof n=="function"||r.isPresent?Lt(o,{ref:i}):null};an.displayName="Presence";function md(e){const[t,n]=F(),r=q(null),o=q(e),i=q("none"),s=e?"mounted":"unmounted",[a,c]=hd(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Y(()=>{const d=_r(r.current);i.current=a==="mounted"?d:"none"},[a]),Gt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,f=_r(d);e?c("MOUNT"):f==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Gt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const p=_r(r.current).includes(CSS.escape(E.animationName));if(E.target===t&&p&&(c("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},f=E=>{E.target===t&&(i.current=_r(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:fe(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function _r(e){return e?.animationName||"none"}function pd(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 mi(e,t=[]){let n=[];function r(i,s){const a=Nt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,S=ye(()=>p,Object.values(p));return l(g.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;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=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,fd(o,...t)]}function fd(...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 ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Ut(e){const t=q(e);return Y(()=>{t.current=e}),ye(()=>(...n)=>t.current?.(...n),[])}var gd=Nt(void 0);function _d(e){const t=Ct(gd);return e||t||"ltr"}function Ed(e,[t,n]){return Math.min(n,Math.max(t,e))}function Vt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function yd(e,t){return rn((n,r)=>t[n][r]??n,e)}var No="ScrollArea",[pi]=mi(No),[Sd,st]=pi(No),fi=Q((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=F(null),[d,h]=F(null),[u,f]=F(null),[E,p]=F(null),[g,S]=F(null),[m,_]=F(0),[y,k]=F(0),[T,x]=F(!1),[N,v]=F(!1),b=Ft(t,A=>c(A)),R=_d(o);return l(Sd,{scope:n,type:r,dir:R,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:f,scrollbarX:E,onScrollbarXChange:p,scrollbarXEnabled:T,onScrollbarXEnabledChange:x,scrollbarY:g,onScrollbarYChange:S,scrollbarYEnabled:N,onScrollbarYEnabledChange:v,onCornerWidthChange:_,onCornerHeightChange:k,children:l(sn.div,{dir:R,...s,ref:b,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});fi.displayName=No;var gi="ScrollAreaViewport",_i=Q((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=st(gi,n),a=q(null),c=Ft(t,a,s.onViewportChange);return l(ue,{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(sn.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})})]})});_i.displayName=gi;var Et="ScrollAreaScrollbar",xo=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return Y(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?l(vd,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(bd,{...r,ref:t,forceMount:n}):o.type==="auto"?l(Ei,{...r,ref:t,forceMount:n}):o.type==="always"?l(Co,{...r,ref:t}):null});xo.displayName=Et;var vd=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),[i,s]=F(!1);return Y(()=>{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(an,{present:n||i,children:l(Ei,{"data-state":i?"visible":"hidden",...r,ref:t})})}),bd=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),i=e.orientation==="horizontal",s=vr(()=>c("SCROLL_END"),100),[a,c]=yd("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 Y(()=>{if(a==="idle"){const d=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,c]),Y(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const f=()=>{const E=d[h];u!==E&&(c("SCROLL"),s()),u=E};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,c,s]),l(an,{present:n||a!=="hidden",children:l(Co,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Vt(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Vt(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Ei=Q((e,t)=>{const n=st(Et,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=F(!1),a=e.orientation==="horizontal",c=vr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return ln(n.viewport,c),ln(n.content,c),l(an,{present:r||i,children:l(Co,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Co=Q((e,t)=>{const{orientation:n="vertical",...r}=e,o=st(Et,e.__scopeScrollArea),i=q(null),s=q(0),[a,c]=F({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=wi(a.viewport,a.content),h={...r,sizes:a,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function u(f,E){return kd(f,s.current,a,E)}return n==="horizontal"?l(wd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,E=Ni(f,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=u(f,o.dir))}}):n==="vertical"?l(Nd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,E=Ni(f,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=u(f))}}):null}),wd=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(Et,e.__scopeScrollArea),[s,a]=F(),c=q(null),d=Ft(t,c,i.onScrollbarXChange);return Y(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Si,{"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":Sr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(f),Ci(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:yr(s.paddingLeft),paddingEnd:yr(s.paddingRight)}})}})}),Nd=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(Et,e.__scopeScrollArea),[s,a]=F(),c=q(null),d=Ft(t,c,i.onScrollbarYChange);return Y(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Si,{"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":Sr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(f),Ci(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:yr(s.paddingTop),paddingEnd:yr(s.paddingBottom)}})}})}),[xd,yi]=pi(Et),Si=Q((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:u,...f}=e,E=st(Et,n),[p,g]=F(null),S=Ft(t,b=>g(b)),m=q(null),_=q(""),y=E.viewport,k=r.content-r.viewport,T=Ut(h),x=Ut(c),N=vr(u,10);function v(b){if(m.current){const R=b.clientX-m.current.left,A=b.clientY-m.current.top;d({x:R,y:A})}}return Y(()=>{const b=R=>{const A=R.target;p?.contains(A)&&T(R,k)};return document.addEventListener("wheel",b,{passive:!1}),()=>document.removeEventListener("wheel",b,{passive:!1})},[y,p,k,T]),Y(x,[r,x]),ln(p,N),ln(E.content,N),l(xd,{scope:n,scrollbar:p,hasThumb:o,onThumbChange:Ut(i),onThumbPointerUp:Ut(s),onThumbPositionChange:x,onThumbPointerDown:Ut(a),children:l(sn.div,{...f,ref:S,style:{position:"absolute",...f.style},onPointerDown:Vt(e.onPointerDown,b=>{b.button===0&&(b.target.setPointerCapture(b.pointerId),m.current=p.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),v(b))}),onPointerMove:Vt(e.onPointerMove,v),onPointerUp:Vt(e.onPointerUp,b=>{const R=b.target;R.hasPointerCapture(b.pointerId)&&R.releasePointerCapture(b.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Er="ScrollAreaThumb",vi=Q((e,t)=>{const{forceMount:n,...r}=e,o=yi(Er,e.__scopeScrollArea);return l(an,{present:n||o.hasThumb,children:l(Cd,{ref:t,...r})})}),Cd=Q((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=st(Er,n),s=yi(Er,n),{onThumbPositionChange:a}=s,c=Ft(t,u=>s.onThumbChange(u)),d=q(void 0),h=vr(()=>{d.current&&(d.current(),d.current=void 0)},100);return Y(()=>{const u=i.viewport;if(u){const f=()=>{if(h(),!d.current){const E=Rd(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,h,a]),l(sn.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:Vt(e.onPointerDownCapture,u=>{const f=u.target.getBoundingClientRect(),E=u.clientX-f.left,p=u.clientY-f.top;s.onThumbPointerDown({x:E,y:p})}),onPointerUp:Vt(e.onPointerUp,s.onThumbPointerUp)})});vi.displayName=Er;var To="ScrollAreaCorner",bi=Q((e,t)=>{const n=st(To,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(Td,{...e,ref:t}):null});bi.displayName=To;var Td=Q((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=st(To,n),[i,s]=F(0),[a,c]=F(0),d=!!(i&&a);return ln(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),ln(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(sn.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 yr(e){return e?parseInt(e,10):0}function wi(e,t){const n=e/t;return isNaN(n)?0:n}function Sr(e){const t=wi(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function kd(e,t,n,r="ltr"){const o=Sr(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 xi([c,d],u)(e)}function Ni(e,t,n="ltr"){const r=Sr(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=Ed(e,c);return xi([0,s],[0,a])(d)}function xi(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 Ci(e,t){return e>0&&e<t}var Rd=(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 vr(e,t){const n=Ut(e),r=q(0);return Y(()=>()=>window.clearTimeout(r.current),[]),fe(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ln(e,t){const n=Ut(t);Gt(()=>{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 Ti=fi,Od=_i,Ad=bi;function Id(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 cn={},An={},ki={},In={},Mn={},Pn={},Ri;function ko(){if(Ri)return Pn;Ri=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.EventEmitter=void 0;let e=class{constructor(){O(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 Pn.EventEmitter=e,Pn}var dn={},Oi;function Dn(){return Oi||(Oi=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.DisconnectionReason=dn.ConnectionStatus=void 0,dn.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},dn.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"}),dn}var Ai;function Ro(){if(Ai)return Mn;Ai=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.BaseConnection=void 0;const e=ko(),t=Dn();let n=class{constructor(){O(this,"status",t.ConnectionStatus.CONNECTING);O(this,"queue",[]);O(this,"eventEmitter",new e.EventEmitter);O(this,"disconnectionDetails",null);O(this,"onErrorCallback",null);O(this,"onDisconnectCallback",null);O(this,"onMessageCallback",null);O(this,"onOpenCallback",null);O(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 Mn.BaseConnection=n,Mn}var Ii={},Mi;function nt(){return Mi||(Mi=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=T,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(v,b=e.SynapseErrorCode.UNKNOWN,R={}){super(v);O(this,"code");O(this,"timestamp");O(this,"cause");O(this,"context");O(this,"hint");O(this,"displayMessage");O(this,"reason");this.name="SynapseError",this.code=b,this.timestamp=new Date,this.cause=R.cause,this.context=R.context,this.hint=R.hint,this.reason=R.reason,this.displayMessage=R.displayMessage||R?.hint||v,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(v,b,R,A){const $=n.makeMessage(b,R,v);super($,e.SynapseErrorCode.API,{cause:R,context:{status:b,hasBody:!!R},hint:b&&b>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:v||"Something went wrong"});O(this,"status");O(this,"error");O(this,"headers");this.name="APIError",this.status=b,this.error=R,this.headers=A}static makeMessage(v,b,R){const A=b instanceof Error?b.message:R;return v&&A?`HTTP ${v}: ${A}`:v?`${v} status code (no body)`:A||"(no status code or body)"}static generate(v,b,R,A){if(!v)return new r({message:R});const $=b?.error,J=$&&typeof $=="object"&&!Array.isArray($)?$:void 0;switch(v){case 400:return new i(R||"Bad Request",v,J,A);case 401:return new s(R||"Unauthorized",v,J,A);case 403:return new a(R||"Permission Denied",v,J,A);case 404:return new c(R||"Not Found",v,J,A);case 405:return new d(R||"Method Not Allowed",v,J,A);case 429:return new h(R||"Rate Limit Exceeded",v,J,A);case 500:return new u(R||"Internal Server Error",v,J,A);default:return new n(R||"API Error",v,J,A)}}}e.APIError=n;class r extends n{constructor({message:N}={}){super(N||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:N}={}){super(N||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="InternalServerError"}}e.InternalServerError=u;class f extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.CONNECTION,v),this.name="ConnectionError"}}e.ConnectionError=f;class E extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.RECORDING,v),this.name="RecordingError"}}e.RecordingError=E;class p extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.AUTH,v),this.name="AuthenticationError"}}e.AuthenticationError=p;class g extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.FILE,v),this.name="FileError"}}e.FileError=g;class S extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.SESSION,v),this.name="SessionError"}}e.SessionError=S;class m extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.MESSAGE,v),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.STORE,v),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.CONFIGURATION,v),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.VALIDATION,v),this.name="ValidationError"}}e.ValidationError=k;function T(x,N,v,b={}){if(x instanceof N)return x;const R={...b,context:{...x instanceof t?x.context:void 0,...b.context},hint:b.hint??(x instanceof t?x.hint:void 0),reason:b.reason??(x instanceof t?x.reason:void 0),cause:b.cause??x};if(x instanceof t)return new N(x.message,R);const A=x instanceof Error&&x.message?x.message:v;return new N(A,R)}})(Ii)),Ii}var Pi;function Di(){if(Pi)return In;Pi=1,Object.defineProperty(In,"__esModule",{value:!0}),In.WebSocketConnection=void 0;const e=Ro(),t=Dn(),n=nt();class r extends e.BaseConnection{constructor(s){super();O(this,"conversationId");O(this,"socket",null);O(this,"config");O(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 In.WebSocketConnection=r,In}var Ln={},Li={},Fi;function Ui(){return Fi||(Fi=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})(Li)),Li}var Vi;function ji(){if(Vi)return Ln;Vi=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.SSEConnection=void 0;const e=Ro(),t=Dn(),n=Ui(),r=nt();class o extends e.BaseConnection{constructor(a){super();O(this,"conversationId");O(this,"config");O(this,"connected",!1);O(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 p=await this.config.auth.onUnauthorized();if(c.signal.aborted)return;p&&(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(),f=new TextDecoder;let E="";for(;;){const{done:p,value:g}=await u.read();if(p)break;E+=f.decode(g,{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 f=JSON.parse(u);this.handleMessage(f)}catch(f){const E=(0,r.normalizeError)(f,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 f=c;f<a.length;f++){const E=a[f];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 f}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 Ln.SSEConnection=o,Ln}var zi;function Yi(){return zi||(zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Di(),n=ji(),r=nt();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})(ki)),ki}var Fn={},$i;function Oo(){if($i)return Fn;$i=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.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 Fn.getConfig=r,Fn}var Un={},Vn={},Hi;function br(){if(Hi)return Vn;Hi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.HttpClient=void 0;const e=nt();let t=class{constructor(n){O(this,"baseUrl");O(this,"headers");O(this,"timeout");O(this,"maxRetries");O(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 Vn.HttpClient=t,Vn}var jn={},zn={},Bi;function Yn(){if(Bi)return zn;Bi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.BaseResource=void 0;let e=class{constructor(t){O(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 zn.BaseResource=e,zn}var Gi;function Wi(){if(Gi)return jn;Gi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.Session=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(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 jn.Session=t,jn}var $n={},Ki;function Ao(){if(Ki)return $n;Ki=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.Config=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(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 $n.Config=t,$n}var qi={},Xi;function Ji(){return Xi||(Xi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=br(),n=Oo(),r=Ao(),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 f=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(f).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}})(qi)),qi}var Hn={},Zi;function Io(){if(Zi)return Hn;Zi=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.Auth=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(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 Hn.Auth=t,Hn}var Bn={},un={},Qi;function Mo(){return Qi||(Qi=1,Object.defineProperty(un,"__esModule",{value:!0}),un.ErrorType=un.SYNAPSE_RECOVERY_REASON=void 0,un.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},un.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"}),un}var Gn={},ea;function Po(){if(ea)return Gn;ea=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.ErrorUtils=void 0;const e=nt();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 Gn.ErrorUtils=t,Gn}var ta={},na;function ra(){return na||(na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=br(),n=Oo(),r=Po(),o=Io(),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),f=i.get(u);if(f)return f;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}`}}}),p=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return p.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===p&&i.delete(u)}),i.set(u,p),p}function c(d){const h=i.get(d);return h&&i.delete(d),h}})(ta)),ta}var oa;function Md(){if(oa)return Bn;oa=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.TokenManager=void 0;const e=nt(),t=Mo(),n=Po(),r=ra();let o=class{constructor(i,s,a,c){O(this,"auth");O(this,"httpClient");O(this,"agentId");O(this,"partnerAuthToken");O(this,"refreshToken");O(this,"sessToken");O(this,"_userId");O(this,"_level");O(this,"_expiresAt");O(this,"lastResponse");O(this,"initPromise",null);O(this,"refreshPromise",null);O(this,"prefetchKey");O(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 Bn.TokenManager=o,Bn}var Wn={},sa;function Pd(){var n;if(sa)return Wn;sa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.VoiceResource=void 0;const e=Yn();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)}},O(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),O(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Wn.VoiceResource=t,Wn}var ia;function aa(){if(ia)return Un;ia=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.ResourceManager=void 0;const e=br(),t=Wi(),n=nt(),r=Ao(),o=Ji(),i=Io(),s=Md(),a=Pd();class c{constructor(h){O(this,"resourceConfig");O(this,"httpClient");O(this,"session");O(this,"config");O(this,"auth");O(this,"tokenManager");O(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:f,intent:E,user_location:p,referer:g,...S}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...f&&{user_context:f},...(E||Object.keys(S).length>0)&&{session_context:{...E&&{intent:E},...p&&{user_location:p},...S}},...g&&{referer:g}},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(f){throw f instanceof n.APIError?f: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:f,feedbacks:E,feedbackReason:p,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:f,feedbacks:E,feedbackReason:p,npsBase5:g})}async callTool(h,u,f,E){return await this.session.callTool(h,u,f,E)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Un.ResourceManager=c,Un}var Kn={},la={},ca;function Do(){return ca||(ca=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)}})(la)),la}var da={},ua;function Dd(){return ua||(ua=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=nt();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){O(this,"pendingFiles",[]);O(this,"pendingMessage","");O(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})(da)),da}var ut={},ha;function wr(){if(ha)return ut;ha=1,Object.defineProperty(ut,"__esModule",{value:!0}),ut.SYNAPSE_REALTIME_RESERVED_EVENTS=ut.SYNAPSE_REALTIME_ERROR_CODES=ut.SYNAPSE_REALTIME_EVENTS=ut.SYNAPSE_MESSAGE_TYPES=void 0;const e=Do();return ut.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,ut.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"},ut.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"},ut.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},ut}var qn={},ma;function Ld(){if(ma)return qn;ma=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.AudioManager=void 0;const e=nt();class t{constructor(r={}){O(this,"mediaRecorder",null);O(this,"mediaStream",null);O(this,"recordingStartTime",0);O(this,"autoPauseTimer",null);O(this,"config");O(this,"onAudioData",null);O(this,"onAudioError",null);O(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 qn.AudioManager=t,qn}var pa;function fa(){if(pa)return Kn;pa=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.MessageManager=void 0;const e=Do(),t=Dd(),n=wr(),r=Ld(),o=nt();let i=class{constructor(s){O(this,"connection",null);O(this,"callbacks",null);O(this,"fileManager",null);O(this,"audioManager",null);O(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 f=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,...f&&{text:f},...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:f,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},...f&&{tool_result:f},...E&&{initial_prompts:E}};return}const p=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const S=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:f})}else s?g={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},...f&&{tool_result:f}}}:c&&c?.audio&&c?.format?g={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},...f&&{tool_result:f}}}:f&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:f}});if(!g){const S=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}p.sendMessage(g)}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 Kn.MessageManager=i,Kn}var ga={},_a;function Fd(){return _a||(_a=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})(ga)),ga}var Xn={},Jn={},Ea;function Ud(){if(Ea)return Jn;Ea=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){O(this,"audioCtx",null);O(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 Jn.VoiceAudioAnalyser=t,Jn}var hn={},ya;function Sa(){return ya||(ya=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.VOICE_AGENT_EVENTS=hn.VOICE_AGENT_STATE=void 0,hn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},hn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),hn}var va;function Vd(){if(va)return Xn;va=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.VoiceAgent=void 0;const e=ko(),t=Ud(),n=nt(),r=Sa(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(f=>{if(h.iceGatheringState==="complete"){f();return}const E=setTimeout(f,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),f())}})}let d=class{constructor(h,u,f){O(this,"config");O(this,"resourceManager");O(this,"getCredentials");O(this,"emitter",new e.EventEmitter);O(this,"remoteAnalyser",new t.VoiceAudioAnalyser);O(this,"localAnalyser",new t.VoiceAudioAnalyser);O(this,"pc",null);O(this,"pcId",null);O(this,"dataChannel",null);O(this,"localStream",null);O(this,"remoteAudio",null);O(this,"_state",r.VOICE_AGENT_STATE.IDLE);O(this,"_isMuted",!1);O(this,"manuallyDisconnected",!1);O(this,"_hasConnectionFailureNotified",!1);O(this,"_userSpeaking",!1);O(this,"_silenceTimer",null);O(this,"_cachedIceServers",null);O(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=f}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 f=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:f,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 p=await E.createOffer();await E.setLocalDescription(p);const g=this.config.iceGatheringTimeoutMs??o;await c(E,g);const S=_=>({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(S(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(S(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(f=>{f.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 f;try{f=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const p=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(p.sessionId)}else throw E}if(!Array.isArray(f?.ice_servers)||f.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=f.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 f={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,f)}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,f=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(f?(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 f=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,f,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 Xn.VoiceAgent=d,Xn}var ba;function jd(){if(ba)return An;ba=1,Object.defineProperty(An,"__esModule",{value:!0}),An.SynapseSDK=void 0;const e=Yi(),t=Dn(),n=Oo(),r=aa(),o=fa(),i=wr(),s=ko(),a=nt(),c=Mo(),d=Fd(),h=Do(),u=Vd();class f{constructor(p){O(this,"connection",null);O(this,"messageManager");O(this,"resourceManager");O(this,"sessionConfig",null);O(this,"config");O(this,"connectionType");O(this,"isRefreshingSession",!1);O(this,"isRecovering",!1);O(this,"forceConsumed",!1);O(this,"connectionAttempts",0);O(this,"sdkEventEmitter",new s.EventEmitter);O(this,"_voice",null);O(this,"pendingNetworkReconnect",!1);O(this,"boundOnlineHandler",null);O(this,"isReconnecting",!1);O(this,"reconnectTimer",null);O(this,"boundVisibilityHandler",null);O(this,"isSessionNotOwned",!1);this.config={...p,environment:p.environment||"production"},this.connectionType=p.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...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:S=>this.config.callbacks?.onTokenExchange?.(S)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const p=await this.resourceManager.refreshBearer();if(!p)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(g){this.emitError(this.toConnectionError(g,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return p}async startSession(p){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,p=void 0),await this.resourceManager.ensureCredentials();const g=p?.session_id?p:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:p,files:g,audio:S,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:p,files:g,audio:S,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(x){this.emitError(x)}break;default:const T=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(T),T}}async sendMessageFeedback(p,g,S){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:p,feedback:g,feedbackReason:S});break}}async sendSessionFeedback(p,g){if(!this.connection){const S=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(S),S}if(!this.sessionConfig?.session_id){const S=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(S),S}if(!p?.length&&!g){const S=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(S),S}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:p,npsBase5:g});break}}on(p,g){this.sdkEventEmitter.on(p,g)}off(p,g){this.sdkEventEmitter.off(p,g)}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(p){return await this.resourceManager.getSessionMessages(p)}async callTool(p,g,S){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,p,g,S);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:p,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:p,onError:g})}catch(m){throw m}break;default:const S=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(S),S}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const p=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(p),p}}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(p){if(p instanceof a.APIError){const g=p.reason??(p.status===401||p.status===403?c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:p.error?.msg||p.message,error:p.error,code:p.code,...g&&{reason:g},status:p.status,context:p.context}}return p instanceof a.SynapseError?{message:p.displayMessage||p.message,code:p.code,...p.reason&&{reason:p.reason},context:p.context}:p instanceof Error?{message:p.message}:{message:"An unexpected error occurred"}}emitError(p){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(p))}toSessionError(p,g,S,m){return(0,a.normalizeError)(p,a.SessionError,g,{context:S,hint:m})}async initializeConnection(p){if(this.closeConnection(),!p.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=p;const g=(0,n.getConfig)(this.config?.environment),S=this.connectionType===e.ConnectionType.SOCKET,m=S?g.WEBSOCKET_URL:g.BASE_API_URL,_=this.config.serverUrl?S?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:_||m,auth:{sessionId:p.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,...T)=>{y(k,...T),this.sdkEventEmitter.emit(k,...T)}}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(g=>{this.onIncomingSocketMessage(g)}),this.connection.onError(g=>{this.onRealtimeConnectionError(g)}),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 p=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==p||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const S=(0,d.outcomeForCloseCode)(g.code);if(S){await this.handleRecovery(S,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(p){if(p instanceof a.APIError){const S=(0,d.outcomeForHttpStatus)(p.status);if(S){this.handleRecovery(S,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:p.message,code:p.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,p);const g=p instanceof a.APIError?p:this.toConnectionError(p,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const p=this.resourceManager.getSessToken();if(!p){const g=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(g),g}this.messageManager.sendSocketAuthMessage(p)}onIncomingSocketMessage(p){switch(p.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(p);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(p);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(p);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(p);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:p.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const p=this.resourceManager.getLevel();return p?p==="user":!!this.config.authToken}statusOf(p){if(p instanceof a.APIError)return p.status;if(p instanceof a.SynapseError&&typeof p.context?.status=="number")return p.context.status}emitRecoveryError(p,g,S){this.emitError(new a.SessionError(g,{reason:p,cause:S,context:{stage:"connectionRecovery",reason:p}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(p,g){if(p===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(p){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(p){const g=this.statusOf(p);if(g!==403&&g!==401){this.emitError(this.toSessionError(p,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",p)}}async recoverMissingSession(){const p=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!p){this.closeConnection(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(p);await this.connectTo(g);return}catch(g){const S=this.statusOf(g);if(S===401||S===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);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(p){await this.initializeConnection(p),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(p,g,S,m){return(0,a.normalizeError)(p,a.ConnectionError,g,{context:S,hint:m})}scheduleReconnect(p){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(p);return}const g=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(p)}}},g)}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 An.SynapseSDK=f,An}var wa={},Na;function zd(){return Na||(Na=1,Object.defineProperty(wa,"__esModule",{value:!0})),wa}var Nr={},xa;function Yd(){return xa||(xa=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.USER_FEEDBACK=void 0,Nr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Nr}var Ca={},Ta;function $d(){return Ta||(Ta=1,Object.defineProperty(Ca,"__esModule",{value:!0})),Ca}var Zn={},ka;function Hd(){if(ka)return Zn;ka=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.ToolCall=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(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 Zn.ToolCall=t,Zn}var Be={},Ra;function Bd(){if(Ra)return Be;Ra=1,Object.defineProperty(Be,"__esModule",{value:!0}),Be.SYNAPSE_EICITATION_STATUS=Be.SYNAPSE_CTA_ACTIONS=Be.SYNAPSE_TOOL_FORMATS=Be.SYNAPSE_TOOL_CALLBACK_NAME=Be.SYNAPSE_COMPONENTS=Be.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||(Be.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||(Be.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||(Be.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Be.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Be.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Be.SYNAPSE_EICITATION_STATUS=i={})),Be}var Oa={},Aa;function Gd(){return Aa||(Aa=1,Object.defineProperty(Oa,"__esModule",{value:!0})),Oa}var Ia={},Ma;function Wd(){return Ma||(Ma=1,Object.defineProperty(Ia,"__esModule",{value:!0})),Ia}var Qn={},Pa;function Kd(){if(Pa)return Qn;Pa=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(Qn.SYNAPSE_CONVERSATION=e={})),Qn}var mn={},Da;function qd(){return Da||(Da=1,(function(e){var t=mn&&mn.__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=mn&&mn.__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(Sa(),e)})(mn)),mn}var La;function Xd(){return La||(La=1,(function(e){var t=cn&&cn.__createBinding||(Object.create?(function(x,N,v,b){b===void 0&&(b=v);var R=Object.getOwnPropertyDescriptor(N,v);(!R||("get"in R?!N.__esModule:R.writable||R.configurable))&&(R={enumerable:!0,get:function(){return N[v]}}),Object.defineProperty(x,b,R)}):(function(x,N,v,b){b===void 0&&(b=v),x[b]=N[v]})),n=cn&&cn.__exportStar||function(x,N){for(var v in x)v!=="default"&&!Object.prototype.hasOwnProperty.call(N,v)&&t(N,x,v)};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=jd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Ro();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Di();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=ji();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Yi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Dn(),e);var c=aa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(zd(),e);var d=Wi();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(Yd(),e);var h=Io();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=ra();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n($d(),e);var f=Ao();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var E=Ji();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var p=Hd();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return p.ToolCall}}),n(Bd(),e);var g=fa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(wr(),e),n(Gd(),e);var S=br();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return S.HttpClient}});var m=nt();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 _=Mo();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=Po();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(Wd(),e);var k=Ui();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 T=wr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return T.SYNAPSE_MESSAGE_TYPES}}),n(Kd(),e),n(qd(),e)})(cn)),cn}var I=Xd();function Fa(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=Fa(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ua(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Fa(e))&&(r&&(r+=" "),r+=t);return r}const Jd=(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},Zd=(e,t)=>({classGroupId:e,validator:t}),Va=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),xr="-",ja=[],Qd="arbitrary..",eu=e=>{const t=nu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return tu(o);const i=o.split(xr),s=i[0]===""&&i.length>1?1:0;return za(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?Jd(a,s):s:a||ja}return n[o]||ja}}},za=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=za(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(xr):e.slice(t).join(xr),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},tu=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?Qd+r:void 0})(),nu=e=>{const{theme:t,classGroups:n}=e;return ru(n,t)},ru=(e,t)=>{const n=Va();for(const r in e){const o=e[r];Lo(o,n,r,t)}return n},Lo=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];ou(s,t,n,r)}},ou=(e,t,n,r)=>{if(typeof e=="string"){su(e,t,n);return}if(typeof e=="function"){iu(e,t,n,r);return}au(e,t,n,r)},su=(e,t,n)=>{const r=e===""?t:Ya(t,e);r.classGroupId=n},iu=(e,t,n,r)=>{if(lu(e)){Lo(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Zd(n,e))},au=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];Lo(c,Ya(t,a),n,r)}},Ya=(e,t)=>{let n=e;const r=t.split(xr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Va(),n.nextPart.set(s,a)),n=a}return n},lu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,cu=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)}}},Fo="!",$a=":",du=[],Ha=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),uu=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 g=0;g<h;g++){const S=o[g];if(s===0&&a===0){if(S===$a){i.push(o.slice(c,g)),c=g+1;continue}if(S==="/"){d=g;continue}}S==="["?s++:S==="]"?s--:S==="("?a++:S===")"&&a--}const u=i.length===0?o:o.slice(c);let f=u,E=!1;u.endsWith(Fo)?(f=u.slice(0,-1),E=!0):u.startsWith(Fo)&&(f=u.slice(1),E=!0);const p=d&&d>c?d-c:void 0;return Ha(i,E,f,p)};if(t){const o=t+$a,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Ha(du,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},hu=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}},mu=e=>({cache:cu(e.cacheSize),parseClassName:uu(e),sortModifiers:hu(e),...eu(e)}),pu=/\s+/,fu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(pu);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:f,hasImportantModifier:E,baseClassName:p,maybePostfixModifierPosition:g}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let S=!!g,m=r(S?p.substring(0,g):p);if(!m){if(!S){c=h+(c.length>0?" "+c:c);continue}if(m=r(p),!m){c=h+(c.length>0?" "+c:c);continue}S=!1}const _=f.length===0?"":f.length===1?f[0]:i(f).join(":"),y=E?_+Fo:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const T=o(m,S);for(let x=0;x<T.length;++x){const N=T[x];s.push(y+N)}c=h+(c.length>0?" "+c:c)}return c},gu=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ba(n))&&(o&&(o+=" "),o+=r);return o},Ba=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ba(e[r]))&&(n&&(n+=" "),n+=t);return n},_u=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=mu(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=fu(c,n);return o(c,h),h};return i=s,(...c)=>i(gu(...c))},Eu=[],Me=e=>{const t=n=>n[e]||Eu;return t.isThemeGetter=!0,t},Ga=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Wa=/^\((?:(\w[\w-]*):)?(.+)\)$/i,yu=/^\d+\/\d+$/,Su=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vu=/\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$/,bu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,wu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Nu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,pn=e=>yu.test(e),te=e=>!!e&&!Number.isNaN(Number(e)),jt=e=>!!e&&Number.isInteger(Number(e)),Uo=e=>e.endsWith("%")&&te(e.slice(0,-1)),Tt=e=>Su.test(e),xu=()=>!0,Cu=e=>vu.test(e)&&!bu.test(e),Ka=()=>!1,Tu=e=>wu.test(e),ku=e=>Nu.test(e),Ru=e=>!j(e)&&!z(e),Ou=e=>fn(e,Qa,Ka),j=e=>Ga.test(e),Wt=e=>fn(e,el,Cu),Vo=e=>fn(e,Du,te),qa=e=>fn(e,Ja,Ka),Au=e=>fn(e,Za,ku),Cr=e=>fn(e,tl,Tu),z=e=>Wa.test(e),er=e=>gn(e,el),Iu=e=>gn(e,Lu),Xa=e=>gn(e,Ja),Mu=e=>gn(e,Qa),Pu=e=>gn(e,Za),Tr=e=>gn(e,tl,!0),fn=(e,t,n)=>{const r=Ga.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},gn=(e,t,n=!1)=>{const r=Wa.exec(e);return r?r[1]?t(r[1]):n:!1},Ja=e=>e==="position"||e==="percentage",Za=e=>e==="image"||e==="url",Qa=e=>e==="length"||e==="size"||e==="bg-size",el=e=>e==="length",Du=e=>e==="number",Lu=e=>e==="family-name",tl=e=>e==="shadow",Fu=()=>{const e=Me("color"),t=Me("font"),n=Me("text"),r=Me("font-weight"),o=Me("tracking"),i=Me("leading"),s=Me("breakpoint"),a=Me("container"),c=Me("spacing"),d=Me("radius"),h=Me("shadow"),u=Me("inset-shadow"),f=Me("text-shadow"),E=Me("drop-shadow"),p=Me("blur"),g=Me("perspective"),S=Me("aspect"),m=Me("ease"),_=Me("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"],T=()=>[...k(),z,j],x=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],v=()=>[z,j,c],b=()=>[pn,"full","auto",...v()],R=()=>[jt,"none","subgrid",z,j],A=()=>["auto",{span:["full",jt,z,j]},jt,z,j],$=()=>[jt,"auto",z,j],J=()=>["auto","min","max","fr",z,j],oe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],_e=()=>["start","end","center","stretch","center-safe","end-safe"],ie=()=>["auto",...v()],he=()=>[pn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],U=()=>[e,z,j],Te=()=>[...k(),Xa,qa,{position:[z,j]}],de=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",Mu,Ou,{size:[z,j]}],H=()=>[Uo,er,Wt],D=()=>["","none","full",d,z,j],B=()=>["",te,er,Wt],Ee=()=>["solid","dashed","dotted","double"],Ne=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],se=()=>[te,Uo,Xa,qa],ne=()=>["","none",p,z,j],$e=()=>["none",te,z,j],Ge=()=>["none",te,z,j],We=()=>[te,z,j],Je=()=>[pn,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tt],breakpoint:[Tt],color:[xu],container:[Tt],"drop-shadow":[Tt],ease:["in","out","in-out"],font:[Ru],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tt],shadow:[Tt],spacing:["px",te],text:[Tt],"text-shadow":[Tt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",pn,j,z,S]}],container:["container"],columns:[{columns:[te,j,z,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:T()}],overflow:[{overflow:x()}],"overflow-x":[{"overflow-x":x()}],"overflow-y":[{"overflow-y":x()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:b()}],"inset-x":[{"inset-x":b()}],"inset-y":[{"inset-y":b()}],start:[{start:b()}],end:[{end:b()}],top:[{top:b()}],right:[{right:b()}],bottom:[{bottom:b()}],left:[{left:b()}],visibility:["visible","invisible","collapse"],z:[{z:[jt,"auto",z,j]}],basis:[{basis:[pn,"full","auto",a,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[te,pn,"auto","initial","none",j]}],grow:[{grow:["",te,z,j]}],shrink:[{shrink:["",te,z,j]}],order:[{order:[jt,"first","last","none",z,j]}],"grid-cols":[{"grid-cols":R()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":$()}],"col-end":[{"col-end":$()}],"grid-rows":[{"grid-rows":R()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":$()}],"row-end":[{"row-end":$()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":J()}],"auto-rows":[{"auto-rows":J()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...oe(),"normal"]}],"justify-items":[{"justify-items":[..._e(),"normal"]}],"justify-self":[{"justify-self":["auto",..._e()]}],"align-content":[{content:["normal",...oe()]}],"align-items":[{items:[..._e(),{baseline:["","last"]}]}],"align-self":[{self:["auto",..._e(),{baseline:["","last"]}]}],"place-content":[{"place-content":oe()}],"place-items":[{"place-items":[..._e(),"baseline"]}],"place-self":[{"place-self":["auto",..._e()]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:ie()}],mx:[{mx:ie()}],my:[{my:ie()}],ms:[{ms:ie()}],me:[{me:ie()}],mt:[{mt:ie()}],mr:[{mr:ie()}],mb:[{mb:ie()}],ml:[{ml:ie()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:he()}],w:[{w:[a,"screen",...he()]}],"min-w":[{"min-w":[a,"screen","none",...he()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...he()]}],h:[{h:["screen","lh",...he()]}],"min-h":[{"min-h":["screen","lh","none",...he()]}],"max-h":[{"max-h":["screen","lh",...he()]}],"font-size":[{text:["base",n,er,Wt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,z,Vo]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Uo,j]}],"font-family":[{font:[Iu,j,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,z,j]}],"line-clamp":[{"line-clamp":[te,"none",z,Vo]}],leading:[{leading:[i,...v()]}],"list-image":[{"list-image":["none",z,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",z,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Ee(),"wavy"]}],"text-decoration-thickness":[{decoration:[te,"from-font","auto",z,Wt]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[te,"auto",z,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",z,j]}],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",z,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Te()}],"bg-repeat":[{bg:de()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},jt,z,j],radial:["",z,j],conic:[jt,z,j]},Pu,Au]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:H()}],"gradient-via-pos":[{via:H()}],"gradient-to-pos":[{to:H()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:D()}],"rounded-s":[{"rounded-s":D()}],"rounded-e":[{"rounded-e":D()}],"rounded-t":[{"rounded-t":D()}],"rounded-r":[{"rounded-r":D()}],"rounded-b":[{"rounded-b":D()}],"rounded-l":[{"rounded-l":D()}],"rounded-ss":[{"rounded-ss":D()}],"rounded-se":[{"rounded-se":D()}],"rounded-ee":[{"rounded-ee":D()}],"rounded-es":[{"rounded-es":D()}],"rounded-tl":[{"rounded-tl":D()}],"rounded-tr":[{"rounded-tr":D()}],"rounded-br":[{"rounded-br":D()}],"rounded-bl":[{"rounded-bl":D()}],"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:[...Ee(),"hidden","none"]}],"divide-style":[{divide:[...Ee(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...Ee(),"none","hidden"]}],"outline-offset":[{"outline-offset":[te,z,j]}],"outline-w":[{outline:["",te,er,Wt]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",h,Tr,Cr]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",u,Tr,Cr]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[te,Wt]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":B()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",f,Tr,Cr]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[te,z,j]}],"mix-blend":[{"mix-blend":[...Ne(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ne()}],"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":[te]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[z,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"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":[te]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Te()}],"mask-repeat":[{mask:de()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",z,j]}],filter:[{filter:["","none",z,j]}],blur:[{blur:ne()}],brightness:[{brightness:[te,z,j]}],contrast:[{contrast:[te,z,j]}],"drop-shadow":[{"drop-shadow":["","none",E,Tr,Cr]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",te,z,j]}],"hue-rotate":[{"hue-rotate":[te,z,j]}],invert:[{invert:["",te,z,j]}],saturate:[{saturate:[te,z,j]}],sepia:[{sepia:["",te,z,j]}],"backdrop-filter":[{"backdrop-filter":["","none",z,j]}],"backdrop-blur":[{"backdrop-blur":ne()}],"backdrop-brightness":[{"backdrop-brightness":[te,z,j]}],"backdrop-contrast":[{"backdrop-contrast":[te,z,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",te,z,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[te,z,j]}],"backdrop-invert":[{"backdrop-invert":["",te,z,j]}],"backdrop-opacity":[{"backdrop-opacity":[te,z,j]}],"backdrop-saturate":[{"backdrop-saturate":[te,z,j]}],"backdrop-sepia":[{"backdrop-sepia":["",te,z,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",z,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[te,"initial",z,j]}],ease:[{ease:["linear","initial",m,z,j]}],delay:[{delay:[te,z,j]}],animate:[{animate:["none",_,z,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,z,j]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:$e()}],"rotate-x":[{"rotate-x":$e()}],"rotate-y":[{"rotate-y":$e()}],"rotate-z":[{"rotate-z":$e()}],scale:[{scale:Ge()}],"scale-x":[{"scale-x":Ge()}],"scale-y":[{"scale-y":Ge()}],"scale-z":[{"scale-z":Ge()}],"scale-3d":["scale-3d"],skew:[{skew:We()}],"skew-x":[{"skew-x":We()}],"skew-y":[{"skew-y":We()}],transform:[{transform:[z,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"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",z,j]}],"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":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"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",z,j]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[te,er,Wt,Vo]}],stroke:[{stroke:["none",...U()]}],"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"]}},Uu=_u(Fu);function M(...e){return Uu(Ua(e))}function Kt(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 Vu=e=>{switch(e){case I.SYNAPSE_COMPONENTS.DOCTOR_CARD:case I.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},ju=e=>new Promise(t=>setTimeout(t,e)),nl=Q(({className:e,children:t,...n},r)=>l(Ti,{ref:r,className:M("relative overflow-hidden",e),...n,children:[l(Od,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(rl,{}),l(Ad,{})]}));nl.displayName=Ti.displayName;const rl=Q(({className:e,orientation:t="vertical",...n},r)=>l(xo,{ref:r,orientation:t,className:M("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(vi,{className:"relative flex-1 rounded-full bg-border"})}));rl.displayName=xo.displayName;var zu=Symbol.for("react.lazy"),kr=bo[" use ".trim().toString()];function Yu(e){return typeof e=="object"&&e!==null&&"then"in e}function ol(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===zu&&"_payload"in e&&Yu(e._payload)}function sl(e){const t=Hu(e),n=Q((r,o)=>{let{children:i,...s}=r;ol(i)&&typeof kr=="function"&&(i=kr(i._payload));const a=et.toArray(i),c=a.find(Gu);if(c){const d=c.props.children,h=a.map(u=>u===c?et.count(d)>1?et.only(null):tt(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:tt(d)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var $u=sl("Slot");function Hu(e){const t=Q((n,r)=>{let{children:o,...i}=n;if(ol(o)&&typeof kr=="function"&&(o=kr(o._payload)),tt(o)){const s=Ku(o),a=Wu(i,o.props);return o.type!==ue&&(a.ref=r?wo(r,s):s),Lt(o,a)}return et.count(o)>1?et.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Bu=Symbol("radix.slottable");function Gu(e){return tt(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Bu}function Wu(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 Ku(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 il=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,al=Ua,qu=(e,t)=>n=>{var r;if(t?.variants==null)return al(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 f=il(h)||il(u);return o[d][f]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,f]=h;return f===void 0||(d[u]=f),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:f,...E}=h;return Object.entries(E).every(p=>{let[g,S]=p;return Array.isArray(S)?S.includes({...i,...a}[g]):{...i,...a}[g]===S})?[...d,u,f]:d},[]);return al(e,s,c,n?.class,n?.className)},Xu=qu("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"}}),ce=Q(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?$u:"button",{className:M(Xu({variant:t,size:n,className:e})),ref:i,...o}));ce.displayName="Button";const Ju=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Zu=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),ll=e=>{const t=Zu(e);return t.charAt(0).toUpperCase()+t.slice(1)},cl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Qu=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var eh={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 th=Q(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>qe("svg",{ref:c,...eh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:cl("lucide",o),...!i&&!Qu(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>qe(d,h)),...Array.isArray(i)?i:[i]])),Fe=(e,t)=>{const n=Q(({className:r,...o},i)=>qe(th,{ref:i,iconNode:t,className:cl(`lucide-${Ju(ll(e))}`,`lucide-${e}`,r),...o}));return n.displayName=ll(e),n},nh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],jo=Fe("chevron-down",nh),rh=[["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"}]],oh=Fe("ellipsis-vertical",rh),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"}]],dl=Fe("file-text",sh),ih=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],ul=Fe("info",ih),ah=[["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"}]],lh=Fe("maximize-2",ah),ch=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],dh=Fe("menu",ch),uh=[["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"}]],tr=Fe("message-square-plus",uh),hh=[["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"}]],zo=Fe("mic",hh),mh=[["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"}]],ph=Fe("minimize-2",mh),fh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],hl=Fe("plus",fh),gh=[["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"}]],_h=Fe("rotate-ccw",gh),Eh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ml=Fe("square",Eh),yh=[["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"}]],Rr=Fe("thumbs-up",yh),Sh=[["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"}]],Or=Fe("thumbs-down",Sh),vh=[["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"}]],bh=Fe("triangle-alert",vh),wh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],_n=Fe("x",wh),Nh=[["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"}]],xh=Fe("zoom-in",Nh),pl=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},Ch=(e=>e?pl(e):pl),Th=e=>e;function kh(e,t=Th){const n=On.useSyncExternalStore(e.subscribe,On.useCallback(()=>t(e.getState()),[e,t]),On.useCallback(()=>t(e.getInitialState()),[e,t]));return On.useDebugValue(n),n}const Rh=e=>{const t=Ch(e),n=r=>kh(t,r);return Object.assign(n,t),n},Oh=(e=>Rh);function fl(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 Yo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Yo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Yo(r)(n)}}}},Ah=(e,t)=>(n,r,o)=>{let i={storage:fl(()=>localStorage),partialize:g=>g,version:0,merge:(g,S)=>({...S,...g}),...t},s=!1;const a=new Set,c=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,S)=>(u(g,S),h());const f=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>f;let E;const p=()=>{var g,S;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:f)});const m=((S=i.onRehydrateStorage)==null?void 0:S.call(i,(g=r())!=null?g:f))||void 0;return Yo(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,T]=_;if(E=i.merge(T,(y=r())!=null?y:f),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:g=>{i={...i,...g},g.storage&&(d=g.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(c.add(g),()=>{c.delete(g)})},i.skipHydration||p(),E||f},Ih=Ah,Pe={USER:"user",ASSISTANT:"assistant"};var Se=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Se||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let kt="";const nr=e=>`med-assist-store-${e}`,Mh=e=>{kt=nr(e)},gl={sessionId:"",isStreaming:!1,recordingStatus:Se.IDLE,isWaitingForResponse:!1,error:null,isTimeoutError:!1,startNewConnection:!1,showRetryButton:!1,chats:{},inlineText:null,connectionStatus:ge.CONNECTING,streamingTimeoutId:null,responseTimeoutId:null,lastStreamingActivity:null,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},_l={...gl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},W=Oh()(Ih((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:Se.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}),inlineText:null,setInlineText:n=>e({inlineText:n}),isBotIconAnimating:!1,setIsBotIconAnimating:n=>e({isBotIconAnimating: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}})),clearMessagesForSession:n=>e(r=>({chats:{...r.chats,[n]:[]}})),clearAllChats:()=>e({chats:{}}),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,isTimeoutError:!1,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),isTimeoutError:!1,setTimeoutError:n=>e({isTimeoutError:n}),clearSession:async()=>{e(gl),await sessionStorage.removeItem(kt||nr(t().agentId))},clearUser:()=>{e(_l),sessionStorage.removeItem(kt||nr(t().agentId))},streamingTimeoutId:null,setStreamingTimeoutId:n=>e({streamingTimeoutId:n}),clearStreamingTimeout:()=>{const n=t();n.streamingTimeoutId&&(clearTimeout(n.streamingTimeoutId),e({streamingTimeoutId:null}))},responseTimeoutId:null,setResponseTimeoutId:n=>e({responseTimeoutId:n}),clearResponseTimeout:()=>{const n=t();n.responseTimeoutId&&(clearTimeout(n.responseTimeoutId),e({responseTimeoutId:null}))},lastStreamingActivity:null,setLastStreamingActivity:n=>e({lastStreamingActivity:n})}),{name:"med-assist-store",storage:fl(()=>({getItem:()=>kt?sessionStorage.getItem(kt):null,setItem:(e,t)=>{kt&&sessionStorage.setItem(kt,t)},removeItem:()=>{kt&&sessionStorage.removeItem(kt)}})),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})})),Ph=e=>{const t=nr(e);let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}W.setState(_l),n&&W.setState(n)},$o=Nt(null),Dh=({children:e})=>{const[t,n]=F(null);return l($o.Provider,{value:{synapse:t,setSynapse:n},children:e})},Lh=()=>{const e=Ct($o);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Fh=()=>{const e=Ct($o);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},Uh=()=>{const[e,t]=F(I.VOICE_AGENT_STATE.IDLE),[n,r]=F(!1),o=Lh(),{setError:i}=W();Y(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},f=()=>{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,f),()=>{h.off(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(I.VOICE_AGENT_EVENTS.ERROR,f)}},[o,i]);const s=fe(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=fe(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),c=fe(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=fe(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:c,toggleMute:d}},qt=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));qt.displayName="Card";const El=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("flex flex-col space-y-1.5 p-6",e),...t}));El.displayName="CardHeader";const yl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("font-semibold leading-none tracking-tight",e),...t}));yl.displayName="CardTitle";const Vh=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("text-sm text-muted-foreground",e),...t}));Vh.displayName="CardDescription";const Sl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("p-6 pt-0",e),...t}));Sl.displayName="CardContent";const vl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("flex items-center p-6 pt-0",e),...t}));vl.displayName="CardFooter";const Ho=5,jh=10*1024*1024,Ar={width:384,height:600},Ir=20,zh=400,Yh=320,$h=560,Hh=150;function Bh({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=fe(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Ar.width-Ir,y:window.innerHeight-Ar.height-Ir},[]),[i,s]=F(()=>e??o()),[a,c]=F(!1),d=q({x:0,y:0}),h=q(null),u=q(!1);Y(()=>{t||(u.current=!1)},[t]),dt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),Y(()=>{if(!t||typeof window>"u")return;let g=null;const S=()=>{s(_=>{const y=Math.max(0,window.innerWidth-Ar.width-Ir),k=Math.max(0,window.innerHeight-Ar.height-Ir),T=Math.max(0,Math.min(_.x,y)),x=Math.max(0,Math.min(_.y,k));return T===_.x&&x===_.y?_:{x:T,y:x}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(S,Hh)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const f=fe(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){c(!1);return}g.preventDefault(),c(!0);const S=h.current;if(S){const m=S.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),E=fe(g=>{if(!t||!a)return;const S=g.clientX-d.current.x,m=g.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(S,_)),T=Math.max(0,Math.min(m,y));s({x:k,y:T})},[a,t]),p=fe(()=>{!t||!a||(c(!1),r?.())},[a,r]);return Y(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",f),()=>{g.removeEventListener("mousedown",f)}},[t,f]),Y(()=>{if(a)return document.addEventListener("mousemove",E),document.addEventListener("mouseup",p),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""}},[a,E,p]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Bo="#6B5CE0",Gh="#F0F0F0",Mr={background:Gh,backgroundImage:void 0,primary:Bo,textColor:"black"},Wh="rgba(0, 0, 0, 0.4)",Kh="24px";function qh(e){if(e==="dark")return"white";if(e==="light")return"black"}function Xh(e){const t=e?.primary??e?.primaryColor??Mr.primary,n=e?.textColor??qh(e?.mode);return{background:e?.background??Mr.background,backgroundImage:e?.backgroundImage??Mr.backgroundImage,primary:t,primaryColor:t,textColor:n??Mr.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Jh(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 Zh(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 Qh(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 Go(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return Jh(t);if(t.startsWith("rgb"))return Zh(t);if(t.startsWith("hsl"))return Qh(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function bl(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Wo(e){return bl(e)>.5?"0 0% 9%":"0 0% 98%"}function em(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 tm(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 wl(e,t){const n=t.primary??Bo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,p)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(E,p)};let c;try{c=Go(n)}catch{c=Go(Bo)}a("--primary",c),a("--primary-foreground",Wo(c)),a("--ring",c),a("--border-primary",c);const d=tm(c);for(const[E,p]of Object.entries(d))a(`--primary-${E}`,p);const h=Wo(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",Go(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",em(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=bl(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 f=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${f}-${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",Wo(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",Kh),a("--theme-background-overlay",Wh),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 Xt({className:e,style:t}){return l("div",{className:M("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 Ko(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Nl(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Ko,{}),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(Xt,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Xt,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Xt,{className:"h-9 w-9 rounded-full"}),l(Xt,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function nm(){return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(Ko,{}),[{role:"assistant",size:"h-16 w-[70%]"},{role:"user",size:"h-9 w-[45%]"},{role:"assistant",size:"h-24 w-[75%]"},{role:"user",size:"h-9 w-[35%]"},{role:"assistant",size:"h-16 w-[65%]"}].map((e,t)=>l("div",{className:M("flex",e.role==="user"?"justify-end":"justify-start"),children:l(Xt,{className:M("rounded-lg",e.size)})},t))]})}function rm({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(Ko,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Xt,{className:M("h-5 rounded-md",t[r%t.length])}),l(Xt,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function om(e,t=[]){let n=[];function r(i,s){const a=Nt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,S=ye(()=>p,Object.values(p));return l(g.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;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=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,sm(o,...t)]}function sm(...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 ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var im=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],qo=im.reduce((e,t)=>{const n=sl(`Primitive.${t}`),r=Q((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}},{}),xl={exports:{}},Xo={};const am=Id(bo);var Cl;function lm(){if(Cl)return Xo;Cl=1;var e=am;function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,f){var E=f(),p=r({inst:{value:E,getSnapshot:f}}),g=p[0].inst,S=p[1];return i(function(){g.value=E,g.getSnapshot=f,c(g)&&S({inst:g})},[u,E,f]),o(function(){return c(g)&&S({inst:g}),u(function(){c(g)&&S({inst:g})})},[u]),s(E),E}function c(u){var f=u.getSnapshot;u=u.value;try{var E=f();return!n(u,E)}catch{return!0}}function d(u,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return Xo.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,Xo}var Tl;function cm(){return Tl||(Tl=1,xl.exports=lm()),xl.exports}var dm=cm();function um(){return dm.useSyncExternalStore(hm,()=>!0,()=>!1)}function hm(){return()=>{}}var Jo="Avatar",[mm]=om(Jo),[pm,kl]=mm(Jo),Rl=Q((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=F("idle");return l(pm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(qo.span,{...r,ref:t})})});Rl.displayName=Jo;var Ol="AvatarImage",Al=Q((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=kl(Ol,n),a=fm(r,i),c=Ut(d=>{o(d),s.onImageLoadingStatusChange(d)});return Gt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(qo.img,{...i,ref:t,src:r}):null});Al.displayName=Ol;var Il="AvatarFallback",Ml=Q((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=kl(Il,n),[s,a]=F(r===void 0);return Y(()=>{if(r!==void 0){const c=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(c)}},[r]),s&&i.imageLoadingStatus!=="loaded"?l(qo.span,{...o,ref:t}):null});Ml.displayName=Il;function Pl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function fm(e,{referrerPolicy:t,crossOrigin:n}){const r=um(),o=q(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=F(()=>Pl(i,e));return Gt(()=>{a(Pl(i,e))},[i,e]),Gt(()=>{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 Dl=Rl,Ll=Al,Fl=Ml;const Zo=Q(({className:e,...t},n)=>l(Dl,{ref:n,className:M("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Zo.displayName=Dl.displayName;const Ul=Q(({className:e,...t},n)=>l(Ll,{ref:n,className:M("aspect-square h-full w-full",e),...t}));Ul.displayName=Ll.displayName;const Qo=Q(({className:e,...t},n)=>l(Fl,{ref:n,className:M("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Qo.displayName=Fl.displayName;const Vl=Nt(!1);function gm({enabled:e,children:t}){return l(Vl.Provider,{value:e,children:t})}function _m(){return Ct(Vl)}const jl="(max-width: 768px), (pointer: coarse)",zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Em(){if(typeof window>"u")return!1;const e=window.matchMedia?.(jl)?.matches??!1,t=zl.test(navigator?.userAgent??"");return e||t}function Yl(){const[e,t]=F(Em);return Y(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(jl),r=zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function ym({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,historyEnabled:u=!1}){const f=Yl(),E=_m(),p=W(A=>A.displayMode)==="side_panel",g=E&&!f&&!p,S=W(A=>A.displayMode)==="full",m=W(A=>A.initialDisplayMode)==="full",_=!S&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",y=W(A=>A.connectionStatus),k=W(A=>A.level)==="user",[T,x]=F(!1),N=q(null),v=ye(()=>a==="connected"||a==="connecting"||a==="listening"||a==="speaking"||a==="thinking",[a]),b=fe(()=>{T||(x(!0),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,x(!1)},6e3),s())},[T,s]);Y(()=>{y===ge.CONNECTED&&(x(!1),N.current&&clearTimeout(N.current))},[y]);const R=(()=>{switch(y){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(Zo,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(Qo,{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:M("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",R.dotColor,y===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:M("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",_),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:R.text})})]})]}),l("div",{className:M("flex items-center",!g&&"gap-1"),children:[!v&&(!k||!u)&&l(ce,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:b,disabled:T,className:M("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",_),children:l(tr,{className:"w-5 h-5"})}),h&&k&&l(ce,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:M("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(oh,{className:"w-5 h-5"})}),g&&l(ce,{onClick:d,type:"button",variant:"ghost",size:"icon",title:S?"Exit fullscreen":"Enter fullscreen",className:M("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:S?l(ph,{className:"w-8 h-8"}):l(lh,{className:"w-8 h-8"})}),(t||!m)&&l(ce,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:M("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(_n,{className:"w-8 h-8"})})]})]})})}const es=Q(({className:e,...t},n)=>l("textarea",{className:M("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}));es.displayName="Textarea";function $l({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=F(!1),[s,a]=F(""),c=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";Y(()=>{if(c){const f=URL.createObjectURL(e);return a(f),()=>URL.revokeObjectURL(f)}},[e,c]),Y(()=>{i(!1)},[e]);const h=()=>c?"text-green-600":"text-text-secondary",u=f=>{if(f===0)return"0 B";const E=1024,p=["B","KB","MB","GB"],g=Math.floor(Math.log(f)/Math.log(E));return`${(f/Math.pow(E,g)).toFixed(1)} ${p[g]}`.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(dl,{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(_n,{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(_n,{className:"h-3 w-3"})})]})}function ts({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($l,{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($l,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const ns=({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"})}),Hl=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Sm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Bl=({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"})}),vm=Xe(()=>Hl().then(e=>({default:e.ElicitationInput})));function bm({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:f,theme:E,allowed:p,showStartNewChatButton:g,onStartNewChat:S,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:T}){const x=q(null),N=q(null),v=e.trim().length>0||a,b=!p||p.includes(I.SYNAPSE_CONVERSATION.AUDIO),R=!p||p.includes(I.SYNAPSE_CONVERSATION.VOICE),A=v||!b,$=v,J=!p||p.includes(I.SYNAPSE_CONVERSATION.FILE),oe=(d||f!==Se.IDLE)&&!s,_e=M("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)]":oe?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),ie=V=>{const H=Array.from(V.target.files||[]);H.length>0&&r(H)},he=()=>{d||(x.current&&(x.current.value=""),x.current?.click())},U=V=>{V.key==="Enter"&&!V.shiftKey&&$&&!d&&(V.preventDefault(),n())},Te=V=>{V.style.height="auto",V.style.overflow="hidden";const H=V.scrollHeight,D=T?20:28,B=120,Ee=Math.max(D,Math.min(H,B));V.style.height=Ee+"px",H>B?V.style.overflow="auto":V.style.overflow="hidden"},de=V=>{Te(V.currentTarget)};return Y(()=>{N.current&&Te(N.current)},[e]),Y(()=>{!d&&!u&&N.current?.focus()},[d]),g&&S?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:S,className:M("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(tr,{className:"w-5 h-5","aria-hidden":!0})]})}):l(ue,{children:y?l(He,{fallback:l(Nl,{}),children:l(vm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):T?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ts,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:x,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,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(es,{ref:N,onInput:de,placeholder:h,value:e,onChange:V=>t(V.target.value),rows:1,maxLength:1e3,autoFocus:!u,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:U,title:"Enter your message","aria-label":"Enter your message",className:M("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:J&&f===Se.IDLE&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:he,disabled:d,className:M("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(hl,{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(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,className:M("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(ml,{className:"w-4 h-4"})}):b&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:oe,className:M("h-10 w-10 shrink-0 p-2",_e),title:"Start recording","aria-label":"Start recording",children:l(zo,{className:"w-6 h-6",strokeWidth:1.5})}),A&&!s?l(ce,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!$,variant:"ghost",className:M("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",$?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:$?"Send message":"Type a message to send","aria-label":$?"Send message":"Type a message to send",children:l(ns,{className:"w-4 h-4 text-primary-foreground"})}):b&&R&&!s&&l(ce,{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(Bl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:x,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ts,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(es,{ref:N,onInput:de,placeholder:h,value:e,onChange:V=>t(V.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:U,title:"Enter your message","aria-label":"Enter your message",className:M("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:J&&f===Se.IDLE&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:he,disabled:d,className:M("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(hl,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,className:M("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(ml,{className:"w-4 h-4"})}):A?l(ce,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!$,variant:"ghost",className:M("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",$?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:$?"Send message":"Type a message to send","aria-label":$?"Send message":"Type a message to send",children:l(ns,{className:"w-4 h-4 text-primary-foreground"})}):b&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:oe,className:M("h-10 w-10 shrink-0",_e),title:"Start recording","aria-label":"Start recording",children:l(zo,{className:"w-5 h-5",strokeWidth:1.5})}),b&&R&&!s&&l(ce,{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(Bl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}function wm({message:e,onDismiss:t}){return l(ue,{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(_n,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Nm(){const e=W(r=>r.toastMessage),t=W(r=>r.setToastMessage),n=fe(()=>{t(null)},[t]);return Y(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(wm,{message:e,onDismiss:n}):null}function rs({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 xm="Before we begin",Cm=e=>`A quick note on how ${e} works and handles your information.`,Tm=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 km(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 Gl=(e,t)=>{if(t){const n=km(t,e);if(n.length)return n}return Tm(e)},Rm="I agree and consent",Om="By continuing, you consent to the above.",Am="Continue";function Wl({botName:e,consentContent:t,isFullScreen:n}){return l(ue,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:M("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:xm}),l("p",{className:M("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Cm(e)})]}),l("div",{className:M("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:Gl(e,t).map((r,o)=>l("p",{className:M("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function Im({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(rs,{isOpen:e,onClose:t,children:l("div",{className:M("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(Wl,{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"}),Gl(n,o).map((a,c)=>l("p",{className:M("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(ce,{onClick:t,className:M("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Mm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=F(!1);return e?l(rs,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:M("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(Wl,{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:M("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:M("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Rm})]}),l("p",{className:M("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:Om})]}),l(ce,{disabled:!i,onClick:()=>i&&r(),className:M("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Am})]})}):null}const Pm=Xe(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),Dm=Xe(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),Lm=Xe(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),Fm=Xe(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),Um=Xe(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),Vm=[{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"}],jm=[{Icon:Pm,label:"Bad",score:1},{Icon:Dm,label:"Poor",score:2},{Icon:Lm,label:"Okay",score:3},{Icon:Fm,label:"Good",score:4},{Icon:Um,label:"Great!",score:5}];function zm(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Ym({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=F(null),[d,h]=F(new Set),[u,f]=F(!1),E=s&&a!==null?zm(a,t):t.form?.default?.length?t.form.default:Vm,p=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},g=_=>{c(_),h(new Set)},S=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(rs,{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:jm.map(({Icon:_,label:y,score:k})=>{const T=a===k,x=a!==null&&!T;return l("button",{onClick:()=>g(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 ${T?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${x?"opacity-50":""}`,style:T?{filter:"brightness(1.25)"}:void 0,children:l(He,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(_,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${T?"text-primary/50 font-medium":x?"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:()=>p(_.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(ce,{disabled:!S,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:()=>f(_=>!_),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 Kl({isOpen:e,onClose:t,showCloseButton:n=!0,iconUrl:r,onStartNewSession:o,showStartNewChatButton:i,children:s,sidebar:a,sessionDrawer:c,fullScreenEmptyState:d,title:h,titleImg:u,tagline:f,sessionId:E,chatComposer:p,environment:g,mode:S,sidePanelMode:m,sidePanelWidth:_,side:y,onSidePanelPushChange:k,onToggleDisplayMode:T,onOpenSessionDrawer:x,historyEnabled:N=!1,isAuthComponent:v,activeElicitation:b,voiceAgentState:R,theme:A,feedbackModal:$,consentModal:J}){const[oe,_e]=F(!1),[ie,he]=F(!1),[U,Te]=F(!1),de=q(null),V=W(L=>L.level),H=S,D=H==="full",B=H==="side_panel",Ee=q(null),[Ne,se]=F("");Y(()=>{Ee.current!==null&&Ee.current!==H&&se(H==="full"?"Switched to fullscreen mode":H==="side_panel"?"Switched to side panel mode":H==="widget"?"Switched to widget mode":"Switched to mobile layout"),Ee.current=H},[H]);const ne=ye(()=>Xh(A),[A]),{setIsMobile:$e}=W(L=>L),Ge=!!v,We=async L=>{if(!(!p?.onSend||ie)){he(!0);try{await p.onSend(L)}finally{he(!1)}}};dt(()=>{if(!de.current)return;const L=H==="full"?{...ne,headerTinted:!1}:ne;wl(de.current,L),H==="full"&&!ne.backgroundImage?(de.current.style.setProperty("--background","0 0% 100%"),de.current.style.setProperty("--widget-bg-overlay","transparent")):(de.current.style.removeProperty("--background"),de.current.style.removeProperty("--widget-bg-overlay"),wl(de.current,ne))},[ne,H]),Y(()=>{const L=()=>{const Oe=window?.innerWidth??0,le=navigator?.userAgent?.toLowerCase()??"",Re=Oe<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(le);_e(Re),$e(Re)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),dt(()=>{if(!e||!oe||!de.current)return;const L=de.current;let Oe=null,le=null,Re=null,Ze=window.visualViewport?.offsetTop??0,rt=0;const xe=2,at=80;if(window.visualViewport){const Ae=()=>{if(L&&window.visualViewport){const Ie=window.visualViewport.height,lt=window.visualViewport.offsetTop;Oe=requestAnimationFrame(()=>{L.style.transition="none",L.style.top=`${lt}px`,L.style.left="0",L.style.right="0",L.style.bottom="auto",L.style.width="100vw",L.style.height=`${Ie}px`,L.style.maxHeight=`${Ie}px`,L.style.minHeight=`${Ie}px`,le&&clearTimeout(le),le=setTimeout(()=>{L.style.transition=""},100)})}},De=()=>{Ae()},Ue=()=>{if(!L||!window.visualViewport)return;const Ie=window.visualViewport.offsetTop,lt=Date.now();Math.abs(Ie-Ze)<xe||lt-rt<at||(rt=lt,Ze=Ie,Oe=requestAnimationFrame(()=>{L.style.transition="none",L.style.top=`${Ie}px`,Re&&clearTimeout(Re),Re=setTimeout(()=>{L.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",De),window.visualViewport.addEventListener("scroll",Ue),Ae(),()=>{Oe&&cancelAnimationFrame(Oe),le&&clearTimeout(le),Re&&clearTimeout(Re),window.visualViewport?.removeEventListener("resize",De),window.visualViewport?.removeEventListener("scroll",Ue),L&&(L.style.width="",L.style.height="",L.style.maxHeight="",L.style.minHeight="",L.style.transition="")}}else{const Ae=()=>{L&&(L.style.transition="none",L.style.top="0",L.style.left="0",L.style.right="0",L.style.bottom="auto",L.style.width="100vw",L.style.height="100svh",L.style.maxHeight="100svh",setTimeout(()=>{L.style.transition=""},100))};return window.addEventListener("resize",Ae),Ae(),()=>{window.removeEventListener("resize",Ae),L&&(L.style.width="",L.style.height="",L.style.maxHeight="",L.style.transition="")}}},[e,oe]),Y(()=>{if(e&&!(B&&m==="push")){const L=de.current,Oe=window.scrollY,le=document.body.style.cssText,Re=document.documentElement.style.overflow,Ze=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Oe}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",Ze>0&&!oe&&(document.body.style.paddingRight=`${Ze}px`);let rt=0;const xe=Ae=>{rt=Ae.touches[0].clientY},at=Ae=>{if(Ae.touches.length!==1)return;const De=rt-Ae.touches[0].clientY;rt=Ae.touches[0].clientY;let Ue=Ae.target;for(;Ue&&Ue!==L;){const{overflowY:Ie}=window.getComputedStyle(Ue);if((Ie==="auto"||Ie==="scroll")&&Ue.scrollHeight>Ue.clientHeight){const{scrollTop:lt,scrollHeight:en,clientHeight:yn}=Ue,St=lt<=0&&De<0,ct=lt+yn>=en-1&&De>0;if(!St&&!ct)return;break}Ue=Ue.parentElement}Ae.preventDefault()};return L&&(L.addEventListener("touchstart",xe,{passive:!0}),L.addEventListener("touchmove",at,{passive:!1})),()=>{L&&(L.removeEventListener("touchstart",xe),L.removeEventListener("touchmove",at)),document.body.style.cssText=le,document.documentElement.style.overflow=Re,window.scrollTo(0,Oe)}}},[e,oe,B,m]),Y(()=>{if(!(!B||m!=="push"||!e))return k?.(!0,_??0,y??"right"),()=>{k?.(!1,_??0,y??"right")}},[e,B,m,_,y,k]);const{position:Je,elementRef:Ot}=Bh({enabled:e&&!oe&&!D&&!B});Y(()=>{de.current&&(Ot.current=de.current)},[Ot]);const mt=M("synapse-chat-widget-container","fixed m-0 p-0","box-border",!oe&&!D&&!B?"transition-all duration-300":"",oe?"w-screen h-[100svh]":D?"w-screen h-screen":B?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),it=M("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",ne.backgroundImage?"theme-with-background":"",oe?"rounded-none border-0 flex-col":D?"rounded-none border-0 flex-row":B?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return l("div",{ref:de,"data-mode":H,className:mt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...D&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...D&&!e&&{display:"none"},...B&&e&&{top:0,bottom:0,[y==="left"?"left":"right"]:0,[y==="left"?"right":"left"]:"auto",width:`${_}px`,height:"100vh"},...B&&!e&&{display:"none"},...!oe&&!D&&!B&&{left:`${Je.x}px`,top:`${Je.y}px`,bottom:"auto",right:"auto"},...oe&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:ne.backgroundImage?"transparent":"hsl(var(--background))"}},children:[l("style",{children:`
|
|
1
|
+
var Wc=Object.defineProperty;var Kc=(e,t,n)=>t in e?Wc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>Kc(e,typeof t!="symbol"?t+"":t,n);var Rn,Q,vs,Dt,ws,Ns,Cs,to,vr,In,Ts,no,ro,oo,xs,wr={},Nr=[],qc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Mn=Array.isArray;function bt(e,t){for(var n in t)e[n]=t[n];return e}function so(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function tt(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?Rn.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 Pn(e,s,r,o,null)}function Pn(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??++vs,__i:-1,__u:0};return o==null&&Q.vnode!=null&&Q.vnode(i),i}function ks(){return{current:null}}function me(e){return e.children}function lt(e,t){this.props=e,this.context=t}function an(e,t){if(t==null)return e.__?an(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"?an(e):null}function Xc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=bt({},t);i.__v=t.__v+1,Q.vnode&&Q.vnode(i),ao(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??an(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Ps(r,i,o),t.__e=t.__=null,i.__e!=n&&Os(i)}}function Os(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}),Os(e)}function io(e){(!e.__d&&(e.__d=!0)&&Dt.push(e)&&!Cr.__r++||ws!=Q.debounceRendering)&&((ws=Q.debounceRendering)||Ns)(Cr)}function Cr(){try{for(var e,t=1;Dt.length;)Dt.length>t&&Dt.sort(Cs),e=Dt.shift(),t=Dt.length,Xc(e)}finally{Dt.length=Cr.__r=0}}function As(e,t,n,r,o,i,s,a,c,d,h){var u,p,E,g,f,S,m,_=r&&r.__k||Nr,y=t.length;for(c=Zc(n,t,_,c,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(p=E.__i!=-1&&_[E.__i]||wr,E.__i=u,S=ao(e,E,p,o,i,s,a,c,d,h),g=E.__e,E.ref&&p.ref!=E.ref&&(p.ref&&co(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=Rs(E,c,e,m),m&&p.__e&&(p.__e=null)):typeof E.type=="function"&&S!==void 0?c=S:g&&(c=g.nextSibling),E.__u&=-7);return n.__e=f,c}function Zc(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]=Pn(null,s,null,null,null):Mn(s)?s=e.__k[i]=Pn(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Pn(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=Jc(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=an(a)),Ls(a,a));return r}function Rs(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=Rs(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=an(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Ot(e,t){return t=t||[],e==null||typeof e=="boolean"||(Mn(e)?e.some(function(n){Ot(n,t)}):t.push(e)),t}function Jc(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 Is(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||qc.test(t)?n:n+"px"}function Tr(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||Is(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Is(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Ts,"$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[In]=r[In]:(n[In]=no,e.addEventListener(t,i?oo:ro,i)):e.removeEventListener(t,i?oo:ro,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 Ms(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[vr]==null)t[vr]=no++;else if(t[vr]<n[In])return;return n(Q.event?Q.event(t):t)}}}function ao(e,t,n,r,o,i,s,a,c,d){var h,u,p,E,g,f,S,m,_,y,O,T,v,x,b,w=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=Q.__b)&&h(t);e:if(typeof w=="function")try{if(m=t.props,_=w.prototype&&w.prototype.render,y=(h=w.contextType)&&r[h.__c],O=h?y?y.props.value:h.__:r,n.__c?S=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new w(m,O):(t.__c=u=new lt(m,O),u.constructor=w,u.render=ed),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),_&&w.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=bt({},u.__s)),bt(u.__s,w.getDerivedStateFromProps(m,u.__s))),E=u.props,g=u.state,u.__v=t,p)_&&w.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&w.getDerivedStateFromProps==null&&m!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(m,O),t.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(m,u.__s,O)===!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(N){N&&(N.__=t)}),Nr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,O),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,g,f)})}if(u.context=O,u.props=m,u.__P=e,u.__e=!1,T=Q.__r,v=0,_)u.state=u.__s,u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),Nr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++v<25);u.state=u.__s,u.getChildContext!=null&&(r=bt(bt({},r),u.getChildContext())),_&&!p&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(E,g)),x=h!=null&&h.type===me&&h.key==null?Ds(h.props.children):h,a=As(e,Mn(x)?x:[x],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),S&&(u.__E=u.__=null)}catch(N){if(t.__v=null,c||i!=null)if(N.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(b=i.length;b--;)so(i[b]);lo(t)}else t.__e=n.__e,t.__k=n.__k,N.then||lo(t);Q.__e(N,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=Qc(n.__e,t,n,r,o,i,s,c,d);return(h=Q.diffed)&&h(t),128&t.__u?void 0:a}function lo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(lo))}function Ps(e,t,n){for(var r=0;r<n.length;r++)co(n[r],n[++r],n[++r]);Q.__c&&Q.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){Q.__e(i,o.__v)}})}function Ds(e){return typeof e!="object"||e==null||e.__b>0?e:Mn(e)?e.map(Ds):e.constructor!==void 0?null:bt({},e)}function Qc(e,t,n,r,o,i,s,a,c){var d,h,u,p,E,g,f,S=n.props||wr,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&&(Q.__m&&Q.__m(t,i),a=!1),i=null}if(_==null)S===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&Rn.call(e.childNodes),!a&&i!=null)for(S={},d=0;d<e.attributes.length;d++)S[(E=e.attributes[d]).name]=E.value;for(d in S)E=S[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||Tr(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"||S[d]===E||Tr(e,d,E,S[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=""),As(t.type=="template"?e.content:e,Mn(p)?p:[p],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&an(n,0),a,c),i!=null)for(d=i.length;d--;)so(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||_=="progress"&&!g||_=="option"&&g!=S[d])&&Tr(e,d,g,S[d],o),d="checked",f!=null&&f!=e[d]&&Tr(e,d,f,S[d],o))}return e}function co(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){Q.__e(o,n)}}function Ls(e,t,n){var r,o;if(Q.unmount&&Q.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||co(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Q.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Ls(r[o],t,n||typeof e.type!="function");n||so(e.__e),e.__c=e.__=e.__e=void 0}function ed(e,t,n){return this.constructor(e,n)}function Dn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),Q.__&&Q.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],ao(t,e=(!r&&n||t).__k=tt(me,null,[e]),o||wr,wr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Rn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Ps(i,e,s)}function Us(e,t){Dn(e,t,Us)}function td(e,t,n){var r,o,i,s,a=bt({},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?Rn.call(arguments,2):n),Pn(e.type,a,r||e.key,o||e.ref,null)}function vt(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,io(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"+xs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Rn=Nr.slice,Q={__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}},vs=0,lt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=bt({},this.state),typeof e=="function"&&(e=e(bt({},n),this.props)),e&&bt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),io(this))},lt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),io(this))},lt.prototype.render=me,Dt=[],Ns=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Cs=function(e,t){return e.__v.__b-t.__v.__b},Cr.__r=0,to=Math.random().toString(8),vr="__d"+to,In="__a"+to,Ts=/(PointerCapture)$|Capture$/i,no=0,ro=Ms(!1),oo=Ms(!0),xs=0;var nd=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:--nd,__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 Q.vnode&&Q.vnode(d),d}var At,fe,uo,Fs,ln=0,Vs=[],Te=Q,js=Te.__b,zs=Te.__r,Ys=Te.diffed,Hs=Te.__c,$s=Te.unmount,Bs=Te.__;function Bt(e,t){Te.__h&&Te.__h(fe,e,ln||t),ln=0;var n=fe.__H||(fe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function V(e){return ln=1,cn(Ws,e)}function cn(e,t,n){var r=Bt(At++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ws(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 $(e,t){var n=Bt(At++,3);!Te.__s&&go(n.__H,t)&&(n.__=e,n.u=t,fe.__H.__h.push(n))}function pt(e,t){var n=Bt(At++,4);!Te.__s&&go(n.__H,t)&&(n.__=e,n.u=t,fe.__h.push(n))}function X(e){return ln=5,le(function(){return{current:e}},[])}function ho(e,t,n){ln=6,pt(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 le(e,t){var n=Bt(At++,7);return go(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ue(e,t){return ln=8,le(function(){return e},t)}function wt(e){var t=fe.context[e.__c],n=Bt(At++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(fe)),t.props.value):e.__}function mo(e,t){Te.useDebugValue&&Te.useDebugValue(t?t(e):e)}function rd(e){var t=Bt(At++,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 po(){var e=Bt(At++,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 od(){for(var e;e=Vs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(xr),t.__h.some(fo),t.__h=[]}catch(n){t.__h=[],Te.__e(n,e.__v)}}}Te.__b=function(e){fe=null,js&&js(e)},Te.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Bs&&Bs(e,t)},Te.__r=function(e){zs&&zs(e),At=0;var t=(fe=e.__c).__H;t&&(uo===fe?(t.__h=[],fe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(xr),t.__h.some(fo),t.__h=[],At=0)),uo=fe},Te.diffed=function(e){Ys&&Ys(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Vs.push(t)!==1&&Fs===Te.requestAnimationFrame||((Fs=Te.requestAnimationFrame)||sd)(od)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),uo=fe=null},Te.__c=function(e,t){t.some(function(n){try{n.__h.some(xr),n.__h=n.__h.filter(function(r){return!r.__||fo(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],Te.__e(r,n.__v)}}),Hs&&Hs(e,t)},Te.unmount=function(e){$s&&$s(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{xr(r)}catch(o){t=o}}),n.__H=void 0,t&&Te.__e(t,n.__v))};var Gs=typeof requestAnimationFrame=="function";function sd(e){var t,n=function(){clearTimeout(r),Gs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Gs&&(t=requestAnimationFrame(n))}function xr(e){var t=fe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),fe=t}function fo(e){var t=fe;e.__c=e.__(),fe=t}function go(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Ws(e,t){return typeof t=="function"?t(e):t}function Ks(e,t){for(var n in t)e[n]=t[n];return e}function _o(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 Eo(e,t){var n=t(),r=V({t:{__:n,u:t}}),o=r[0].t,i=r[1];return pt(function(){o.__=n,o.u=t,yo(o)&&i({t:o})},[e,n,t]),$(function(){return yo(o)&&i({t:o}),e(function(){yo(o)&&i({t:o})})},[e]),n}function yo(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 So(e){e()}function bo(e){return e}function vo(){return[!1,So]}var wo=pt;function kr(e,t){this.props=e,this.context=t}function Gt(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:_o(this.props,o)}function r(o){return this.shouldComponentUpdate=n,tt(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(kr.prototype=new lt).isPureReactComponent=!0,kr.prototype.shouldComponentUpdate=function(e,t){return _o(this.props,e)||_o(this.state,t)};var qs=Q.__b;Q.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),qs&&qs(e)};var id=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function te(e){function t(n){var r=Ks({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=id,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Xs=function(e,t){return e==null?null:Ot(Ot(e).map(t))},ot={map:Xs,forEach:Xs,count:function(e){return e?Ot(e).length:0},only:function(e){var t=Ot(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Ot},ad=Q.__e;Q.__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)}ad(e,t,n,r)};var Zs=Q.unmount;function Js(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=Ks({},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 Js(r,t,n)})),e}function Qs(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Qs(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 Xe(){this.__u=0,this.o=null,this.__b=null}function ei(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function nt(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?tt(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function dn(){this.i=null,this.l=null}Q.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Zs&&Zs(e)},(Xe.prototype=new lt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ei(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]=Qs(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)},Xe.prototype.componentWillUnmount=function(){this.o=[]},Xe.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]=Js(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&tt(me,null,e.fallback);return o&&(o.__u&=-33),[tt(me,null,t.__a?null:e.children),o]};var ti=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 ld(e){return this.getChildContext=function(){return e.context},e.children}function cd(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Dn(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)}}}Dn(tt(ld,{context:t.context},e.__v),t.v)}function ni(e,t){var n=tt(cd,{__v:e,h:t});return n.containerInfo=t,n}(dn.prototype=new lt).__a=function(e){var t=this,n=ei(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),ti(t,e,r)):o()};n?n(i):i()}},dn.prototype.render=function(e){this.i=null,this.l=new Map;var t=Ot(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},dn.prototype.componentDidUpdate=dn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){ti(e,n,t)})};var ri=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,dd=/^(?: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]/,ud=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,hd=/[A-Z0-9]/g,md=typeof document<"u",pd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function No(e,t,n){return t.__k==null&&(t.textContent=""),Dn(e,t),typeof n=="function"&&n(),e?e.__c:null}function oi(e,t,n){return Us(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 si=Q.event;Q.event=function(e){return si&&(e=si(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Co,fd={configurable:!0,get:function(){return this.class}},ii=Q.vnode;Q.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||md&&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"||pd(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":ud.test(s)&&(s=c):c=s="oninput":i&&dd.test(s)?s=s.replace(hd,"-$&").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=Ot(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=Ot(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",fd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=ri,ii&&ii(e)};var ai=Q.__r;Q.__r=function(e){ai&&ai(e),Co=e.__c};var li=Q.diffed;Q.diffed=function(e){li&&li(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),Co=null};var ci={ReactCurrentDispatcher:{current:{readContext:function(e){return Co.__n[e.__c].props.value},useCallback:ue,useContext:wt,useDebugValue:mo,useDeferredValue:bo,useEffect:$,useId:po,useImperativeHandle:ho,useInsertionEffect:wo,useLayoutEffect:pt,useMemo:le,useReducer:cn,useRef:X,useState:V,useSyncExternalStore:Eo,useTransition:vo}}},gd="18.3.1";function di(e){return tt.bind(null,e)}function st(e){return!!e&&e.$$typeof===ri}function ui(e){return st(e)&&e.type===me}function hi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Lt(e){return st(e)?td.apply(null,arguments):e}function To(e){return!!e.__k&&(Dn(null,e),!0)}function mi(e){return e&&(e.base||e.nodeType===1&&e)||null}var pi=function(e,t){return e(t)},fi=function(e,t){var n=Q.debounceRendering;Q.debounceRendering=function(o){return o()};var r=e(t);return Q.debounceRendering=n,r},gi=st,Ln={useState:V,useId:po,useReducer:cn,useEffect:$,useLayoutEffect:pt,useInsertionEffect:wo,useTransition:vo,useDeferredValue:bo,useSyncExternalStore:Eo,startTransition:So,useRef:X,useImperativeHandle:ho,useMemo:le,useCallback:ue,useContext:wt,useDebugValue:mo,version:"18.3.1",Children:ot,render:No,hydrate:oi,unmountComponentAtNode:To,createPortal:ni,createElement:tt,createContext:vt,createFactory:di,cloneElement:Lt,createRef:ks,Fragment:me,isValidElement:st,isElement:gi,isFragment:ui,isMemo:hi,findDOMNode:mi,Component:lt,PureComponent:kr,memo:Gt,forwardRef:te,flushSync:fi,unstable_batchedUpdates:pi,StrictMode:me,Suspense:Xe,SuspenseList:dn,lazy:nt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ci};const xo=Object.freeze(Object.defineProperty({__proto__:null,Children:ot,Component:lt,Fragment:me,PureComponent:kr,StrictMode:me,Suspense:Xe,SuspenseList:dn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ci,cloneElement:Lt,createContext:vt,createElement:tt,createFactory:di,createPortal:ni,createRef:ks,default:Ln,findDOMNode:mi,flushSync:fi,forwardRef:te,hydrate:oi,isElement:gi,isFragment:ui,isMemo:hi,isValidElement:st,lazy:nt,memo:Gt,render:No,startTransition:So,unmountComponentAtNode:To,unstable_batchedUpdates:pi,useCallback:ue,useContext:wt,useDebugValue:mo,useDeferredValue:bo,useEffect:$,useErrorBoundary:rd,useId:po,useImperativeHandle:ho,useInsertionEffect:wo,useLayoutEffect:pt,useMemo:le,useReducer:cn,useRef:X,useState:V,useSyncExternalStore:Eo,useTransition:vo,version:gd},Symbol.toStringTag,{value:"Module"}));function _d(e){return{render:function(t){No(t,e)},unmount:function(){To(e)}}}function _i(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ko(...e){return t=>{let n=!1;const r=e.map(o=>{const i=_i(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():_i(e[o],null)}}}}function Ut(...e){return ue(ko(...e),e)}function Ed(e){const t=yd(e),n=te((r,o)=>{const{children:i,...s}=r,a=ot.toArray(i),c=a.find(bd);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)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function yd(e){const t=te((n,r)=>{const{children:o,...i}=n;if(st(o)){const s=wd(o),a=vd(i,o.props);return o.type!==me&&(a.ref=r?ko(r,s):s),Lt(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Sd=Symbol("radix.slottable");function bd(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Sd}function vd(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 wd(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 Nd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],un=Nd.reduce((e,t)=>{const n=Ed(`Primitive.${t}`),r=te((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}},{}),Wt=globalThis?.document?pt:()=>{};function Cd(e,t){return cn((n,r)=>t[n][r]??n,e)}var hn=e=>{const{present:t,children:n}=e,r=Td(t),o=typeof n=="function"?n({present:r.isPresent}):ot.only(n),i=Ut(r.ref,xd(o));return typeof n=="function"||r.isPresent?Lt(o,{ref:i}):null};hn.displayName="Presence";function Td(e){const[t,n]=V(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,c]=Cd(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return $(()=>{const d=Or(r.current);i.current=a==="mounted"?d:"none"},[a]),Wt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Or(d);e?c("MOUNT"):p==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Wt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const g=Or(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=Or(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:ue(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Or(e){return e?.animationName||"none"}function xd(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 Ei(e,t=[]){let n=[];function r(i,s){const a=vt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[c]||a,S=le(()=>g,Object.values(g));return l(f.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[c]||a,g=wt(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=>vt(s));return function(s){const a=s?.[e]||i;return le(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,kd(o,...t)]}function kd(...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 le(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Ft(e){const t=X(e);return $(()=>{t.current=e}),le(()=>(...n)=>t.current?.(...n),[])}var Od=vt(void 0);function Ad(e){const t=wt(Od);return e||t||"ltr"}function Rd(e,[t,n]){return Math.min(n,Math.max(t,e))}function Vt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Id(e,t){return cn((n,r)=>t[n][r]??n,e)}var Oo="ScrollArea",[yi]=Ei(Oo),[Md,ct]=yi(Oo),Si=te((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,S]=V(null),[m,_]=V(0),[y,O]=V(0),[T,v]=V(!1),[x,b]=V(!1),w=Ut(t,D=>c(D)),N=Ad(o);return l(Md,{scope:n,type:r,dir:N,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:E,onScrollbarXChange:g,scrollbarXEnabled:T,onScrollbarXEnabledChange:v,scrollbarY:f,onScrollbarYChange:S,scrollbarYEnabled:x,onScrollbarYEnabledChange:b,onCornerWidthChange:_,onCornerHeightChange:O,children:l(un.div,{dir:N,...s,ref:w,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});Si.displayName=Oo;var bi="ScrollAreaViewport",vi=te((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ct(bi,n),a=X(null),c=Ut(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(un.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})})]})});vi.displayName=bi;var Nt="ScrollAreaScrollbar",Ao=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(Nt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return $(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?l(Pd,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(Dd,{...r,ref:t,forceMount:n}):o.type==="auto"?l(wi,{...r,ref:t,forceMount:n}):o.type==="always"?l(Ro,{...r,ref:t}):null});Ao.displayName=Nt;var Pd=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(Nt,e.__scopeScrollArea),[i,s]=V(!1);return $(()=>{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(hn,{present:n||i,children:l(wi,{"data-state":i?"visible":"hidden",...r,ref:t})})}),Dd=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(Nt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Mr(()=>c("SCROLL_END"),100),[a,c]=Id("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 $(()=>{if(a==="idle"){const d=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,c]),$(()=>{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(hn,{present:n||a!=="hidden",children:l(Ro,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Vt(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Vt(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),wi=te((e,t)=>{const n=ct(Nt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=V(!1),a=e.orientation==="horizontal",c=Mr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return mn(n.viewport,c),mn(n.content,c),l(hn,{present:r||i,children:l(Ro,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Ro=te((e,t)=>{const{orientation:n="vertical",...r}=e,o=ct(Nt,e.__scopeScrollArea),i=X(null),s=X(0),[a,c]=V({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=ki(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 zd(p,s.current,a,E)}return n==="horizontal"?l(Ld,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,E=Oi(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(Ud,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,E=Oi(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}),Ld=te((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(Nt,e.__scopeScrollArea),[s,a]=V(),c=X(null),d=Ut(t,c,i.onScrollbarXChange);return $(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ci,{"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":Ir(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),Ri(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:Rr(s.paddingLeft),paddingEnd:Rr(s.paddingRight)}})}})}),Ud=te((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(Nt,e.__scopeScrollArea),[s,a]=V(),c=X(null),d=Ut(t,c,i.onScrollbarYChange);return $(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ci,{"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":Ir(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),Ri(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:Rr(s.paddingTop),paddingEnd:Rr(s.paddingBottom)}})}})}),[Fd,Ni]=yi(Nt),Ci=te((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(Nt,n),[g,f]=V(null),S=Ut(t,w=>f(w)),m=X(null),_=X(""),y=E.viewport,O=r.content-r.viewport,T=Ft(h),v=Ft(c),x=Mr(u,10);function b(w){if(m.current){const N=w.clientX-m.current.left,D=w.clientY-m.current.top;d({x:N,y:D})}}return $(()=>{const w=N=>{const D=N.target;g?.contains(D)&&T(N,O)};return document.addEventListener("wheel",w,{passive:!1}),()=>document.removeEventListener("wheel",w,{passive:!1})},[y,g,O,T]),$(v,[r,v]),mn(g,x),mn(E.content,x),l(Fd,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:v,onThumbPointerDown:Ft(a),children:l(un.div,{...p,ref:S,style:{position:"absolute",...p.style},onPointerDown:Vt(e.onPointerDown,w=>{w.button===0&&(w.target.setPointerCapture(w.pointerId),m.current=g.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),b(w))}),onPointerMove:Vt(e.onPointerMove,b),onPointerUp:Vt(e.onPointerUp,w=>{const N=w.target;N.hasPointerCapture(w.pointerId)&&N.releasePointerCapture(w.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Ar="ScrollAreaThumb",Ti=te((e,t)=>{const{forceMount:n,...r}=e,o=Ni(Ar,e.__scopeScrollArea);return l(hn,{present:n||o.hasThumb,children:l(Vd,{ref:t,...r})})}),Vd=te((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ct(Ar,n),s=Ni(Ar,n),{onThumbPositionChange:a}=s,c=Ut(t,u=>s.onThumbChange(u)),d=X(void 0),h=Mr(()=>{d.current&&(d.current(),d.current=void 0)},100);return $(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const E=Yd(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),l(un.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:Vt(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:Vt(e.onPointerUp,s.onThumbPointerUp)})});Ti.displayName=Ar;var Io="ScrollAreaCorner",xi=te((e,t)=>{const n=ct(Io,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(jd,{...e,ref:t}):null});xi.displayName=Io;var jd=te((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ct(Io,n),[i,s]=V(0),[a,c]=V(0),d=!!(i&&a);return mn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),mn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(un.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 Rr(e){return e?parseInt(e,10):0}function ki(e,t){const n=e/t;return isNaN(n)?0:n}function Ir(e){const t=ki(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function zd(e,t,n,r="ltr"){const o=Ir(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 Ai([c,d],u)(e)}function Oi(e,t,n="ltr"){const r=Ir(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=Rd(e,c);return Ai([0,s],[0,a])(d)}function Ai(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 Ri(e,t){return e>0&&e<t}var Yd=(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 Mr(e,t){const n=Ft(e),r=X(0);return $(()=>()=>window.clearTimeout(r.current),[]),ue(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function mn(e,t){const n=Ft(t);Wt(()=>{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 Ii=Si,Hd=vi,$d=xi;function Bd(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 pn={},Un={},Mi={},Fn={},Vn={},jn={},Pi;function Mo(){if(Pi)return jn;Pi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.EventEmitter=void 0;let e=class{constructor(){A(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 jn.EventEmitter=e,jn}var fn={},Di;function zn(){return Di||(Di=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.DisconnectionReason=fn.ConnectionStatus=void 0,fn.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},fn.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"}),fn}var Li;function Po(){if(Li)return Vn;Li=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.BaseConnection=void 0;const e=Mo(),t=zn();let n=class{constructor(){A(this,"status",t.ConnectionStatus.CONNECTING);A(this,"queue",[]);A(this,"eventEmitter",new e.EventEmitter);A(this,"disconnectionDetails",null);A(this,"onErrorCallback",null);A(this,"onDisconnectCallback",null);A(this,"onMessageCallback",null);A(this,"onOpenCallback",null);A(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 Vn.BaseConnection=n,Vn}var Ui={},Fi;function it(){return Fi||(Fi=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=T,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(b,w=e.SynapseErrorCode.UNKNOWN,N={}){super(b);A(this,"code");A(this,"timestamp");A(this,"cause");A(this,"context");A(this,"hint");A(this,"displayMessage");A(this,"reason");this.name="SynapseError",this.code=w,this.timestamp=new Date,this.cause=N.cause,this.context=N.context,this.hint=N.hint,this.reason=N.reason,this.displayMessage=N.displayMessage||N?.hint||b,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(b,w,N,D){const W=n.makeMessage(w,N,b);super(W,e.SynapseErrorCode.API,{cause:N,context:{status:w,hasBody:!!N},hint:w&&w>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:b||"Something went wrong"});A(this,"status");A(this,"error");A(this,"headers");this.name="APIError",this.status=w,this.error=N,this.headers=D}static makeMessage(b,w,N){const D=w instanceof Error?w.message:N;return b&&D?`HTTP ${b}: ${D}`:b?`${b} status code (no body)`:D||"(no status code or body)"}static generate(b,w,N,D){if(!b)return new r({message:N});const W=w?.error,G=W&&typeof W=="object"&&!Array.isArray(W)?W:void 0;switch(b){case 400:return new i(N||"Bad Request",b,G,D);case 401:return new s(N||"Unauthorized",b,G,D);case 403:return new a(N||"Permission Denied",b,G,D);case 404:return new c(N||"Not Found",b,G,D);case 405:return new d(N||"Method Not Allowed",b,G,D);case 429:return new h(N||"Rate Limit Exceeded",b,G,D);case 500:return new u(N||"Internal Server Error",b,G,D);default:return new n(N||"API Error",b,G,D)}}}e.APIError=n;class r extends n{constructor({message:x}={}){super(x||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:x}={}){super(x||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(x,b,w,N){super(x,b,w,N),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.CONNECTION,b),this.name="ConnectionError"}}e.ConnectionError=p;class E extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.RECORDING,b),this.name="RecordingError"}}e.RecordingError=E;class g extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.AUTH,b),this.name="AuthenticationError"}}e.AuthenticationError=g;class f extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.FILE,b),this.name="FileError"}}e.FileError=f;class S extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.SESSION,b),this.name="SessionError"}}e.SessionError=S;class m extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.MESSAGE,b),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.STORE,b),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.CONFIGURATION,b),this.name="ConfigurationError"}}e.ConfigurationError=y;class O extends t{constructor(x,b={}){super(x,e.SynapseErrorCode.VALIDATION,b),this.name="ValidationError"}}e.ValidationError=O;function T(v,x,b,w={}){if(v instanceof x)return v;const N={...w,context:{...v instanceof t?v.context:void 0,...w.context},hint:w.hint??(v instanceof t?v.hint:void 0),reason:w.reason??(v instanceof t?v.reason:void 0),cause:w.cause??v};if(v instanceof t)return new x(v.message,N);const D=v instanceof Error&&v.message?v.message:b;return new x(D,N)}})(Ui)),Ui}var Vi;function ji(){if(Vi)return Fn;Vi=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.WebSocketConnection=void 0;const e=Po(),t=zn(),n=it();class r extends e.BaseConnection{constructor(s){super();A(this,"conversationId");A(this,"socket",null);A(this,"config");A(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 Fn.WebSocketConnection=r,Fn}var Yn={},zi={},Yi;function Hi(){return Yi||(Yi=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})(zi)),zi}var $i;function Bi(){if($i)return Yn;$i=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.SSEConnection=void 0;const e=Po(),t=zn(),n=Hi(),r=it();class o extends e.BaseConnection{constructor(a){super();A(this,"conversationId");A(this,"config");A(this,"connected",!1);A(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 Yn.SSEConnection=o,Yn}var Gi;function Wi(){return Gi||(Gi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=ji(),n=Bi(),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})(Mi)),Mi}var Hn={},Ki;function Do(){if(Ki)return Hn;Ki=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.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 Hn.getConfig=r,Hn}var $n={},Bn={},qi;function Pr(){if(qi)return Bn;qi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.HttpClient=void 0;const e=it();let t=class{constructor(n){A(this,"baseUrl");A(this,"headers");A(this,"timeout");A(this,"maxRetries");A(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 Bn.HttpClient=t,Bn}var Gn={},Wn={},Xi;function Kn(){if(Xi)return Wn;Xi=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.BaseResource=void 0;let e=class{constructor(t){A(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 Wn.BaseResource=e,Wn}var Zi;function Ji(){if(Zi)return Gn;Zi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.Session=void 0;const e=Kn();let t=class extends e.BaseResource{constructor(){super(...arguments);A(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 Gn.Session=t,Gn}var qn={},Qi;function Lo(){if(Qi)return qn;Qi=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Config=void 0;const e=Kn();let t=class extends e.BaseResource{constructor(){super(...arguments);A(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 qn.Config=t,qn}var ea={},ta;function na(){return ta||(ta=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Pr(),n=Do(),r=Lo(),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}})(ea)),ea}var Xn={},ra;function Uo(){if(ra)return Xn;ra=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.Auth=void 0;const e=Kn();let t=class extends e.BaseResource{constructor(){super(...arguments);A(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 Xn.Auth=t,Xn}var Zn={},gn={},oa;function Fo(){return oa||(oa=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.ErrorType=gn.SYNAPSE_RECOVERY_REASON=void 0,gn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},gn.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"}),gn}var Jn={},sa;function Vo(){if(sa)return Jn;sa=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.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 Jn.ErrorUtils=t,Jn}var ia={},aa;function la(){return aa||(aa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=Pr(),n=Do(),r=Vo(),o=Uo(),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}})(ia)),ia}var ca;function Gd(){if(ca)return Zn;ca=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.TokenManager=void 0;const e=it(),t=Fo(),n=Vo(),r=la();let o=class{constructor(i,s,a,c){A(this,"auth");A(this,"httpClient");A(this,"agentId");A(this,"partnerAuthToken");A(this,"refreshToken");A(this,"sessToken");A(this,"_userId");A(this,"_level");A(this,"_expiresAt");A(this,"lastResponse");A(this,"initPromise",null);A(this,"refreshPromise",null);A(this,"prefetchKey");A(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 Zn.TokenManager=o,Zn}var Qn={},da;function Wd(){var n;if(da)return Qn;da=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.VoiceResource=void 0;const e=Kn();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)}},A(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),A(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Qn.VoiceResource=t,Qn}var ua;function ha(){if(ua)return $n;ua=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.ResourceManager=void 0;const e=Pr(),t=Ji(),n=it(),r=Lo(),o=na(),i=Uo(),s=Gd(),a=Wd();class c{constructor(h){A(this,"resourceConfig");A(this,"httpClient");A(this,"session");A(this,"config");A(this,"auth");A(this,"tokenManager");A(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,...S}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...p&&{user_context:p},...(E||Object.keys(S).length>0)&&{session_context:{...E&&{intent:E},...g&&{user_location:g},...S}},...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 $n.ResourceManager=c,$n}var er={},ma={},pa;function jo(){return pa||(pa=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)}})(ma)),ma}var fa={},ga;function Kd(){return ga||(ga=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(){A(this,"pendingFiles",[]);A(this,"pendingMessage","");A(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})(fa)),fa}var ft={},_a;function Dr(){if(_a)return ft;_a=1,Object.defineProperty(ft,"__esModule",{value:!0}),ft.SYNAPSE_REALTIME_RESERVED_EVENTS=ft.SYNAPSE_REALTIME_ERROR_CODES=ft.SYNAPSE_REALTIME_EVENTS=ft.SYNAPSE_MESSAGE_TYPES=void 0;const e=jo();return ft.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,ft.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"},ft.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"},ft.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},ft}var tr={},Ea;function qd(){if(Ea)return tr;Ea=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.AudioManager=void 0;const e=it();class t{constructor(r={}){A(this,"mediaRecorder",null);A(this,"mediaStream",null);A(this,"recordingStartTime",0);A(this,"autoPauseTimer",null);A(this,"config");A(this,"onAudioData",null);A(this,"onAudioError",null);A(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 tr.AudioManager=t,tr}var ya;function Sa(){if(ya)return er;ya=1,Object.defineProperty(er,"__esModule",{value:!0}),er.MessageManager=void 0;const e=jo(),t=Kd(),n=Dr(),r=qd(),o=it();let i=class{constructor(s){A(this,"connection",null);A(this,"callbacks",null);A(this,"fileManager",null);A(this,"audioManager",null);A(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 S=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}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 S=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}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 er.MessageManager=i,er}var ba={},va;function Xd(){return va||(va=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})(ba)),ba}var nr={},rr={},wa;function Zd(){if(wa)return rr;wa=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){A(this,"audioCtx",null);A(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 rr.VoiceAudioAnalyser=t,rr}var _n={},Na;function Ca(){return Na||(Na=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.VOICE_AGENT_EVENTS=_n.VOICE_AGENT_STATE=void 0,_n.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},_n.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),_n}var Ta;function Jd(){if(Ta)return nr;Ta=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceAgent=void 0;const e=Mo(),t=Zd(),n=it(),r=Ca(),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){A(this,"config");A(this,"resourceManager");A(this,"getCredentials");A(this,"emitter",new e.EventEmitter);A(this,"remoteAnalyser",new t.VoiceAudioAnalyser);A(this,"localAnalyser",new t.VoiceAudioAnalyser);A(this,"pc",null);A(this,"pcId",null);A(this,"dataChannel",null);A(this,"localStream",null);A(this,"remoteAudio",null);A(this,"_state",r.VOICE_AGENT_STATE.IDLE);A(this,"_isMuted",!1);A(this,"manuallyDisconnected",!1);A(this,"_hasConnectionFailureNotified",!1);A(this,"_userSpeaking",!1);A(this,"_silenceTimer",null);A(this,"_cachedIceServers",null);A(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 S=_=>({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(S(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(S(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 nr.VoiceAgent=d,nr}var xa;function Qd(){if(xa)return Un;xa=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.SynapseSDK=void 0;const e=Wi(),t=zn(),n=Do(),r=ha(),o=Sa(),i=Dr(),s=Mo(),a=it(),c=Fo(),d=Xd(),h=jo(),u=Jd();class p{constructor(g){A(this,"connection",null);A(this,"messageManager");A(this,"resourceManager");A(this,"sessionConfig",null);A(this,"config");A(this,"connectionType");A(this,"isRefreshingSession",!1);A(this,"isRecovering",!1);A(this,"forceConsumed",!1);A(this,"connectionAttempts",0);A(this,"sdkEventEmitter",new s.EventEmitter);A(this,"_voice",null);A(this,"pendingNetworkReconnect",!1);A(this,"boundOnlineHandler",null);A(this,"isReconnecting",!1);A(this,"reconnectTimer",null);A(this,"boundVisibilityHandler",null);A(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:S=>this.config.callbacks?.onTokenExchange?.(S)}),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:S,tool_declined:m,tool_id:_,initial_prompts:y,tool_result:O}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:g,files:f,audio:S,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...O&&Object.keys(O)?.length&&{tool_result:O}})}catch(v){this.emitError(v)}break;default:const T=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(T),T}}async sendMessageFeedback(g,f,S){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:S});break}}async sendSessionFeedback(g,f){if(!this.connection){const S=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(S),S}if(!this.sessionConfig?.session_id){const S=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(S),S}if(!g?.length&&!f){const S=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(S),S}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,S){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,S);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 S=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(S),S}}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,S,m){return(0,a.normalizeError)(g,a.SessionError,f,{context:S,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),S=this.connectionType===e.ConnectionType.SOCKET,m=S?f.WEBSOCKET_URL:f.BASE_API_URL,_=this.config.serverUrl?S?`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=(O,...T)=>{y(O,...T),this.sdkEventEmitter.emit(O,...T)}}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 S=(0,d.outcomeForCloseCode)(f.code);if(S){await this.handleRecovery(S,f);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(f)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(g){if(g instanceof a.APIError){const S=(0,d.outcomeForHttpStatus)(g.status);if(S){this.handleRecovery(S,{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,S){this.emitError(new a.SessionError(f,{reason:g,cause:S,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 S=this.statusOf(f);if(S===401||S===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,S,m){return(0,a.normalizeError)(g,a.ConnectionError,f,{context:S,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 Un.SynapseSDK=p,Un}var ka={},Oa;function eu(){return Oa||(Oa=1,Object.defineProperty(ka,"__esModule",{value:!0})),ka}var Lr={},Aa;function tu(){return Aa||(Aa=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.USER_FEEDBACK=void 0,Lr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Lr}var Ra={},Ia;function nu(){return Ia||(Ia=1,Object.defineProperty(Ra,"__esModule",{value:!0})),Ra}var or={},Ma;function ru(){if(Ma)return or;Ma=1,Object.defineProperty(or,"__esModule",{value:!0}),or.ToolCall=void 0;const e=Kn();let t=class extends e.BaseResource{constructor(){super(...arguments);A(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 or.ToolCall=t,or}var Ze={},Pa;function ou(){if(Pa)return Ze;Pa=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.SYNAPSE_EICITATION_STATUS=Ze.SYNAPSE_CTA_ACTIONS=Ze.SYNAPSE_TOOL_FORMATS=Ze.SYNAPSE_TOOL_CALLBACK_NAME=Ze.SYNAPSE_COMPONENTS=Ze.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||(Ze.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||(Ze.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||(Ze.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Ze.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Ze.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Ze.SYNAPSE_EICITATION_STATUS=i={})),Ze}var Da={},La;function su(){return La||(La=1,Object.defineProperty(Da,"__esModule",{value:!0})),Da}var Ua={},Fa;function iu(){return Fa||(Fa=1,Object.defineProperty(Ua,"__esModule",{value:!0})),Ua}var sr={},Va;function au(){if(Va)return sr;Va=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(sr.SYNAPSE_CONVERSATION=e={})),sr}var En={},ja;function lu(){return ja||(ja=1,(function(e){var t=En&&En.__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=En&&En.__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(Ca(),e)})(En)),En}var za;function cu(){return za||(za=1,(function(e){var t=pn&&pn.__createBinding||(Object.create?(function(v,x,b,w){w===void 0&&(w=b);var N=Object.getOwnPropertyDescriptor(x,b);(!N||("get"in N?!x.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return x[b]}}),Object.defineProperty(v,w,N)}):(function(v,x,b,w){w===void 0&&(w=b),v[w]=x[b]})),n=pn&&pn.__exportStar||function(v,x){for(var b in v)b!=="default"&&!Object.prototype.hasOwnProperty.call(x,b)&&t(x,v,b)};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=Qd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Po();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=ji();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Bi();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Wi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(zn(),e);var c=ha();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(eu(),e);var d=Ji();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(tu(),e);var h=Uo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=la();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(nu(),e);var p=Lo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var E=na();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var g=ru();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return g.ToolCall}}),n(ou(),e);var f=Sa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return f.MessageManager}}),n(Dr(),e),n(su(),e);var S=Pr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return S.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 _=Fo();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=Vo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(iu(),e);var O=Hi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return O.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return O.DEFAULT_CHANNEL}});var T=Dr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return T.SYNAPSE_MESSAGE_TYPES}}),n(au(),e),n(lu(),e)})(pn)),pn}var R=cu();function Ya(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=Ya(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ha(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ya(e))&&(r&&(r+=" "),r+=t);return r}const du=(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},uu=(e,t)=>({classGroupId:e,validator:t}),$a=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ur="-",Ba=[],hu="arbitrary..",mu=e=>{const t=fu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return pu(o);const i=o.split(Ur),s=i[0]===""&&i.length>1?1:0;return Ga(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?du(a,s):s:a||Ba}return n[o]||Ba}}},Ga=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=Ga(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(Ur):e.slice(t).join(Ur),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},pu=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?hu+r:void 0})(),fu=e=>{const{theme:t,classGroups:n}=e;return gu(n,t)},gu=(e,t)=>{const n=$a();for(const r in e){const o=e[r];zo(o,n,r,t)}return n},zo=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];_u(s,t,n,r)}},_u=(e,t,n,r)=>{if(typeof e=="string"){Eu(e,t,n);return}if(typeof e=="function"){yu(e,t,n,r);return}Su(e,t,n,r)},Eu=(e,t,n)=>{const r=e===""?t:Wa(t,e);r.classGroupId=n},yu=(e,t,n,r)=>{if(bu(e)){zo(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(uu(n,e))},Su=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];zo(c,Wa(t,a),n,r)}},Wa=(e,t)=>{let n=e;const r=t.split(Ur),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=$a(),n.nextPart.set(s,a)),n=a}return n},bu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,vu=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)}}},Yo="!",Ka=":",wu=[],qa=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Nu=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 S=o[f];if(s===0&&a===0){if(S===Ka){i.push(o.slice(c,f)),c=f+1;continue}if(S==="/"){d=f;continue}}S==="["?s++:S==="]"?s--:S==="("?a++:S===")"&&a--}const u=i.length===0?o:o.slice(c);let p=u,E=!1;u.endsWith(Yo)?(p=u.slice(0,-1),E=!0):u.startsWith(Yo)&&(p=u.slice(1),E=!0);const g=d&&d>c?d-c:void 0;return qa(i,E,p,g)};if(t){const o=t+Ka,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):qa(wu,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Cu=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}},Tu=e=>({cache:vu(e.cacheSize),parseClassName:Nu(e),sortModifiers:Cu(e),...mu(e)}),xu=/\s+/,ku=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(xu);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 S=!!f,m=r(S?g.substring(0,f):g);if(!m){if(!S){c=h+(c.length>0?" "+c:c);continue}if(m=r(g),!m){c=h+(c.length>0?" "+c:c);continue}S=!1}const _=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=E?_+Yo:_,O=y+m;if(s.indexOf(O)>-1)continue;s.push(O);const T=o(m,S);for(let v=0;v<T.length;++v){const x=T[v];s.push(y+x)}c=h+(c.length>0?" "+c:c)}return c},Ou=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Xa(n))&&(o&&(o+=" "),o+=r);return o},Xa=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Xa(e[r]))&&(n&&(n+=" "),n+=t);return n},Au=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=Tu(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=ku(c,n);return o(c,h),h};return i=s,(...c)=>i(Ou(...c))},Ru=[],Fe=e=>{const t=n=>n[e]||Ru;return t.isThemeGetter=!0,t},Za=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ja=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Iu=/^\d+\/\d+$/,Mu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Pu=/\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$/,Du=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Lu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Uu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,yn=e=>Iu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),jt=e=>!!e&&Number.isInteger(Number(e)),Ho=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Rt=e=>Mu.test(e),Fu=()=>!0,Vu=e=>Pu.test(e)&&!Du.test(e),Qa=()=>!1,ju=e=>Lu.test(e),zu=e=>Uu.test(e),Yu=e=>!Y(e)&&!H(e),Hu=e=>Sn(e,ol,Qa),Y=e=>Za.test(e),Kt=e=>Sn(e,sl,Vu),$o=e=>Sn(e,Ku,ne),el=e=>Sn(e,nl,Qa),$u=e=>Sn(e,rl,zu),Fr=e=>Sn(e,il,ju),H=e=>Ja.test(e),ir=e=>bn(e,sl),Bu=e=>bn(e,qu),tl=e=>bn(e,nl),Gu=e=>bn(e,ol),Wu=e=>bn(e,rl),Vr=e=>bn(e,il,!0),Sn=(e,t,n)=>{const r=Za.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},bn=(e,t,n=!1)=>{const r=Ja.exec(e);return r?r[1]?t(r[1]):n:!1},nl=e=>e==="position"||e==="percentage",rl=e=>e==="image"||e==="url",ol=e=>e==="length"||e==="size"||e==="bg-size",sl=e=>e==="length",Ku=e=>e==="number",qu=e=>e==="family-name",il=e=>e==="shadow",Xu=()=>{const e=Fe("color"),t=Fe("font"),n=Fe("text"),r=Fe("font-weight"),o=Fe("tracking"),i=Fe("leading"),s=Fe("breakpoint"),a=Fe("container"),c=Fe("spacing"),d=Fe("radius"),h=Fe("shadow"),u=Fe("inset-shadow"),p=Fe("text-shadow"),E=Fe("drop-shadow"),g=Fe("blur"),f=Fe("perspective"),S=Fe("aspect"),m=Fe("ease"),_=Fe("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],O=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...O(),H,Y],v=()=>["auto","hidden","clip","visible","scroll"],x=()=>["auto","contain","none"],b=()=>[H,Y,c],w=()=>[yn,"full","auto",...b()],N=()=>[jt,"none","subgrid",H,Y],D=()=>["auto",{span:["full",jt,H,Y]},jt,H,Y],W=()=>[jt,"auto",H,Y],G=()=>["auto","min","max","fr",H,Y],Ce=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],ie=()=>["auto",...b()],_e=()=>[yn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],F=()=>[e,H,Y],de=()=>[...O(),tl,el,{position:[H,Y]}],Oe=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Gu,Hu,{size:[H,Y]}],Z=()=>[Ho,ir,Kt],L=()=>["","none","full",d,H,Y],K=()=>["",ne,ir,Kt],re=()=>["solid","dashed","dotted","double"],xe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ne,Ho,tl,el],Ae=()=>["","none",g,H,Y],Ye=()=>["none",ne,H,Y],ae=()=>["none",ne,H,Y],Pe=()=>[ne,H,Y],De=()=>[yn,"full",...b()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Rt],breakpoint:[Rt],color:[Fu],container:[Rt],"drop-shadow":[Rt],ease:["in","out","in-out"],font:[Yu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Rt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Rt],shadow:[Rt],spacing:["px",ne],text:[Rt],"text-shadow":[Rt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",yn,Y,H,S]}],container:["container"],columns:[{columns:[ne,Y,H,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:T()}],overflow:[{overflow:v()}],"overflow-x":[{"overflow-x":v()}],"overflow-y":[{"overflow-y":v()}],overscroll:[{overscroll:x()}],"overscroll-x":[{"overscroll-x":x()}],"overscroll-y":[{"overscroll-y":x()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:w()}],"inset-x":[{"inset-x":w()}],"inset-y":[{"inset-y":w()}],start:[{start:w()}],end:[{end:w()}],top:[{top:w()}],right:[{right:w()}],bottom:[{bottom:w()}],left:[{left:w()}],visibility:["visible","invisible","collapse"],z:[{z:[jt,"auto",H,Y]}],basis:[{basis:[yn,"full","auto",a,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,yn,"auto","initial","none",Y]}],grow:[{grow:["",ne,H,Y]}],shrink:[{shrink:["",ne,H,Y]}],order:[{order:[jt,"first","last","none",H,Y]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":W()}],"row-end":[{"row-end":W()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...Ce(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...Ce()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":Ce()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:ie()}],mx:[{mx:ie()}],my:[{my:ie()}],ms:[{ms:ie()}],me:[{me:ie()}],mt:[{mt:ie()}],mr:[{mr:ie()}],mb:[{mb:ie()}],ml:[{ml:ie()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"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,ir,Kt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,H,$o]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ho,Y]}],"font-family":[{font:[Bu,Y,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,H,Y]}],"line-clamp":[{"line-clamp":[ne,"none",H,$o]}],leading:[{leading:[i,...b()]}],"list-image":[{"list-image":["none",H,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",H,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",H,Kt]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[ne,"auto",H,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:b()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",H,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",H,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:de()}],"bg-repeat":[{bg:Oe()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},jt,H,Y],radial:["",H,Y],conic:[jt,H,Y]},Wu,$u]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:Z()}],"gradient-via-pos":[{via:Z()}],"gradient-to-pos":[{to:Z()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:L()}],"rounded-s":[{"rounded-s":L()}],"rounded-e":[{"rounded-e":L()}],"rounded-t":[{"rounded-t":L()}],"rounded-r":[{"rounded-r":L()}],"rounded-b":[{"rounded-b":L()}],"rounded-l":[{"rounded-l":L()}],"rounded-ss":[{"rounded-ss":L()}],"rounded-se":[{"rounded-se":L()}],"rounded-ee":[{"rounded-ee":L()}],"rounded-es":[{"rounded-es":L()}],"rounded-tl":[{"rounded-tl":L()}],"rounded-tr":[{"rounded-tr":L()}],"rounded-br":[{"rounded-br":L()}],"rounded-bl":[{"rounded-bl":L()}],"border-w":[{border:K()}],"border-w-x":[{"border-x":K()}],"border-w-y":[{"border-y":K()}],"border-w-s":[{"border-s":K()}],"border-w-e":[{"border-e":K()}],"border-w-t":[{"border-t":K()}],"border-w-r":[{"border-r":K()}],"border-w-b":[{"border-b":K()}],"border-w-l":[{"border-l":K()}],"divide-x":[{"divide-x":K()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":K()}],"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,H,Y]}],"outline-w":[{outline:["",ne,ir,Kt]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",h,Vr,Fr]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",u,Vr,Fr]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:K()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[ne,Kt]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":K()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",p,Vr,Fr]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[ne,H,Y]}],"mix-blend":[{"mix-blend":[...xe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":xe()}],"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":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"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":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"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":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"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":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"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":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"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":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"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":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[H,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"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":O()}],"mask-image-conic-pos":[{"mask-conic":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"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:de()}],"mask-repeat":[{mask:Oe()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",H,Y]}],filter:[{filter:["","none",H,Y]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,H,Y]}],contrast:[{contrast:[ne,H,Y]}],"drop-shadow":[{"drop-shadow":["","none",E,Vr,Fr]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",ne,H,Y]}],"hue-rotate":[{"hue-rotate":[ne,H,Y]}],invert:[{invert:["",ne,H,Y]}],saturate:[{saturate:[ne,H,Y]}],sepia:[{sepia:["",ne,H,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",H,Y]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,H,Y]}],"backdrop-contrast":[{"backdrop-contrast":[ne,H,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,H,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,H,Y]}],"backdrop-invert":[{"backdrop-invert":["",ne,H,Y]}],"backdrop-opacity":[{"backdrop-opacity":[ne,H,Y]}],"backdrop-saturate":[{"backdrop-saturate":[ne,H,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,H,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",H,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",H,Y]}],ease:[{ease:["linear","initial",m,H,Y]}],delay:[{delay:[ne,H,Y]}],animate:[{animate:["none",_,H,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,H,Y]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:Ye()}],"rotate-x":[{"rotate-x":Ye()}],"rotate-y":[{"rotate-y":Ye()}],"rotate-z":[{"rotate-z":Ye()}],scale:[{scale:ae()}],"scale-x":[{"scale-x":ae()}],"scale-y":[{"scale-y":ae()}],"scale-z":[{"scale-z":ae()}],"scale-3d":["scale-3d"],skew:[{skew:Pe()}],"skew-x":[{"skew-x":Pe()}],"skew-y":[{"skew-y":Pe()}],transform:[{transform:[H,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"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",H,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":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"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",H,Y]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[ne,ir,Kt,$o]}],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"]}},Zu=Au(Xu);function P(...e){return Zu(Ha(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 Ju=e=>{switch(e){case R.SYNAPSE_COMPONENTS.DOCTOR_CARD:case R.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},Qu=e=>new Promise(t=>setTimeout(t,e)),al=te(({className:e,children:t,...n},r)=>l(Ii,{ref:r,className:P("relative overflow-hidden",e),...n,children:[l(Hd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(ll,{}),l($d,{})]}));al.displayName=Ii.displayName;const ll=te(({className:e,orientation:t="vertical",...n},r)=>l(Ao,{ref:r,orientation:t,className:P("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(Ti,{className:"relative flex-1 rounded-full bg-border"})}));ll.displayName=Ao.displayName;var eh=Symbol.for("react.lazy"),jr=xo[" use ".trim().toString()];function th(e){return typeof e=="object"&&e!==null&&"then"in e}function cl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===eh&&"_payload"in e&&th(e._payload)}function dl(e){const t=rh(e),n=te((r,o)=>{let{children:i,...s}=r;cl(i)&&typeof jr=="function"&&(i=jr(i._payload));const a=ot.toArray(i),c=a.find(sh);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)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var nh=dl("Slot");function rh(e){const t=te((n,r)=>{let{children:o,...i}=n;if(cl(o)&&typeof jr=="function"&&(o=jr(o._payload)),st(o)){const s=ah(o),a=ih(i,o.props);return o.type!==me&&(a.ref=r?ko(r,s):s),Lt(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var oh=Symbol("radix.slottable");function sh(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===oh}function ih(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 ah(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 ul=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,hl=Ha,lh=(e,t)=>n=>{var r;if(t?.variants==null)return hl(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=ul(h)||ul(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,S]=g;return Array.isArray(S)?S.includes({...i,...a}[f]):{...i,...a}[f]===S})?[...d,u,p]:d},[]);return hl(e,s,c,n?.class,n?.className)},ch=lh("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=te(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?nh:"button",{className:P(ch({variant:t,size:n,className:e})),ref:i,...o}));Ee.displayName="Button";const dh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),uh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),ml=e=>{const t=uh(e);return t.charAt(0).toUpperCase()+t.slice(1)},pl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),hh=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var mh={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 ph=te(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>tt("svg",{ref:c,...mh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:pl("lucide",o),...!i&&!hh(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>tt(d,h)),...Array.isArray(i)?i:[i]])),ze=(e,t)=>{const n=te(({className:r,...o},i)=>tt(ph,{ref:i,iconNode:t,className:pl(`lucide-${dh(ml(e))}`,`lucide-${e}`,r),...o}));return n.displayName=ml(e),n},fh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Bo=ze("chevron-down",fh),gh=[["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"}]],_h=ze("ellipsis-vertical",gh),Eh=[["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"}]],fl=ze("file-text",Eh),yh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],gl=ze("info",yh),Sh=[["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"}]],bh=ze("maximize-2",Sh),vh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],wh=ze("menu",vh),Nh=[["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"}]],ar=ze("message-square-plus",Nh),Ch=[["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"}]],Go=ze("mic",Ch),Th=[["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"}]],xh=ze("minimize-2",Th),kh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_l=ze("plus",kh),Oh=[["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"}]],Ah=ze("rotate-ccw",Oh),Rh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],El=ze("square",Rh),Ih=[["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"}]],yl=ze("thumbs-up",Ih),Mh=[["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"}]],Sl=ze("thumbs-down",Mh),Ph=[["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"}]],Dh=ze("triangle-alert",Ph),Lh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],vn=ze("x",Lh),Uh=[["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"}]],Fh=ze("zoom-in",Uh),bl=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},Vh=(e=>e?bl(e):bl),jh=e=>e;function zh(e,t=jh){const n=Ln.useSyncExternalStore(e.subscribe,Ln.useCallback(()=>t(e.getState()),[e,t]),Ln.useCallback(()=>t(e.getInitialState()),[e,t]));return Ln.useDebugValue(n),n}const Yh=e=>{const t=Vh(e),n=r=>zh(t,r);return Object.assign(n,t),n},Hh=(e=>Yh);function $h(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 Wo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Wo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Wo(r)(n)}}}},Bh=(e,t)=>(n,r,o)=>{let i={storage:$h(()=>localStorage),partialize:f=>f,version:0,merge:(f,S)=>({...S,...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,S)=>(u(f,S),h());const p=e((...f)=>(n(...f),h()),r,o);o.getInitialState=()=>p;let E;const g=()=>{var f,S;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:p)});const m=((S=i.onRehydrateStorage)==null?void 0:S.call(i,(f=r())!=null?f:p))||void 0;return Wo(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(O=>[!0,O]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[O,T]=_;if(E=i.merge(T,(y=r())!=null?y:p),n(E,!0),O)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},Gh=Bh,Ne={USER:"user",ASSISTANT:"assistant"};var Se=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Se||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let dt="";const lr=e=>`med-assist-store-${e}`,Wh=e=>{wn(),dt=lr(e)},Kh=200;let gt=null,cr=null;function wn(){if(cr&&(clearTimeout(cr),cr=null),!!gt){try{sessionStorage.setItem(gt.key,JSON.stringify(gt.value))}catch{}gt=null}}typeof window<"u"&&(window.addEventListener("pagehide",wn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&wn()}));const qh={getItem:()=>{if(!dt)return null;if(gt?.key===dt)return gt.value;try{const e=sessionStorage.getItem(dt);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{dt&&(gt&>.key!==dt&&wn(),gt={key:dt,value:t},cr||(cr=setTimeout(wn,Kh)))},removeItem:()=>{gt?.key===dt&&(gt=null),dt&&sessionStorage.removeItem(dt)}},vl={sessionId:"",isStreaming:!1,recordingStatus:Se.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:ge.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},wl={...vl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=Hh()(Gh((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:Se.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(vl),await sessionStorage.removeItem(dt||lr(t().agentId))},clearUser:()=>{e(wl),sessionStorage.removeItem(dt||lr(t().agentId))}}),{name:"med-assist-store",storage:qh,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})})),Xh=e=>{const t=lr(e);wn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(wl),n&&j.setState(n)},Ko=vt(null),Zh=({children:e})=>{const[t,n]=V(null);return l(Ko.Provider,{value:{synapse:t,setSynapse:n},children:e})},Jh=()=>{const e=wt(Ko);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Qh=()=>{const e=wt(Ko);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},em=()=>{const[e,t]=V(R.VOICE_AGENT_STATE.IDLE),[n,r]=V(!1),o=Jh(),i=j(h=>h.setError);$(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},p=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(R.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(R.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(R.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(R.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=ue(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=ue(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),c=ue(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=ue(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:c,toggleMute:d}},Xt=te(({className:e,...t},n)=>l("div",{ref:n,className:P("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));Xt.displayName="Card";const Nl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("flex flex-col space-y-1.5 p-6",e),...t}));Nl.displayName="CardHeader";const Cl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("font-semibold leading-none tracking-tight",e),...t}));Cl.displayName="CardTitle";const tm=te(({className:e,...t},n)=>l("div",{ref:n,className:P("text-sm text-muted-foreground",e),...t}));tm.displayName="CardDescription";const Tl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("p-6 pt-0",e),...t}));Tl.displayName="CardContent";const xl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("flex items-center p-6 pt-0",e),...t}));xl.displayName="CardFooter";const qo=5,kl=3,Ol=10*1024*1024,zr={width:384,height:600},Yr=20,nm=400,rm=320,om=560,sm=150;function im({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=ue(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-zr.width-Yr,y:window.innerHeight-zr.height-Yr},[]),[i,s]=V(()=>e??o()),[a,c]=V(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);$(()=>{t||(u.current=!1)},[t]),pt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),$(()=>{if(!t||typeof window>"u")return;let f=null;const S=()=>{s(_=>{const y=Math.max(0,window.innerWidth-zr.width-Yr),O=Math.max(0,window.innerHeight-zr.height-Yr),T=Math.max(0,Math.min(_.x,y)),v=Math.max(0,Math.min(_.y,O));return T===_.x&&v===_.y?_:{x:T,y:v}})},m=()=>{f!==null&&clearTimeout(f),f=setTimeout(S,sm)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),f!==null&&clearTimeout(f)}},[t]);const p=ue(f=>{if(!t)return;if(!f.target.closest(".synapse-chat-widget-header")){c(!1);return}f.preventDefault(),c(!0);const S=h.current;if(S){const m=S.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=ue(f=>{if(!t||!a)return;const S=f.clientX-d.current.x,m=f.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),O=Math.max(0,Math.min(S,_)),T=Math.max(0,Math.min(m,y));s({x:O,y:T})},[a,t]),g=ue(()=>{!t||!a||(c(!1),r?.())},[a,r]);return $(()=>{if(!t)return;const f=h.current;if(f)return f.addEventListener("mousedown",p),()=>{f.removeEventListener("mousedown",p)}},[t,p]),$(()=>{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 Xo="#6B5CE0",am="#F0F0F0",Hr={background:am,backgroundImage:void 0,primary:Xo,textColor:"black"},lm="rgba(0, 0, 0, 0.4)",cm="24px";function dm(e){if(e==="dark")return"white";if(e==="light")return"black"}function um(e){const t=e?.primary??e?.primaryColor??Hr.primary,n=e?.textColor??dm(e?.mode);return{background:e?.background??Hr.background,backgroundImage:e?.backgroundImage??Hr.backgroundImage,primary:t,primaryColor:t,textColor:n??Hr.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function hm(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 mm(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 pm(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 Zo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return hm(t);if(t.startsWith("rgb"))return mm(t);if(t.startsWith("hsl"))return pm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Al(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Jo(e){return Al(e)>.5?"0 0% 9%":"0 0% 98%"}function fm(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 gm(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 Rl(e,t){const n=t.primary??Xo,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=Zo(n)}catch{c=Zo(Xo)}a("--primary",c),a("--primary-foreground",Jo(c)),a("--ring",c),a("--border-primary",c);const d=gm(c);for(const[E,g]of Object.entries(d))a(`--primary-${E}`,g);const h=Jo(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",Zo(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",fm(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=Al(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",Jo(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",cm),a("--theme-background-overlay",lm),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 Zt({className:e,style:t}){return l("div",{className:P("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 Qo(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Il(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Qo,{}),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(Zt,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Zt,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Zt,{className:"h-9 w-9 rounded-full"}),l(Zt,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function _m(){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(Qo,{}),e.map((t,n)=>l("div",{className:P("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:l(Zt,{className:P("rounded-lg",t.size)})},n))]})}function Em({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(Qo,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Zt,{className:P("h-5 rounded-md",t[r%t.length])}),l(Zt,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function ym(e,t=[]){let n=[];function r(i,s){const a=vt(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,S=le(()=>g,Object.values(g));return l(f.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,p){const E=p?.[e]?.[c]||a,g=wt(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=>vt(s));return function(s){const a=s?.[e]||i;return le(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Sm(o,...t)]}function Sm(...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 le(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var bm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],es=bm.reduce((e,t)=>{const n=dl(`Primitive.${t}`),r=te((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}},{}),Ml={exports:{}},ts={};const vm=Bd(xo);var Pl;function wm(){if(Pl)return ts;Pl=1;var e=vm;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,S=g[1];return i(function(){f.value=E,f.getSnapshot=p,c(f)&&S({inst:f})},[u,E,p]),o(function(){return c(f)&&S({inst:f}),u(function(){c(f)&&S({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 ts.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,ts}var Dl;function Nm(){return Dl||(Dl=1,Ml.exports=wm()),Ml.exports}var Cm=Nm();function Tm(){return Cm.useSyncExternalStore(xm,()=>!0,()=>!1)}function xm(){return()=>{}}var ns="Avatar",[km]=ym(ns),[Om,Ll]=km(ns),Ul=te((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=V("idle");return l(Om,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(es.span,{...r,ref:t})})});Ul.displayName=ns;var Fl="AvatarImage",Vl=te((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Ll(Fl,n),a=Am(r,i),c=Ft(d=>{o(d),s.onImageLoadingStatusChange(d)});return Wt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(es.img,{...i,ref:t,src:r}):null});Vl.displayName=Fl;var jl="AvatarFallback",zl=te((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Ll(jl,n),[s,a]=V(r===void 0);return $(()=>{if(r!==void 0){const c=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(c)}},[r]),s&&i.imageLoadingStatus!=="loaded"?l(es.span,{...o,ref:t}):null});zl.displayName=jl;function Yl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Am(e,{referrerPolicy:t,crossOrigin:n}){const r=Tm(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=V(()=>Yl(i,e));return Wt(()=>{a(Yl(i,e))},[i,e]),Wt(()=>{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 Hl=Ul,$l=Vl,Bl=zl;const rs=te(({className:e,...t},n)=>l(Hl,{ref:n,className:P("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));rs.displayName=Hl.displayName;const Gl=te(({className:e,...t},n)=>l($l,{ref:n,className:P("aspect-square h-full w-full",e),...t}));Gl.displayName=$l.displayName;const os=te(({className:e,...t},n)=>l(Bl,{ref:n,className:P("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));os.displayName=Bl.displayName;const Wl=vt(!1);function Rm({enabled:e,children:t}){return l(Wl.Provider,{value:e,children:t})}function Im(){return wt(Wl)}const Kl="(max-width: 768px), (pointer: coarse)",ql=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Mm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Kl)?.matches??!1,t=ql.test(navigator?.userAgent??"");return e||t}function Xl(){const[e,t]=V(Mm);return $(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Kl),r=ql.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Pm({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=Xl(),p=Im(),E=j(N=>N.displayMode)==="side_panel",g=p&&!u&&!E,f=j(N=>N.displayMode)==="full",S=j(N=>N.initialDisplayMode)==="full",m=!f&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",_=j(N=>N.connectionStatus),y=j(N=>N.level)==="user",[O,T]=V(!1),v=X(null),x=le(()=>a===R.VOICE_AGENT_STATE.CONNECTED||a===R.VOICE_AGENT_STATE.CONNECTING||a===R.VOICE_AGENT_STATE.LISTENING||a===R.VOICE_AGENT_STATE.SPEAKING||a===R.VOICE_AGENT_STATE.THINKING,[a]),b=ue(()=>{O||(T(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,T(!1)},6e3),s())},[O,s]);$(()=>{_===ge.CONNECTED&&(T(!1),v.current&&clearTimeout(v.current))},[_]);const w=(()=>{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(rs,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(os,{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:P("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",w.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:P("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:w.text})})]})]}),l("div",{className:P("flex items-center",!g&&"gap-1"),children:[!x&&!y&&l(Ee,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:b,disabled:O,className:P("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(ar,{className:"w-5 h-5"})}),h&&y&&l(Ee,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:P("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:l(_h,{className:"w-5 h-5"})}),g&&l(Ee,{onClick:d,type:"button",variant:"ghost",size:"icon",title:f?"Exit fullscreen":"Enter fullscreen",className:P("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:f?l(xh,{className:"w-8 h-8"}):l(bh,{className:"w-8 h-8"})}),(t||!S)&&l(Ee,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:P("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:l(vn,{className:"w-8 h-8"})})]})]})})}const ss=te(({className:e,...t},n)=>l("textarea",{className:P("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}));ss.displayName="Textarea";function Zl({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";$(()=>{if(c){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,c]),$(()=>{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(fl,{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(vn,{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(vn,{className:"h-3 w-3"})})]})}function is({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(Zl,{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(Zl,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const as=({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"})}),Jl=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Dm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Ql=({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"})}),Lm=nt(()=>Jl().then(e=>({default:e.ElicitationInput})));function Um({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:S,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:O,isFullScreen:T}){const v=X(null),x=X(null),b=e.trim().length>0||a,w=!g||g.includes(R.SYNAPSE_CONVERSATION.AUDIO),N=!g||g.includes(R.SYNAPSE_CONVERSATION.VOICE),D=b||!w,W=b,G=!g||g.includes(R.SYNAPSE_CONVERSATION.FILE),Ce=(d||p!==Se.IDLE)&&!s,pe=P("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)]":Ce?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),ie=B=>{const Z=Array.from(B.target.files||[]);Z.length>0&&r(Z)},_e=()=>{d||(v.current&&(v.current.value=""),v.current?.click())},F=B=>{B.key==="Enter"&&!B.shiftKey&&W&&!d&&(B.preventDefault(),n())},de=B=>{B.style.height="auto",B.style.overflow="hidden";const Z=B.scrollHeight,L=T?20:28,K=120,re=Math.max(L,Math.min(Z,K));B.style.height=re+"px",Z>K?B.style.overflow="auto":B.style.overflow="hidden"},Oe=B=>{de(B.currentTarget)};return $(()=>{x.current&&de(x.current)},[e]),$(()=>{!d&&!u&&x.current?.focus()},[d]),f&&S?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:S,className:P("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(ar,{className:"w-5 h-5","aria-hidden":!0})]})}):l(me,{children:y?l(Xe,{fallback:l(Il,{}),children:l(Lm,{elicitationEntry:O,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):T?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(is,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:v,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,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(ss,{ref:x,onInput:Oe,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!u,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:F,title:"Enter your message","aria-label":"Enter your message",className:P("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:G&&p===Se.IDLE&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_e,disabled:d,className:P("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(_l,{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:P("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(El,{className:"w-4 h-4"})}):w&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:Ce,className:P("h-10 w-10 shrink-0 p-2",pe),title:"Start recording","aria-label":"Start recording",children:l(Go,{className:"w-6 h-6",strokeWidth:1.5})}),D&&!s?l(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!W,variant:"ghost",className:P("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",W?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:W?"Send message":"Type a message to send","aria-label":W?"Send message":"Type a message to send",children:l(as,{className:"w-4 h-4 text-primary-foreground"})}):w&&N&&!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(Ql,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:v,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(is,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(ss,{ref:x,onInput:Oe,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:F,title:"Enter your message","aria-label":"Enter your message",className:P("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:G&&p===Se.IDLE&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_e,disabled:d,className:P("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(_l,{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:P("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(El,{className:"w-4 h-4"})}):D?l(Ee,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!W,variant:"ghost",className:P("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",W?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:W?"Send message":"Type a message to send","aria-label":W?"Send message":"Type a message to send",children:l(as,{className:"w-4 h-4 text-primary-foreground"})}):w&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:Ce,className:P("h-10 w-10 shrink-0",pe),title:"Start recording","aria-label":"Start recording",children:l(Go,{className:"w-5 h-5",strokeWidth:1.5})}),w&&N&&!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(Ql,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const Fm=Gt(Um),ec=vt(null),tc=ec.Provider;function Vm(){const e=wt(ec);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function jm({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(vn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function zm(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=ue(()=>{t(null)},[t]);return $(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(jm,{message:e,onDismiss:n}):null}function ls({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 Ym="Before we begin",Hm=e=>`A quick note on how ${e} works and handles your information.`,$m=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 Bm(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 nc=(e,t)=>{if(t){const n=Bm(t,e);if(n.length)return n}return $m(e)},Gm="I agree and consent",Wm="By continuing, you consent to the above.",Km="Continue";function rc({botName:e,consentContent:t,isFullScreen:n}){return l(me,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:P("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Ym}),l("p",{className:P("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Hm(e)})]}),l("div",{className:P("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:nc(e,t).map((r,o)=>l("p",{className:P("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function qm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(ls,{isOpen:e,onClose:t,children:l("div",{className:P("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(rc,{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"}),nc(n,o).map((a,c)=>l("p",{className:P("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(Ee,{onClick:t,className:P("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Xm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=V(!1);return e?l(ls,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:P("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(rc,{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:P("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:P("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Gm})]}),l("p",{className:P("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:Wm})]}),l(Ee,{disabled:!i,onClick:()=>i&&r(),className:P("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Km})]})}):null}const Zm=nt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),Jm=nt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),Qm=nt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),ep=nt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),tp=nt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),np=[{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"}],rp=[{Icon:Zm,label:"Bad",score:1},{Icon:Jm,label:"Poor",score:2},{Icon:Qm,label:"Okay",score:3},{Icon:ep,label:"Good",score:4},{Icon:tp,label:"Great!",score:5}];function op(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function sp({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?op(a,t):t.form?.default?.length?t.form.default:np,g=_=>{h(y=>{const O=new Set(y);return O.has(_)?O.delete(_):O.add(_),O})},f=_=>{c(_),h(new Set)},S=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(ls,{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:rp.map(({Icon:_,label:y,score:O})=>{const T=a===O,v=a!==null&&!T;return l("button",{onClick:()=>f(O),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 ${T?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${v?"opacity-50":""}`,style:T?{filter:"brightness(1.25)"}:void 0,children:l(Xe,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(_,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${T?"text-primary/50 font-medium":v?"text-primary/50":"text-primary"}`,children:y})]},O)})}),(!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:!S,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 oc({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:S,feedbackModal:m,consentModal:_}){const{onClose:y,showCloseButton:O=!0,title:T,titleImg:v,tagline:x,iconUrl:b,onStartNewSession:w,showStartNewChatButton:N,onToggleDisplayMode:D,onOpenSessionDrawer:W}=Vm(),[G,Ce]=V(!1),[pe,ie]=V(!1),[_e,F]=V(!1),de=X(null),Oe=j(z=>z.level),B=c,Z=B==="full",L=B==="side_panel",K=X(null),[re,xe]=V("");$(()=>{K.current!==null&&K.current!==B&&xe(B==="full"?"Switched to fullscreen mode":B==="side_panel"?"Switched to side panel mode":B==="widget"?"Switched to widget mode":"Switched to mobile layout"),K.current=B},[B]);const J=le(()=>um(S),[S]),Ae=j(z=>z.setIsMobile),Ye=!!E,ae=ue(async z=>{if(!(!s?.onSend||pe)){ie(!0);try{await s.onSend(z)}finally{ie(!1)}}},[s?.onSend,pe]);pt(()=>{if(!de.current)return;const z=B==="full"?{...J,headerTinted:!1}:J;Rl(de.current,z),B==="full"&&!J.backgroundImage?(de.current.style.setProperty("--background","0 0% 100%"),de.current.style.setProperty("--widget-bg-overlay","transparent")):(de.current.style.removeProperty("--background"),de.current.style.removeProperty("--widget-bg-overlay"),Rl(de.current,J))},[J,B]),$(()=>{const z=()=>{const Re=window?.innerWidth??0,be=navigator?.userAgent?.toLowerCase()??"",Le=Re<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(be);Ce(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),pt(()=>{if(!e||!G||!de.current)return;const z=de.current;let Re=null,be=null,Le=null,We=window.visualViewport?.offsetTop??0,Ue=0;const _t=2,ht=80;if(window.visualViewport){const Ve=()=>{if(z&&window.visualViewport){const Be=window.visualViewport.height,Ie=window.visualViewport.offsetTop;Re=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ie}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Be}px`,z.style.maxHeight=`${Be}px`,z.style.minHeight=`${Be}px`,be&&clearTimeout(be),be=setTimeout(()=>{z.style.transition=""},100)})}},rt=()=>{Ve()},$e=()=>{if(!z||!window.visualViewport)return;const Be=window.visualViewport.offsetTop,Ie=Date.now();Math.abs(Be-We)<_t||Ie-Ue<ht||(Ue=Ie,We=Be,Re=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Be}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",rt),window.visualViewport.addEventListener("scroll",$e),Ve(),()=>{Re&&cancelAnimationFrame(Re),be&&clearTimeout(be),Le&&clearTimeout(Le),window.visualViewport?.removeEventListener("resize",rt),window.visualViewport?.removeEventListener("scroll",$e),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const Ve=()=>{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",Ve),Ve(),()=>{window.removeEventListener("resize",Ve),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),$(()=>{if(e&&!(L&&d==="push")){const z=de.current,Re=window.scrollY,be=document.body.style.cssText,Le=document.documentElement.style.overflow,We=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Re}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",We>0&&!G&&(document.body.style.paddingRight=`${We}px`);let Ue=0;const _t=Ve=>{Ue=Ve.touches[0].clientY},ht=Ve=>{if(Ve.touches.length!==1)return;const rt=Ue-Ve.touches[0].clientY;Ue=Ve.touches[0].clientY;let $e=Ve.target;for(;$e&&$e!==z;){const{overflowY:Be}=window.getComputedStyle($e);if((Be==="auto"||Be==="scroll")&&$e.scrollHeight>$e.clientHeight){const{scrollTop:Ie,scrollHeight:Ht,clientHeight:Et}=$e,Cn=Ie<=0&&rt<0,tn=Ie+Et>=Ht-1&&rt>0;if(!Cn&&!tn)return;break}$e=$e.parentElement}Ve.preventDefault()};return z&&(z.addEventListener("touchstart",_t,{passive:!0}),z.addEventListener("touchmove",ht,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",_t),z.removeEventListener("touchmove",ht)),document.body.style.cssText=be,document.documentElement.style.overflow=Le,window.scrollTo(0,Re)}}},[e,G,L,d]),$(()=>{if(!(!L||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,L,d,h,u,p]);const{position:Pe,elementRef:De}=im({enabled:e&&!G&&!Z&&!L});$(()=>{de.current&&(De.current=de.current)},[De]);const Tt=P("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!Z&&!L?"transition-all duration-300":"",G?"w-screen h-[100svh]":Z?"w-screen h-screen":L?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Yt=P("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",J.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":Z?"rounded-none border-0 flex-row":L?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return l("div",{ref:de,"data-mode":B,className:Tt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...Z&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...Z&&!e&&{display:"none"},...L&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...L&&!e&&{display:"none"},...!G&&!Z&&!L&&{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:J.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 Pc=Object.defineProperty;var Dc=(e,t,n)=>t in e?Pc(e,t,{enumerable:!0,config
|
|
|
35
35
|
.synapse-chat-widget-container [data-radix-scroll-area-viewport] {
|
|
36
36
|
overscroll-behavior: contain;
|
|
37
37
|
}
|
|
38
|
-
`}),l(qt,{className:it,"data-text-color":ne.textColor,style:oe?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:Ne}),!ne.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),ne.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${ne.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),ne.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:ne.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(Im,{isOpen:U,onClose:()=>Te(!1),botName:h,explicitDisclaimer:A?.explicitDisclaimer,consentContent:A?.consentContent,isFullScreen:D}),J?.isOpen&&l(Mm,{isOpen:!0,botName:h,consentContent:A?.consentContent,onAccept:J.onAccept,isFullScreen:D}),$?.isOpen&&l(Ym,{isOpen:$.isOpen,config:$.config,onSubmit:$.onSubmit,onSkip:$.onSkip,onClose:$.onClose,onDontShowAgain:$.onDontShowAgain}),D&&a,V==="user"&&!D&&c,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:{...D?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!oe&&!D&&!B&&{cursor:e?"grab":"default"}},children:l(ym,{onClose:t,showCloseButton:n,title:h,titleImg:u,tagline:f,iconUrl:r,startNewConversation:o,voiceAgentState:R,headerTinted:D?!1:ne.headerTinted,onToggleDisplayMode:T,onOpenSessionDrawer:D?void 0:x,historyEnabled:N})}),(()=>{const L=D&&!!d,Oe=p&&R===I.VOICE_AGENT_STATE.IDLE?l(He,{fallback:l(Nl,{}),children:l(bm,{value:p.value,onChange:p.onChange,onSend:Ge?We:p.onSend,onFileChange:p.onFileChange,onRemoveFile:p.onRemoveFile,onRecording:p.onRecording,isRecording:p.isRecording,hasAttachment:p.hasAttachment,attachmentFiles:p.attachmentFiles,isDisabled:p.isDisabled||Ge&&ie,isMobile:oe,placeholder:p.placeholder,recordingStatus:p.recordingStatus,theme:ne,onStartNewChat:o,showStartNewChatButton:i,isVoiceAgentActive:p.isVoiceAgentActive,handleVoiceMode:p.handleVoiceMode,allowed:p.allowed,isAuthComponent:v,activeElicitationState:b,isFullScreen:D&&!L})}):null,le={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Re=l(ue,{children:[E&&g==="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: ",E]})}),D?l("div",{onClick:()=>Te(!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:le,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):A?.explicitDisclaimer?l("div",{onClick:()=>Te(!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:[A?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>Te(!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:[A?.hideWatermark!==!0&&l(ue,{children:[l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Eka Care"})]}),l(ul,{className:"w-3 h-3"})]})]}),Ze=d&&D?d({composer:L?Oe:null,composerFooter:L?Re:null}):null;return l(ue,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Ze??s,l(Nm,{})]}),p&&!L&&l("div",{className:M("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:M(D&&"max-w-2xl mx-auto w-full"),children:Oe}),Re]})]})})()]})]})]})}function $m(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Hm(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 Bm({sessions:e,activeSessionId:t,onSelectSession:n,onNewChat:r,isCollapsed:o,onToggle:i,isLoading:s=!1}){return l("div",{id:"synapse-session-sidebar","data-collapsed":o,className:M("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",o?"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:M("flex items-center w-full",o?"justify-center":"justify-between"),children:[!o&&l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{type:"button",onClick:i,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:o?"Expand chats":"Collapse chats","aria-label":o?"Expand chats":"Collapse chats","aria-expanded":!o,"aria-controls":"synapse-session-list",children:l(dh,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:o?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:o?l("button",{type:"button",onClick:r,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(tr,{className:"w-6 h-6"})}):l("button",{type:"button",onClick:r,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(tr,{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"})]})}),!o&&l("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:s&&e.length===0?l(rm,{}):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"})}):e.map(a=>{const c=a.session_id===t,d=new Date(a.c_at),h=Hm(d),u=$m(d);return l("button",{type:"button",onClick:()=>n(a.session_id),"aria-current":c?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:c?{backgroundImage:"linear-gradient(hsl(var(--primary) / 0.1), hsl(var(--primary) / 0.1))"}:void 0,children:[l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:a.title||`Chat at ${u}`}),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:a.title?`${h}, ${u}`:h}),c&&l(Gm,{})]})]},a.session_id)})})]})}function Gm(){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 Wm(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(r.getTime()-864e5),i=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return i.getTime()===r.getTime()?`Today, ${s}`:i.getTime()===o.getTime()?`Yesterday, ${s}`:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}, ${s}`}function Km({isOpen:e,onClose:t,sessions:n,activeSessionId:r,onSelectSession:o,onNewChat:i}){return l(ue,{children:[l("div",{className:M("absolute inset-0 z-[60] transition-opacity duration-200",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:t}),l("div",{className:M("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",e?"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:t,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:l(_n,{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:()=>{i(),t()},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(tr,{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:n.length===0?l("div",{className:"flex items-center justify-center h-full px-4",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):n.map(s=>{const a=s.session_id===r,c=!!s.title,d=`Chat on ${Wm(s.c_at)}`;return l("button",{onClick:()=>{o(s.session_id),t()},className:"flex flex-col gap-2 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:a?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:c?l(ue,{children:[l("div",{className:"flex flex-col gap-0.5 w-full",children:l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:s.title})}),l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:d}),a&&l(ql,{})]})]}):l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-sm font-medium leading-5 truncate text-foreground",children:d}),a&&l(ql,{})]})},s.session_id)})})]})]})}function ql(){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 qm(){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 Xm=180;function Jm({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<=Xm&&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:qm()}),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:M("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 ht={AUTH_FAILED:"auth_failed",SESSION_FAILED:"session_failed",CONNECTION_FAILED:"connection_failed",CONNECTION_ESTABLISHED:"connection_established",READY:"ready",TYPING_STARTED:"typing_started",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"};function Xl(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function Jl(){const[e,t]=F(typeof navigator<"u"?navigator.onLine:!0);return Y(()=>{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 Zl=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Zm=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Qm=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}},ep=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},Ql=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},tp=({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?op(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:Ql(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,...Zl(a),slots:a.slots??d.slots}}}return s},np=(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,...Zl(o),availability:tp({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},ec=e=>!!e&&Array.isArray(e.doctors),rp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!ec(e)||!ec(t))return e;const r=e.format||t.format;return{...t,doctors:np(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},op=(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},tc=(e,t)=>`${e}::${t}`,sp=e=>e<1e12?e*1e3:e,ip=(e,t)=>`${e}::${t}::answer`,ap=e=>!!e?.tool_id&&!!e?.component;function lp(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(ap),i=r.timestamp?Kt(sp(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Pe.USER?Pe.USER:Pe.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>tc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[tc(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:ip(r.id,s.tool_id),content:s.answer,role:Pe.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const nc="initial-bot-message",Jt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},cp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=F([]),d=q([]),[h,u]=F(!1),[f,E]=F(!1),p=q(new Map),g=q(0),[S,m]=F(!1),_=q([]),y=q(null),k=q({}),T=q(null),x=Fh(),N=q(null),{isOnline:v}=Jl(),b=q(!1),R=W(C=>C.agentId),A=W(C=>C.sessionId),$=W(C=>C.isStreaming),J=W(C=>C.isWaitingForResponse),oe=W(C=>C.initialMessage),_e=W(C=>C.userId),ie=W(C=>C.fileUploadPerSession),{setSessionId:he,setRefreshToken:U,setSessToken:Te,setLevel:de,setError:V,setConnectionStatus:H,setShowRetryButton:D,setStartNewConnection:B,setIsStreaming:Ee,setIsWaitingForResponse:Ne,setProgressMessage:se,setRecordingStatus:ne,clearSession:$e,clearUser:Ge,addMessageToSession:We,getMessagesForSession:Je,setMessagesForSession:Ot,updateMessageInSession:mt,setUserId:it,setFileUploadPerSession:L,setToastMessage:Oe,upsertElicitationState:le,setElicitationState:Re,setInitialMessage:Ze,setSessionInitialMessage:rt}=W.getState();Y(()=>{if(!v)V({title:"No internet connection",description:"Please check your internet connection."}),H(ge.NOT_CONNECTED);else if(!S)H(ge.CONNECTING);else if(De())H(ge.CONNECTED),Ie();else{const{showRetryButton:C,startNewConnection:w,error:P}=W.getState();(C||w||P)&&!De()&&Ie(),T.current!==null&&!w&&!yn()&&xe(W.getState().sessionId||void 0)}},[v,S]),Y(()=>{A&&(c(C=>{const w=new Set(C.map(P=>P.id));return[...C,...(Je(A)||[]).filter(P=>!w.has(P.id))]}),_.current=[])},[A]),Y(()=>{if(m(!1),!R)return;const C=new I.SynapseSDK({agentId:R,...o&&{authToken:o},...W.getState().refreshToken&&{refreshToken:W.getState().refreshToken},...W.getState().sessToken&&{sessToken:W.getState().sessToken},...W.getState().level&&{level:W.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:_e,callbacks:{onError:w=>{if(ir(w),typeof navigator<"u"&&!navigator.onLine){H(ge.NOT_CONNECTED),V({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(w.reason)switch(w.reason){case I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{W.getState().level!=="user"?(Ge(),y.current?.clearTokens(),bn()):lr();return}case I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:lr();return;case I.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:V(null),H(ge.NOT_CONNECTED),B(!0);return;case I.SYNAPSE_RECOVERY_REASON.RETRY_LATER:H(ge.CONNECTING);return}switch(w.code){case I.SynapseErrorCode.API:case I.SynapseErrorCode.SESSION:{const P=w;P.status===404||P?.context?.status===404?B(!0):(H(ge.NOT_CONNECTED),V({title:"Something went wrong!",description:Jt(w)}),D(!0));break}case I.SynapseErrorCode.RECORDING:V({title:"Recording failed",description:Jt(w)});break;case I.SynapseErrorCode.CONNECTION:De()||(H(ge.NOT_CONNECTED),g.current<2?(g.current=g.current+1,xe(W.getState().sessionId||void 0)):(D(!0),V({title:"Trying to connect...",description:Jt(w)})));break;default:V({title:"Something went wrong",description:Jt(w)}),D(!0);break}},onTokenExchange:w=>{const P=W.getState().userId;(w?.user_id&&P&&w.user_id!==P||w?.userid_change_detected)&&$e(),w?.refresh_token&&U(w.refresh_token),w?.sess_token&&Te(w.sess_token),w?.level&&de(w.level),w?.user_id&&it(w.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=C,x(C),m(!0),()=>{m(!1),Ue(),y.current=null,x(null),N.current&&(clearTimeout(N.current),N.current=null)}},[R,e,o]),Y(()=>{d.current=a},[a]),Y(()=>{const C=d.current[d.current.length-1];!C?.role||!A||(C?.role===Pe.USER&&!C.isStored?We(A,{...C,isStored:!0}):!$&&!C.isStored&&(c(w=>{const P=[...w];return P[P.length-1]={...C,isStored:!0},P}),We(A,{...C,isStored:!0})))},[a,$]),Y(()=>()=>{const C=d.current[d.current.length-1];C&&!C?.isStored&&A&&We(A,{...C,isStored:!0})},[]),Y(()=>(N.current&&(clearTimeout(N.current),N.current=null),J&&!$?N.current=setTimeout(()=>{Ne(!1),N.current=null},3e4):$&&N.current&&(clearTimeout(N.current),N.current=null),()=>{N.current&&(clearTimeout(N.current),N.current=null)}),[J,$,Ne]);const xe=async C=>{T.current=performance.now();try{const w=await y.current?.startSession(C?{session_id:C}:void 0);if(w?.session_id&&he(w.session_id),w?.user_id&&it(w.user_id),w?.initial_message){Ze(w.initial_message);const P=w.session_id||C;P&&rt(P,w.initial_message)}w?.error?.msg&&Oe(w.error.msg)}catch(w){if(w?.reason)return;const P=w;P.status===404||P.context?.status==404?(V(null),H(ge.NOT_CONNECTED),B(!0)):(V({title:"Connection Lost!",description:Jt(w)}),D(!0))}},at=async C=>{const w=W.getState().chats[C];if(w?.length)return c(w),w;const P=p.current.get(C);if(P)return P;const G=(async()=>{try{const X=await y.current?.getSessionMessages(C);if(!X?.length)return[];const{messages:Z,elicitations:pe}=lp(X);return Object.keys(pe).length&&Re({...W.getState().elicitationState,...pe}),Ot(C,Z),c(Z),Z}catch{return[]}finally{p.current.delete(C)}})();p.current.set(C,G),E(!0);try{return await G}finally{E(!1)}},Ae=async({forceNewSession:C=!1,sessionId:w}={})=>{try{if(!y.current){V({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),C){H(ge.CONNECTING),c([]),await $e(),await y?.current?.endSession(),Ie(),await xe(),At();return}const P=W.getState()?.sessionId,G=w||P||void 0;G!==P&&(Ue(),c([]),G&&await at(G)),await xe(G),At()}catch{}finally{u(!1)}},De=()=>y.current?.isConnected()??!1,Ue=()=>{y.current?.endSession()},Ie=()=>{g.current=0,D(!1),B(!1),V(null)},lt=()=>{St(ht.READY)},en=()=>{let C;try{C=y.current?.getSessionConfig()?.session_id}catch{C=void 0}return C||W.getState().sessionId||void 0},yn=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},St=(C,w={})=>{const P=en();!P||k.current[C]===P||(k.current[C]=P,Xl(C,{sessionId:P,...w}))},ct=(C,w={})=>{const P=en();Xl(C,{...P&&{sessionId:P},...w})},ir=C=>{if(De())return;const w=C?.code,P=[I.SynapseErrorCode.RECORDING,I.SynapseErrorCode.FILE,I.SynapseErrorCode.MESSAGE,I.SynapseErrorCode.VALIDATION,I.SynapseErrorCode.CONFIGURATION,I.SynapseErrorCode.STORE];if(w&&P.includes(w))return;const G=typeof C?.status=="number"?C.status:void 0,X=C?.error,Z=typeof X?.code=="string"?X.code:typeof X?.type=="string"?X.type:void 0,pe={...G!==void 0&&{status:G}};if(C?.reason===I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||C?.reason===I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||w===I.SynapseErrorCode.AUTH||G===401||G===403){ct(ht.AUTH_FAILED,{reason:C?.reason??Z??w??"auth_error",...pe});return}const ve=w===I.SynapseErrorCode.API&&G===void 0;if(w===I.SynapseErrorCode.CONNECTION||G===0||ve){ct(ht.CONNECTION_FAILED,{reason:C?.reason??Z??(ve?"timeout":w)??"connection_error",...pe});return}ct(ht.SESSION_FAILED,{reason:C?.reason??Z??w??"session_error",...pe})},zr=C=>{switch(C){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:ct(ht.SESSION_FAILED,{reason:C});return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:ct(ht.CONNECTION_FAILED,{reason:C});return}},Yr=()=>{ct(ht.CONNECTION_ESTABLISHED,{...T.current!==null&&{elapsedMs:Math.max(0,Math.round(performance.now()-T.current))}})},$r=()=>{St(ht.TYPING_STARTED)},Sn=()=>{d.current.some(C=>C.role===Pe.USER)||St(ht.FIRST_MESSAGE_SENT)},vn=C=>{d.current.some(w=>w.role===Pe.ASSISTANT&&w.id!==nc)||St(ht.FIRST_BOT_REPLY,{messageId:C})},At=()=>{y.current?.on(I.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,C=>{const w=C;if(w.data?.text&&w.messageId){$||(Ne(!1),Ee(!0)),De()&&H(ge.CONNECTED),Ie();const P=w.data.text,G=w.messageId,X=b.current;b.current=!1;const Z=d.current[d.current.length-1];!(Z&&Z.id===G&&Z.role===Pe.ASSISTANT)&&vn(G),c(pe=>{const ve=pe[pe.length-1];if(ve&&ve.id===G&&ve.role===Pe.ASSISTANT){const Ke=[...pe],It=X&&ve.content.length>0&&!/\s$/.test(ve.content)&&!/^\s/.test(P)?`
|
|
38
|
+
`}),l(Xt,{className:Yt,"data-text-color":J.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}),!J.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),J.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${J.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),J.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:J.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(qm,{isOpen:_e,onClose:()=>F(!1),botName:T,explicitDisclaimer:S?.explicitDisclaimer,consentContent:S?.consentContent,isFullScreen:Z}),_?.isOpen&&l(Xm,{isOpen:!0,botName:T,consentContent:S?.consentContent,onAccept:_.onAccept,isFullScreen:Z}),m?.isOpen&&l(sp,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),Z&&n,Oe==="user"&&!Z&&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:{...Z?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!Z&&!L&&{cursor:e?"grab":"default"}},children:l(Pm,{onClose:y,showCloseButton:O,title:T,titleImg:v,tagline:x,iconUrl:b,startNewConversation:w,voiceAgentState:f,headerTinted:Z?!1:J.headerTinted,onToggleDisplayMode:D,onOpenSessionDrawer:Z?void 0:W})}),(()=>{const z=Z&&!!o,Re=s&&f===R.VOICE_AGENT_STATE.IDLE?l(Xe,{fallback:l(Il,{}),children:l(Fm,{value:s.value,onChange:s.onChange,onSend:Ye?ae:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||Ye&&pe,isMobile:G,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:J,onStartNewChat:w,showStartNewChatButton:N,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:E,activeElicitationState:g,isFullScreen:Z&&!z})}):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]})}),Z?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"})]})}):S?.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:[S?.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:[S?.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(gl,{className:"w-3 h-3"})]})]}),We=o&&Z?o({composer:z?Re: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:[We??t,l(zm,{})]}),s&&!z&&l("div",{className:P("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:P(Z&&"max-w-2xl mx-auto w-full"),children:Re}),Le]})]})})()]})]})]})}function ip(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function ap(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 lp(e){const t=new Date(e.c_at),n=ap(t),r=ip(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function cp(){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 dp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=lp(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(cp,{})]})]})}function sc({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?l(Em,{}):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(dp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function ic(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:P("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:P("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(vn,{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(ar,{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(sc,{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:P("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:P("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(wh,{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(ar,{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(ar,{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(sc,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function up(){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 hp=180;function mp({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<=hp&&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:up()}),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:P("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 ut={AUTH_FAILED:"auth_failed",SESSION_FAILED:"session_failed",CONNECTION_FAILED:"connection_failed",CONNECTION_ESTABLISHED:"connection_established",READY:"ready",TYPING_STARTED:"typing_started",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply",NEW_CHAT_STARTED:"new_chat_started"};function ac(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function lc(){const[e,t]=V(typeof navigator<"u"?navigator.onLine:!0);return $(()=>{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 cc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),pp=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",fp=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}},gp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},dc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},_p=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===R.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),c=n||a,d=n&&r?Sp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:dc(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,...cc(a),slots:a.slots??d.slots}}}return s},Ep=(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,...cc(o),availability:_p({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},uc=e=>!!e&&Array.isArray(e.doctors),yp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==R.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!uc(e)||!uc(t))return e;const r=e.format||t.format;return{...t,doctors:Ep(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Sp=(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},hc=(e,t)=>`${e}::${t}`,bp=e=>e<1e12?e*1e3:e,vp=(e,t)=>`${e}::${t}::answer`,wp=e=>!!e?.tool_id&&!!e?.component;function Np(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(wp),i=r.timestamp?qt(bp(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=>hc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[hc(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:vp(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Cp=Math.round(Ol/(1024*1024)),mc=(e,t=0)=>e.length+t>kl?{title:`You can only upload up to ${kl} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Ol?{title:`Total file size limit of ${Cp} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,pc="initial-bot-message",Jt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Tp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=V([]),d=X([]),[h,u]=V(!1),[p,E]=V(!1),g=X(new Map),f=X(0),[S,m]=V(!1),_=X([]),y=X(null),O=X({}),T=X({}),v=X(null),x=Qh(),b=X(null),{isOnline:w}=lc(),N=X(!1),D=X([]),W=j(C=>C.agentId),G=j(C=>C.sessionId),Ce=j(C=>C.isStreaming),pe=j(C=>C.isWaitingForResponse),ie=j(C=>C.initialMessage),_e=j(C=>C.userId),F=j(C=>C.fileUploadPerSession),{setSessionId:de,setRefreshToken:Oe,setSessToken:B,setLevel:Z,setError:L,setConnectionStatus:K,setShowRetryButton:re,setStartNewConnection:xe,setIsStreaming:J,setIsWaitingForResponse:Ae,setProgressMessage:Ye,setRecordingStatus:ae,clearSession:Pe,clearUser:De,addMessageToSession:Tt,getMessagesForSession:Yt,setMessagesForSession:z,updateMessageInSession:Re,setUserId:be,setFileUploadPerSession:Le,setToastMessage:We,upsertElicitationState:Ue,setElicitationState:_t,setInitialMessage:ht,setSessionInitialMessage:Ve}=j.getState();$(()=>{if(!w)L({title:"No internet connection",description:"Please check your internet connection."}),K(ge.NOT_CONNECTED);else if(!S)K(ge.CONNECTING);else if(Ie())K(ge.CONNECTED),Et();else{const{showRetryButton:C,startNewConnection:k,error:M}=j.getState();(C||k||M)&&!Ie()&&Et(),v.current!==null&&!k&&!mr()&&rt(j.getState().sessionId||void 0)}},[w,S]),$(()=>{G&&(c(C=>{const k=new Set(C.map(I=>I.id)),M=[...C];for(const I of Yt(G)||[])k.has(I.id)||(k.add(I.id),M.push(I));return M}),_.current=[])},[G]),$(()=>{if(m(!1),!W)return;const C=new R.SynapseSDK({agentId:W,...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:k=>{if(Zr(k),typeof navigator<"u"&&!navigator.onLine){K(ge.NOT_CONNECTED),L({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(k.reason)switch(k.reason){case R.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),on()):xn();return}case R.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:xn();return;case R.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:L(null),K(ge.NOT_CONNECTED),xe(!0);return;case R.SYNAPSE_RECOVERY_REASON.RETRY_LATER:K(ge.CONNECTING);return}switch(k.code){case R.SynapseErrorCode.API:case R.SynapseErrorCode.SESSION:{const M=k;M.status===404||M?.context?.status===404?xe(!0):(K(ge.NOT_CONNECTED),L({title:"Something went wrong!",description:Jt(k)}),re(!0));break}case R.SynapseErrorCode.RECORDING:L({title:"Recording failed",description:Jt(k)});break;case R.SynapseErrorCode.CONNECTION:Ie()||(K(ge.NOT_CONNECTED),f.current<2?(f.current=f.current+1,rt(j.getState().sessionId||void 0)):(re(!0),L({title:"Trying to connect...",description:Jt(k)})));break;default:L({title:"Something went wrong",description:Jt(k)}),re(!0);break}},onTokenExchange:k=>{const M=j.getState().userId;(k?.user_id&&M&&k.user_id!==M||k?.userid_change_detected)&&Pe(),k?.refresh_token&&Oe(k.refresh_token),k?.sess_token&&B(k.sess_token),k?.level&&Z(k.level),k?.user_id&&be(k.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=C,x(C),m(!0),()=>{m(!1),Ht(),y.current=null,x(null),b.current&&(clearTimeout(b.current),b.current=null)}},[W,e,o]),$(()=>{d.current=a},[a]),$(()=>{const C=d.current[d.current.length-1];!C?.role||!G||(C?.role===Ne.USER&&!C.isStored?(c(k=>{const M=[...k];return M[M.length-1]={...C,isStored:!0},M}),Tt(G,{...C,isStored:!0})):!Ce&&!C.isStored&&(c(k=>{const M=[...k];return M[M.length-1]={...C,isStored:!0},M}),Tt(G,{...C,isStored:!0})))},[a,Ce]),$(()=>()=>{const C=d.current[d.current.length-1],k=j.getState().sessionId;C&&!C?.isStored&&k&&((j.getState().chats[k]||[]).some(M=>M.id===C.id)||Tt(k,{...C,isStored:!0}))},[]),$(()=>(b.current&&(clearTimeout(b.current),b.current=null),pe&&!Ce?b.current=setTimeout(()=>{Ae(!1),b.current=null},3e4):Ce&&b.current&&(clearTimeout(b.current),b.current=null),()=>{b.current&&(clearTimeout(b.current),b.current=null)}),[pe,Ce,Ae]);const rt=async C=>{v.current=performance.now();try{const k=await y.current?.startSession(C?{session_id:C}:void 0);if(k?.session_id&&(k.session_id in T.current||(T.current[k.session_id]=k.session_id===C),de(k.session_id)),k?.user_id&&be(k.user_id),k?.initial_message){ht(k.initial_message);const M=k.session_id||C;M&&Ve(M,k.initial_message)}k?.error?.msg&&We(k.error.msg)}catch(k){if(k?.reason)return;const M=k;M.status===404||M.context?.status==404?(L(null),K(ge.NOT_CONNECTED),xe(!0)):(L({title:"Connection Lost!",description:Jt(k)}),re(!0))}},$e=async C=>{const k=j.getState().chats[C];if(k?.length)return c(k),k;const M=g.current.get(C);if(M)return M;const I=(async()=>{try{const q=await y.current?.getSessionMessages(C);if(!q?.length)return[];const{messages:oe,elicitations:ce}=Np(q);return Object.keys(ce).length&&_t({...j.getState().elicitationState,...ce}),z(C,oe),c(oe),oe}catch{return[]}finally{g.current.delete(C)}})();g.current.set(C,I),E(!0);try{return await I}finally{E(!1)}},Be=async({forceNewSession:C=!1,sessionId:k}={})=>{try{if(!y.current){L({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),C){K(ge.CONNECTING),c([]),await Pe(),await y?.current?.endSession(),Et(),await rt(),Er();return}const M=j.getState()?.sessionId,I=k||M||void 0;I!==M&&(Ht(),c([]),I&&await $e(I)),await rt(I),Er()}catch{}finally{u(!1)}},Ie=()=>y.current?.isConnected()??!1,Ht=()=>{y.current?.endSession()},Et=()=>{f.current=0;const{showRetryButton:C,startNewConnection:k,error:M}=j.getState();C&&re(!1),k&&xe(!1),M&&L(null)},Cn=()=>{nn(ut.READY)},tn=()=>{let C;try{C=y.current?.getSessionConfig()?.session_id}catch{C=void 0}return C||j.getState().sessionId||void 0},mr=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},nn=(C,k={})=>{const M=tn();!M||O.current[C]===M||(O.current[C]=M,ac(C,{sessionId:M,resumed:T.current[M]??!1,...k}))},yt=(C,k={})=>{const M=tn();ac(C,{...M&&{sessionId:M},...k})},Zr=C=>{if(Ie())return;const k=C?.code,M=[R.SynapseErrorCode.RECORDING,R.SynapseErrorCode.FILE,R.SynapseErrorCode.MESSAGE,R.SynapseErrorCode.VALIDATION,R.SynapseErrorCode.CONFIGURATION,R.SynapseErrorCode.STORE];if(k&&M.includes(k))return;const I=typeof C?.status=="number"?C.status:void 0,q=C?.error,oe=typeof q?.code=="string"?q.code:typeof q?.type=="string"?q.type:void 0,ce={...I!==void 0&&{status:I}};if(C?.reason===R.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||C?.reason===R.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||k===R.SynapseErrorCode.AUTH||I===401||I===403){yt(ut.AUTH_FAILED,{reason:C?.reason??oe??k??"auth_error",...ce});return}const he=k===R.SynapseErrorCode.API&&I===void 0;if(k===R.SynapseErrorCode.CONNECTION||I===0||he){yt(ut.CONNECTION_FAILED,{reason:C?.reason??oe??(he?"timeout":k)??"connection_error",...ce});return}yt(ut.SESSION_FAILED,{reason:C?.reason??oe??k??"session_error",...ce})},pr=C=>{switch(C){case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:yt(ut.SESSION_FAILED,{reason:C});return;case R.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:yt(ut.CONNECTION_FAILED,{reason:C});return}},fr=()=>{yt(ut.CONNECTION_ESTABLISHED,{...v.current!==null&&{elapsedMs:Math.max(0,Math.round(performance.now()-v.current))}})},rn=()=>{nn(ut.TYPING_STARTED)},gr=()=>{nn(ut.FIRST_MESSAGE_SENT)},_r=C=>{C!==pc&&nn(ut.FIRST_BOT_REPLY,{messageId:C})},Er=()=>{const C=y.current;if(!C)return;for(const[M,I]of D.current)C.off(M,I);D.current=[];const k=(M,I)=>{C.on(M,I),D.current.push([M,I])};k(R.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,M=>{const I=M;if(I.data?.text&&I.messageId){const q=j.getState();q.isStreaming||(Ae(!1),J(!0),Et()),q.connectionStatus!==ge.CONNECTED&&Ie()&&K(ge.CONNECTED);const oe=I.data.text,ce=I.messageId,he=N.current;N.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&_r(ce),c(Ke=>{const je=Ke[Ke.length-1];if(je&&je.id===ce&&je.role===Ne.ASSISTANT){const ve=[...Ke],Je=he&&je.content.length>0&&!/\s$/.test(je.content)&&!/^\s/.test(oe)?`
|
|
39
39
|
|
|
40
|
-
`:"";return Ke[Ke.length-1]={...ve,content:ve.content+It+P},Ke}else return[...pe,{id:G,content:P,role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}]})}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{b.current=!1,Ee(!1),se(null),Ne(!1)}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{Ie(),H(ge.CONNECTED),Yr(),lt()}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,C=>{b.current=!0;const w=C;if(!w?.messageId||!w?.data||!w?.data?.details?.component||!w?.data?.tool_id)return;J&&Ne(!1);const{messageId:P,data:G}=w,X=G.tool_id,Z=`${P}::${X}`,pe=W.getState().elicitationState[Z],ve=G.details?.component,Ke=w?.data?.details?._meta?.tool_result,It=G.details?.input,$t=rp(pe?.input,It,ve);let Ye=w.data.details?._meta?.disp_toast_msg;const Qe=G?.details?._meta?.schema?.required||[];switch(G?.details?.status){case I.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Ve=w?.data?.details?.input||{},je=Qe.reduce((gt,vt)=>(Ve[vt]!==void 0&&(gt[vt]=Ve[vt]),gt),{}),ee={...pe?.server_input||{},...je},Mt=Qe.filter(gt=>!ee[gt]),Pt=w.data.details?._meta?.mcp_meta_fields||[];le(Z,{tool_id:X,active:!0,disabled:!1,input:$t,server_input:ee,messageId:P,required:Qe,component:ve,pattern:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.pattern,minLength:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.minLength,maxLength:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.maxLength,type:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.type,disp_toast_msg:w.data.details?._meta?.disp_toast_msg,description:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.description,tool_result:Ke,orientation:w.data.details?._meta?.orientation,...Pt.length&&{mcp_meta_fields:Pt},...Mt?{toolSelectionNames:Mt}:{},...pe?.hide_show_more!==void 0?{hide_show_more:pe.hide_show_more}:{}});break}case I.SYNAPSE_EICITATION_STATUS.SUCCESS:{le(Z,{...pe||{},tool_id:X,disabled:!0,active:Vu(ve),messageId:P,component:ve,input:$t,tool_result:Ke,send_to_llm:!0});break}case I.SYNAPSE_EICITATION_STATUS.FAILURE:{le(Z,{...pe||{},tool_id:X,active:!1,messageId:P,response_value:{label:G?.details?._meta?.disp_message||"Tool call failed"},tool_result:Ke,disabled:!0});break}default:le(Z,{tool_id:X,disabled:!1,active:!1,messageId:P,tool_result:Ke,input:$t,component:ve})}Ye&&Oe(Ye);const pt=w?.data?.details?._meta?.user_hint;c(Ve=>{let je=Ve[Ve.length-1]?.id===P?Ve.length-1:Ve.findIndex?.(ee=>ee.id===P);if(je==-1){const ee={id:P,content:w.data?.details?.input?.text||"",role:Pe.ASSISTANT,tool_keys:[Z],isResponseFromTool:!0,isStored:!1,...pt?{userHint:pt}:{}};return[...Ve,ee]}else{const ee={...Ve[je],isResponseFromTool:!0,tool_keys:[...new Set([...Ve[je].tool_keys||[],Z])],...pt?{userHint:pt}:{}};Ve[je]=ee,mt(A,P,ee)}return[...Ve]});const Ht=w?.data?.details?._meta?.disp_message,ft=W.getState().elicitationState;if((!ft[Z]?.active||ft[Z]?.send_to_llm)&&(Ht||Object.keys(Ke||{}).length))try{Yt({message:Ht||"",tool_result:Ke,toolCalled:!0,tool_key:Z})}catch{}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,C=>{if(C?.reason===I.DisconnectionReason.CLIENT_CLOSED)return;const w=C;ct(ht.CONNECTION_FAILED,{reason:w?.reason??"unknown",...typeof w?.code=="number"&&{closeCode:w.code}}),T.current=performance.now();const P=typeof navigator<"u"&&!navigator.onLine;if(H(ge.NOT_CONNECTED),P){V({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),D(!1);return}g.current<2?(g.current=g.current+1,D(!0),V({title:"Something went wrong!",description:"Please try again."})):(V({title:"Something went wrong!",description:"Please start a new Chat."}),B(!0))}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.ERROR,C=>{const w=C?.data?.code;switch(zr(w),w){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:B(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:V({title:"Session not found",description:"Please start a new chat from onError callback"}),B(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:bn();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(g.current<1){g.current++,cr();return}V({title:"Error parsing request",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:V({title:"Request timed out",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;default:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async C=>{const w=C;w?.data?.text&&(c(P=>[...P,{id:Date.now().toString(),content:w.data.text||"",role:Pe.USER,timestamp:Kt(Date.now()),isStored:!0}]),ne(Se.IDLE)),Ee(!1),Ne(!1),se(null)}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,C=>{b.current=!0;const w=C;w.data?.text&&(Ne(!1),se(w.data.text))}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_START,C=>{b.current=!0;const w=C;if(w.data?.name&&w.messageId){const P=w.messageId;c(G=>{const X=G[G.length-1];if(X&&X.id===P&&X.role===Pe.ASSISTANT){const Z=[...G];return Z[Z.length-1]={...X,toolCallStatus:`Calling tool: ${w.data.name}...`},A&&mt(A,P,{toolCallStatus:`Calling tool: ${w.data.name}...`}),Z}return G})}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_END,C=>{b.current=!0;const w=C;if(w.data?.name&&w.messageId){const P=w.messageId;c(G=>{const X=G[G.length-1];if(X&&X.id===P&&X.role===Pe.ASSISTANT){const Z=[...G];return Z[Z.length-1]={...X,toolCallStatus:"Tool call completed."},A&&mt(A,P,{toolCallStatus:"Tool call completed."}),Z}return G})}})},Yt=async({message:C,files:w,audio:P,toolCalled:G,selectedComponent:X,resend:Z,tool_declined:pe,tool_result:ve,tool_key:Ke})=>{const It=W.getState().elicitationState,$t=Object.values(It).some(Ye=>Ye.active);if(!(!G&&(!w||w.length===0)&&!C?.trim()&&!P?.audio&&!X&&!$t&&!ve&&!Object.keys(ve||{}).length)){if(w&&w.length>3){V({title:"Maximum 3 files are allowed to be sent at a time",description:"Please try again"});return}if(w&&w.length>0&&w.reduce((Ye,Qe)=>Ye+Qe.size,0)>10*1024*1024){V({title:"Total file size limit of 10MB exceeded",description:"Please reduce the size of the files or try again with less files"});return}if(w&&w.length>0&&w.length+ie>Ho){const Ye=Ho-ie;V({title:`You can only upload up to ${Ho} files per session`,description:`${Ye<=0?"Maximum file upload limit reached":`You have ${Ye} file${Ye===1?"":"s"} upload${Ye===1?"":"s"} left`}`});return}else w&&w.length&&L(ie+w.length);V(null),D(!1),De()&&H(ge.CONNECTED);try{const Ye=a.length<=2&&_.current.length==1?_.current:null;let Qe=null,pt=null;const Ht=a.length-1,ft=Ht>=0?a[Ht]:null,Ve=W.getState().elicitationState,je=Ke||null,ee=je?Ve[je]:void 0,Mt=ee?.component===I.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===I.SYNAPSE_COMPONENTS.CARD?!!ee&&!ve&&!!ee.active:!!ee?.active,Pt=!!(w||[]).length||!!P?.audio||!!pe||!Mt||!G,gt=X?X.label:void 0,vt=ee?.component===I.SYNAPSE_COMPONENTS.PILL&&typeof gt=="string"?gt:null;if(!Pt&&Mt&&je&&ee?.messageId){const ae=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(ke=>!ee.server_input?.[ke])??[],Le=ae.reduce((ke,be)=>{if(X){const Nn=X[be];Nn!==void 0&&(ke[be]=Nn)}else ae.length===1&&(ke[be]=C);return ke},{}),bt=ee.mcp_meta_fields?.reduce((ke,be)=>(ae.includes(be)?ke[be]=Le[be]:ee.server_input?.[be]&&(ke[be]=ee.server_input[be]),Z&&!ke.is_resend&&(ke.is_resend=Z),ke),{}),Wr=Object.keys(ee.server_input||{})?.reduce((ke,be)=>{const Nn=!Object.keys(bt||{})?.includes(be),gs=!!ee.server_input?.[be];return(Z?Nn&&gs:Nn&&ee.required?.includes(be)&&gs)&&(ke[be]=ee.server_input?.[be]),ke},{}),Kr=Z?{}:(ee.required||ae).reduce((ke,be)=>(Object.keys(bt||{}).includes(be)||(Le[be]!==void 0?ke[be]=Le[be]:X&&X[be]!==void 0&&(ke[be]=X[be])),ke),{}),wn={...Wr||{},...Kr,...Object.keys(bt||{}).length&&{mcp_meta_fields:bt}};if(!Object.keys(wn).length)return;await le(je,{...ee,server_input:{...ee.server_input||{},...wn}});try{await ar(ee.tool_id,ee.messageId,wn),Qe=!0}catch(ke){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Jt(ke)}`}}),pt="Tool call failed",le(je,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Jt(ke)}`}})}}else{const ae=ft?.id,Le=ae?Object.entries(It).filter(([Wr,Kr])=>{const[wn]=Wr.split("::");return wn===ae&&Kr.active}):[],bt=ve??ee?.tool_result;await y.current?.sendMessage({message:C??"",files:w,audio:P,...Ye&&{initial_prompts:Ye},...pe||Le.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...bt&&{tool_result:bt}})}(C||w&&w.length>0||P?.audio||vt||pt)&&(Qe||Sn(),c(ae=>{if(Qe)return ae;const Le=ae.length===0&&oe?.text?[{id:nc,content:oe.text,role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}]:[];return[...ae,...Le,{id:Date.now().toString(),content:vt||pt||C||"",files:w||[],audio:P,role:Pe.USER,timestamp:Kt(Date.now()),isStored:!1}]}),Qe||Ne(!0),Qe=null);const re=W.getState().elicitationState,Ce=new Set;je&&Ce.add(je),ft?.tool_keys?.forEach(ae=>Ce.add(ae)),Ce.forEach(ae=>{const Le=re[ae];Le&&le(ae,{...Le,...Pt&&{active:!1,disabled:!0},...ae===je?{response_value:{...Le?.response_value||{},label:vt||C||""}}:{}})})}catch{}}},Hr=C=>C.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(C.type)?(V({title:`File type not supported: ${C.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):C.size>3*1024*1024?(V({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,Br=async()=>{try{await y.current?.startRecording({onChunks:async C=>{ne(Se.PROCESSING),await Yt({audio:C}),ne(Se.TRANSCRIBING)},onError(C){ne(Se.IDLE)}}),ne(Se.LISTENING)}catch(C){throw ne(Se.IDLE),C}},Gr=()=>{y.current?.endRecording()},ar=async(C,w,P)=>{try{if(!De())throw new Error("Not connected to the server");await y.current?.callTool(C,w,P)}catch(G){throw G}},bn=async()=>{Ie(),await $e(),await Ae({forceNewSession:!0})},lr=()=>{Ge(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),H(ge.NOT_CONNECTED),V({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},cr=async()=>{if(De()){H(ge.CONNECTED);const C=d.current[d.current.length-1];if(C&&C.role===Pe.USER)try{y.current?.sendMessage({message:C.content,files:C.files||[],messageId:C.id,audio:C.audio})}catch{}}else if(H(ge.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:C}=W.getState();await xe(C)}else g.current===2?(g.current++,D(!0),V({title:"Trying to connect..."})):(V({title:"Something went wrong!",description:"Please start a new chat."}),B(!0))};return{sendMessage:Yt,startSession:Ae,incomingMessages:a,loading:h,isLoadingSessionMessages:f,endSession:Ue,isReady:S,startRecording:Br,stopRecording:Gr,getPastSessions:async()=>{try{const C=await y.current?.getPastSessions();return!C||!C?.data?.length?[]:C.data}catch{return[]}},handleRetry:cr,isValidFile:Hr,handleStartNewConnection:bn,callTool:ar,handleInitialTaskClick:async C=>{const{message:w}=C;if(!oe?.suggestions?.length||!w)return;const P=oe.suggestions.find(X=>X.value===w);if(_.current=[{role:"assistant",text:`${oe.text} ${P?.response||""}`}],!P||!P.response){await Yt(C);return}Sn(),c(X=>[...X,{id:Date.now().toString(),content:w,role:Pe.USER,timestamp:Kt(Date.now()),isStored:!1}]),Ne(!0),await ju(1e3),Ne(!1);const G=Date.now().toString();vn(G),c(X=>[...X,{id:G,content:P.response||"Please try again",role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}])},sendMessageFeedback:async(C,w,P)=>{if(De())try{await y.current?.sendMessageFeedback(w,C,P)}catch{}},sendSessionFeedback:async(C,w)=>{if(!(!De()||!C?.length&&!w))try{await y.current?.sendSessionFeedback(C,w)}catch{}},clearElicitationState:async(C,w)=>{const P=W.getState().elicitationState,G=C?P[C]:void 0;try{await Yt({message:w||"User aborted elicitation",tool_declined:!0,tool_result:G?.tool_result,tool_key:C})}catch{}finally{C&&G&&le(C,{...G,active:!1,disabled:!0})}},notifyTypingStarted:$r}};function dp(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 up=32,hp=100,mp=320;function pp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function fp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=q(null),i=q(null),[s,a]=F(!1),c=q(null),d=q(!1),h=q("auto"),u=q(!0),f=fe(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=fe(S=>pp()?"auto":S,[]),p=fe(S=>{const m=f();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(S)}),a(!1))},[f,E]),g=fe(S=>{d.current=!0,h.current=S,c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null,d.current&&(d.current=!1,p(h.current))}))},[p]);return Y(()=>()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),d.current=!1},[]),Y(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),Y(()=>{if(!e||!u.current)return;const S=setTimeout(()=>g("auto"),mp);return()=>clearTimeout(S)},[r,e,g]),Y(()=>{let S=!1,m=null,_=null,y=0;const k=()=>{if(S)return;const T=f(),x=i.current?.parentElement;if(!T||!x){requestAnimationFrame(k);return}const N=()=>{const{scrollTop:R,scrollHeight:A,clientHeight:$}=T;return A-R-$<=up};u.current=!0;let v=0;const b=()=>{if(v>0){v--;return}u.current=N()};T.addEventListener("scroll",b,{passive:!0}),_=()=>T.removeEventListener("scroll",b),m=new ResizeObserver(()=>{if(!u.current)return;const R=Date.now();R-y<hp||(y=R,v++,g("auto"))}),m.observe(x)};return k(),()=>{S=!0,m?.disconnect(),_?.()}},[f,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:p,scheduleScrollToBottom:g}}const os="eka-medassist-agent-config",rc="feedback_hidden",ss="upfront_consent_accepted";function is(e,t){try{const n=localStorage.getItem(os);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function oc(e,t){try{const n=localStorage.getItem(os),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(os,JSON.stringify(r))}catch{}}function gp({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=Uh(),d=()=>{r===I.VOICE_AGENT_STATE.IDLE&&i()},h=r!==I.VOICE_AGENT_STATE.IDLE,[u,f]=F(""),[E,p]=F(!1),g=W(re=>re.setDisplayMode),[S,m]=F(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),_=()=>m(re=>re==="full"?"widget":"full"),y=Yl()?"mobile":S,k=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),T=Math.min(Math.max(n.sidePanelWidth??zh,Yh),$h),x=n.sidePanelMode??"push",[N,v]=F([]),b=q(!1),[R,A]=F(!1),[$,J]=F(!1),[oe,_e]=F(()=>!!n.theme?.upfrontConsent&&!is(t,ss)),ie=q(null),{setAgentId:he,startNewConnection:U,showRetryButton:Te,clearError:de,error:V,connectionStatus:H,recordingStatus:D,isWaitingForResponse:B,isStreaming:Ee,setError:Ne,sessionId:se,setContext:ne,initialMessage:$e,setInitialMessage:Ge,sessionInitialMessages:We,setInitialDisplayMode:Je,clearSession:Ot}=W(),mt=W(re=>re.elicitationState),it=W(re=>re.level),{incomingMessages:L,loading:Oe,isLoadingSessionMessages:le,sendMessage:Re,handleInitialTaskClick:Ze,notifyTypingStarted:rt,startSession:xe,isReady:at,startRecording:Ae,stopRecording:De,handleRetry:Ue,isValidFile:Ie,sendMessageFeedback:lt,clearElicitationState:en,sendSessionFeedback:yn,getPastSessions:St}=cp({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:dp(n.displayMode)}),[ct,ir]=F(!1),[zr,Yr]=F([]),[$r,Sn]=F(!0),vn=q(St);Y(()=>{vn.current=St});const At=fe(async()=>{Sn(!0);try{const re=await vn.current();Yr(re)}catch{}finally{Sn(!1)}},[]),Yt=fe(async()=>{ir(!0),await At()},[At]),Hr=fe(()=>{ir(!1)},[]),[Br,Gr]=F(!1),ar=fe(()=>Gr(re=>!re),[]);Y(()=>{y!=="full"||it!=="user"||At()},[y,it,se,At]),Y(()=>{t&&(ie.current!==t&&(Mh(t),Ph(t),he(t),n.force&&Ot(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(g(n.displayMode),Je(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&ne(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&Ge(n.initialMessage),ie.current=t),e&&at&&!b.current&&(b.current=!0,xe({forceNewSession:!1})))},[e,at,t]),Y(()=>{Sm([Hl])},[]),Y(()=>()=>{s()},[]),Y(()=>{!n.theme?.upfrontConsent||!t||is(t,ss)||_e(!0)},[n.theme?.upfrontConsent,t]);const bn=fe(()=>{oc(t,ss),_e(!1)},[t]),lr=()=>{n.feedback&&!is(t,rc)?J(!0):n.onClose()},cr=async(re,Ce)=>{await yn(re,Ce),J(!1),n.onClose()},C=()=>{J(!1),n.onClose()},w=()=>{oc(t,rc),J(!1),n.onClose()},P=()=>{J(!1)},G=L.length>0,X=L.length===1,Z=ye(()=>{const re=L[L.length-1],Ce=re?.tool_keys?.[re.tool_keys.length-1];if(!Ce)return null;const ae=mt[Ce];return ae?.active?{...ae,tool_key:Ce}:null},[L,mt]),pe=ye(()=>(se?We[se]:void 0)??$e??n?.initialMessage??null,[se,We,$e,n?.initialMessage]),ve=ye(()=>!!pe?.text||!!pe?.suggestions?.length,[pe]),Ke=ye(()=>ve&&L?.length===0&&!le,[L,ve,le]),It=ye(()=>Z?Z.component===I.SYNAPSE_COMPONENTS.MOBILE||Z.component===I.SYNAPSE_COMPONENTS.OTP||Z.component===I.SYNAPSE_COMPONENTS.EMAIL:!1,[Z]),{scrollAreaRef:$t,messagesEndRef:Ye,showScrollButton:Qe,scrollToBottom:pt}=fp({messageCount:L.length,isStreaming:Ee,isFirstMessage:X,resolvedMode:y}),Ht=H===ge.CONNECTED,ft=B||Ee,Ve=ye(()=>D===Se.IDLE?null:D===Se.LISTENING?"Listening...":D===Se.PROCESSING?"Processing...":D===Se.TRANSCRIBING?"Transcribing...":null,[D]),je=Ve&&D!==Se.IDLE?Ve:B||Ee?"Please wait for the response...":"Type a reply\u2026",ee=async(re,Ce)=>{if(ft)return;const ae=Ce?Ze:Re,Le=re?.message??u;N.length>0?(await ae({files:N,message:Le.trim()}),v([]),A(!1)):Le.trim()?await ae({...re,message:Le.trim()}):re?.resend?await ae(re):re&&await ae(re),f(""),p(!1),A(!1)},Mt=re=>{if(re&&re.length>0){const Ce=re.filter(ae=>!!Ie(ae));if(Ce?.length+N.length>3){Ne({title:"You can only upload up to 3 files at a time",description:"Please remove some files and try again."});return}if(Ce?.length>0&&Ce.reduce((ae,Le)=>ae+Le.size,0)>10*1024*1024){Ne({title:`Total file size limit of ${jh} MB exceeded`,description:"Please reduce the size of the files or try again with less files"});return}if(Ce?.length>0)re=Ce;else return}v(Ce=>(A((Ce?.length??0)+(re?.length??0)>0),[...Ce,...re]))},Pt=re=>{v(Ce=>{const ae=Ce.filter((Le,bt)=>bt!==re);return A(ae.length>0),ae})},gt=async()=>{if(E)await De(),p(!1);else{if(ft)return;try{await Ae(),p(!0)}catch{}}},vt={value:u,onChange:re=>{re.trim()&&rt(),f(re)},onSend:ee,onFileChange:Mt,onRemoveFile:Pt,onRecording:gt,isRecording:E,hasAttachment:R,attachmentFiles:N,isDisabled:ft,placeholder:je,recordingStatus:D,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d};return{inputValue:u,setInputValue:f,isRecording:E,hasAttachment:R,attachmentFiles:N,showScrollButton:Qe,displayMode:S,setDisplayMode:m,toggleDisplayMode:_,resolvedMode:y,currentDisplayMode:S,setCurrentDisplayMode:m,sidePanelMode:x,sidePanelWidth:T,side:k,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:$t,messagesEndRef:Ye,startNewConnection:U,showRetryButton:Te,clearError:de,error:V,connectionStatus:H,isStreaming:Ee,sessionId:se,activeElicitation:Z,inConversation:G,isFirstMessage:X,isEmptyChat:Ke,isAuthComponent:It,isConnected:Ht,isComposerDisabled:ft,loading:Oe,isLoadingSessionMessages:le,initialMessage:pe,incomingMessages:L,sendMessage:Re,startSession:xe,sendMessageFeedback:lt,clearElicitationState:en,handleRetry:Ue,handleSendMessage:ee,handleFileChange:Mt,handleRemoveFile:Pt,handleRecording:gt,scrollToBottom:pt,handleClose:lr,showFeedbackModal:$,handleSessionFeedbackSubmit:cr,handleSessionFeedbackSkip:C,handleDontShowAgain:w,handleCloseModal:P,showConsentModal:oe,handleConsentAccept:bn,chatComposerProps:vt,isSessionDrawerOpen:ct,pastSessions:zr,isLoadingPastSessions:$r,openSessionDrawer:Yt,closeSessionDrawer:Hr,refreshPastSessions:At,userLevel:it,isSidebarCollapsed:Br,toggleSidebar:ar,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,connectVoiceAgent:i,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c,handleVoiceAgentClick:d}}function Zt(){return Zt=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},Zt.apply(this,arguments)}const _p=["children","options"],sc=["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"}),ic={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Ep=["style","script","pre"],yp=["src","href","data","formAction","srcDoc","action"],Sp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,vp=/\n{2,}$/,ac=/^(\s*>[\s\S]*?)(?=\n\n|$)/,bp=/^ *> ?/gm,wp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Np=/^ {2,}\n/,xp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,lc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,cc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Cp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,Tp=/^(?:\n *)*\n/,kp=/\r\n?/g,Rp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Op=/^\[\^([^\]]+)]/,Ap=/\f/g,Ip=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,Mp=/^\s*?\[(x|\s)\]/,dc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,uc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,hc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,as=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Pp=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,mc=/^<!--[\s\S]*?(?:-->)/,Dp=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,ls=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Lp=/^\{.*\}$/,Fp=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,Up=/^<([^ >]+[:@\/][^ >]+)>/,Vp=/-([a-z])?/gi,pc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,jp=/^[^\n]+(?: \n|\n{2,})/,zp=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,Yp=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,$p=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Hp=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Bp=/\t/g,Gp=/(^ *\||\| *$)/g,Wp=/^ *:-+: *$/,Kp=/^ *:-+ *$/,qp=/^ *-+: *$/,Pr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Dr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Xp=RegExp(`^([*_])\\1${Pr(1)}${Dr}\\1\\1(?!\\1)`),Jp=RegExp(`^([*_])${Pr(0)}${Dr}\\1(?!\\1)`),Zp=RegExp(`^(==)${Pr(0)}${Dr}\\1`),Qp=RegExp(`^(~~)${Pr(0)}${Dr}\\1`),ef=/^(:[a-zA-Z0-9-_]+:)/,tf=/^\\([^0-9A-Za-z\s])/,nf=/\\([^0-9A-Za-z\s])/g,rf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,of=/^\n+/,sf=/^([ \t]*)/,af=/(?:^|\n)( *)$/,cs="(?:\\d+\\.)",ds="(?:[*+-])";function fc(e){return"( *)("+(e===1?cs:ds)+") +"}const gc=fc(1),_c=fc(2);function Ec(e){return RegExp("^"+(e===1?gc:_c))}const lf=Ec(1),cf=Ec(2);function yc(e){return RegExp("^"+(e===1?gc:_c)+"[^\\n]*(?:\\n(?!\\1"+(e===1?cs:ds)+" )[^\\n]*)*(\\n|$)","gm")}const df=yc(1),uf=yc(2);function Sc(e){const t=e===1?cs:ds;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const vc=Sc(1),bc=Sc(2);function wc(e,t){const n=t===1,r=n?vc:bc,o=n?df:uf,i=n?lf:cf;return{t:s=>i.test(s),o:En(function(s,a){const c=af.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(vp,`
|
|
41
|
-
`).match(o);let u=!1;return{items:h.map(function(
|
|
40
|
+
`:"";return ve[ve.length-1]={...je,content:je.content+Je+oe},ve}else return[...Ke,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:qt(Date.now()),isStored:!1}]})}}),k(R.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{N.current=!1,J(!1),Ye(null),Ae(!1)}),k(R.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{Et(),K(ge.CONNECTED),fr(),Cn()}),k(R.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,M=>{N.current=!0;const I=M;if(!I?.messageId||!I?.data||!I?.data?.details?.component||!I?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:q,data:oe}=I,ce=oe.tool_id,he=`${q}::${ce}`,Me=j.getState().elicitationState[he],Ke=oe.details?.component,je=I?.data?.details?._meta?.tool_result,ve=oe.details?.input,Je=yp(Me?.input,ve,Ke);let xt=I.data.details?._meta?.disp_toast_msg;const mt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case R.SYNAPSE_EICITATION_STATUS.PROGRESS:{const ee=I?.data?.details?.input||{},at=mt.reduce((Pt,U)=>(ee[U]!==void 0&&(Pt[U]=ee[U]),Pt),{}),qe={...Me?.server_input||{},...at},St=mt.filter(Pt=>!qe[Pt]),Mt=I.data.details?._meta?.mcp_meta_fields||[];Ue(he,{tool_id:ce,active:!0,disabled:!1,input:Je,server_input:qe,messageId:q,required:mt,component:Ke,pattern:I.data.details?._meta?.schema?.properties?.[I.data.details?.component]?.pattern,minLength:I.data.details?._meta?.schema?.properties?.[I.data.details?.component]?.minLength,maxLength:I.data.details?._meta?.schema?.properties?.[I.data.details?.component]?.maxLength,type:I.data.details?._meta?.schema?.properties?.[I.data.details?.component]?.type,disp_toast_msg:I.data.details?._meta?.disp_toast_msg,description:I.data.details?._meta?.schema?.properties?.[I.data.details?.component]?.description,tool_result:je,orientation:I.data.details?._meta?.orientation,...Mt.length&&{mcp_meta_fields:Mt},...St?{toolSelectionNames:St}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case R.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(he,{...Me||{},tool_id:ce,disabled:!0,active:Ju(Ke),messageId:q,component:Ke,input:Je,tool_result:je,send_to_llm:!0});break}case R.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(he,{...Me||{},tool_id:ce,active:!1,messageId:q,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:je,disabled:!0});break}default:Ue(he,{tool_id:ce,disabled:!1,active:!1,messageId:q,tool_result:je,input:Je,component:Ke})}xt&&We(xt);const kt=I?.data?.details?._meta?.user_hint;c(ee=>{let at=ee[ee.length-1]?.id===q?ee.length-1:ee.findIndex?.(qe=>qe.id===q);if(at==-1){const qe={id:q,content:I.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[he],isResponseFromTool:!0,isStored:!1,...kt?{userHint:kt}:{}};return[...ee,qe]}else{const qe={...ee[at],isResponseFromTool:!0,tool_keys:[...new Set([...ee[at].tool_keys||[],he])],...kt?{userHint:kt}:{}};ee[at]=qe;const St=j.getState().sessionId;St&&Re(St,q,qe)}return[...ee]});const sn=I?.data?.details?._meta?.disp_message,Qe=j.getState().elicitationState;if((!Qe[he]?.active||Qe[he]?.send_to_llm)&&(sn||Object.keys(je||{}).length))try{$t({message:sn||"",tool_result:je,toolCalled:!0,tool_key:he})}catch{}}),k(R.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,M=>{if(M?.reason===R.DisconnectionReason.CLIENT_CLOSED)return;const I=M;yt(ut.CONNECTION_FAILED,{reason:I?.reason??"unknown",...typeof I?.code=="number"&&{closeCode:I.code}}),v.current=performance.now();const q=typeof navigator<"u"&&!navigator.onLine;if(K(ge.NOT_CONNECTED),q){L({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),L({title:"Something went wrong!",description:"Please try again."})):(L({title:"Something went wrong!",description:"Please start a new Chat."}),xe(!0))}),k(R.SYNAPSE_REALTIME_EVENTS.ERROR,M=>{const I=M?.data?.code;switch(pr(I),I){case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:xe(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:L({title:"Session not found",description:"Please start a new chat from onError callback"}),xe(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:on();return;case R.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case R.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case R.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(f.current<1){f.current++,br();return}L({title:"Error parsing request",description:"please try again"}),re(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:L({title:"Request timed out",description:"please try again"}),re(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:L({title:"Something went wrong",description:"please try again"}),re(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:L({title:"Something went wrong",description:"please try again"}),re(!0),ae(Se.IDLE);return;case R.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:L({title:"Something went wrong",description:"please try again"}),re(!0),ae(Se.IDLE);return;default:L({title:"Something went wrong",description:"please try again"}),re(!0),ae(Se.IDLE);return}}),k(R.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async M=>{const I=M;I?.data?.text&&(c(q=>[...q,{id:Date.now().toString(),content:I.data.text||"",role:Ne.USER,timestamp:qt(Date.now()),isStored:!0}]),ae(Se.IDLE)),J(!1),Ae(!1),Ye(null)}),k(R.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,M=>{N.current=!0;const I=M;I.data?.text&&(Ae(!1),Ye(I.data.text))}),k(R.SYNAPSE_REALTIME_EVENTS.TOOL_START,M=>{N.current=!0;const I=M;if(I.data?.name&&I.messageId){const q=I.messageId;c(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const he=[...oe];he[he.length-1]={...ce,toolCallStatus:`Calling tool: ${I.data.name}...`};const Me=j.getState().sessionId;return Me&&Re(Me,q,{toolCallStatus:`Calling tool: ${I.data.name}...`}),he}return oe})}}),k(R.SYNAPSE_REALTIME_EVENTS.TOOL_END,M=>{N.current=!0;const I=M;if(I.data?.name&&I.messageId){const q=I.messageId;c(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const he=[...oe];he[he.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Re(Me,q,{toolCallStatus:"Tool call completed."}),he}return oe})}})},$t=async({message:C,files:k,audio:M,toolCalled:I,selectedComponent:q,resend:oe,tool_declined:ce,tool_result:he,tool_key:Me})=>{const Ke=j.getState().elicitationState,je=Object.values(Ke).some(ve=>ve.active);if(!(!I&&(!k||k.length===0)&&!C?.trim()&&!M?.audio&&!q&&!je&&!he&&!Object.keys(he||{}).length)){if(k&&k.length>0){const ve=mc(k);if(ve){L(ve);return}}if(k&&k.length>0&&k.length+F>qo){const ve=qo-F;L({title:`You can only upload up to ${qo} files per session`,description:`${ve<=0?"Maximum file upload limit reached":`You have ${ve} file${ve===1?"":"s"} upload${ve===1?"":"s"} left`}`});return}else k&&k.length&&Le(F+k.length);L(null),re(!1),Ie()&&K(ge.CONNECTED);try{const ve=a.length<=2&&_.current.length==1?_.current:null;let Je=null,xt=null;const mt=a.length-1,kt=mt>=0?a[mt]:null,sn=j.getState().elicitationState,Qe=Me||null,ee=Qe?sn[Qe]:void 0,at=ee?.component===R.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===R.SYNAPSE_COMPONENTS.CARD?!!ee&&!he&&!!ee.active:!!ee?.active,qe=!!(k||[]).length||!!M?.audio||!!ce||!at||!I,St=q?q.label:void 0,Mt=ee?.component===R.SYNAPSE_COMPONENTS.PILL&&typeof St=="string"?St:null;if(!qe&&at&&Qe&&ee?.messageId){const se=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(ke=>!ee.server_input?.[ke])??[],ye=se.reduce((ke,we)=>{if(q){const An=q[we];An!==void 0&&(ke[we]=An)}else se.length===1&&(ke[we]=C);return ke},{}),et=ee.mcp_meta_fields?.reduce((ke,we)=>(se.includes(we)?ke[we]=ye[we]:ee.server_input?.[we]&&(ke[we]=ee.server_input[we]),oe&&!ke.is_resend&&(ke.is_resend=oe),ke),{}),kn=Object.keys(ee.server_input||{})?.reduce((ke,we)=>{const An=!Object.keys(et||{})?.includes(we),bs=!!ee.server_input?.[we];return(oe?An&&bs:An&&ee.required?.includes(we)&&bs)&&(ke[we]=ee.server_input?.[we]),ke},{}),eo=oe?{}:(ee.required||se).reduce((ke,we)=>(Object.keys(et||{}).includes(we)||(ye[we]!==void 0?ke[we]=ye[we]:q&&q[we]!==void 0&&(ke[we]=q[we])),ke),{}),On={...kn||{},...eo,...Object.keys(et||{}).length&&{mcp_meta_fields:et}};if(!Object.keys(On).length)return;await Ue(Qe,{...ee,server_input:{...ee.server_input||{},...On}});try{await Tn(ee.tool_id,ee.messageId,On),Je=!0}catch(ke){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Jt(ke)}`}}),xt="Tool call failed",Ue(Qe,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Jt(ke)}`}})}}else{const se=kt?.id,ye=se?Object.entries(Ke).filter(([kn,eo])=>{const[On]=kn.split("::");return On===se&&eo.active}):[],et=he??ee?.tool_result;await y.current?.sendMessage({message:C??"",files:k,audio:M,...ve&&{initial_prompts:ve},...ce||ye.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...et&&{tool_result:et}})}(C||k&&k.length>0||M?.audio||Mt||xt)&&(Je||gr(),c(se=>{if(Je)return se;const ye=se.length===0&&ie?.text?[{id:pc,content:ie.text,role:Ne.ASSISTANT,timestamp:qt(Date.now()),isStored:!1}]:[];return[...se,...ye,{id:Date.now().toString(),content:Mt||xt||C||"",files:k||[],audio:M,role:Ne.USER,timestamp:qt(Date.now()),isStored:!1}]}),Je||Ae(!0),Je=null);const Pt=j.getState().elicitationState,U=new Set;Qe&&U.add(Qe),kt?.tool_keys?.forEach(se=>U.add(se)),U.forEach(se=>{const ye=Pt[se];ye&&Ue(se,{...ye,...qe&&{active:!1,disabled:!0},...se===Qe?{response_value:{...ye?.response_value||{},label:Mt||C||""}}:{}})})}catch{}}},Jr=C=>C.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(C.type)?(L({title:`File type not supported: ${C.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):C.size>3*1024*1024?(L({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,yr=async()=>{try{await y.current?.startRecording({onChunks:async C=>{ae(Se.PROCESSING),await $t({audio:C}),ae(Se.TRANSCRIBING)},onError(C){ae(Se.IDLE)}}),ae(Se.LISTENING)}catch(C){throw ae(Se.IDLE),C}},Qr=()=>{y.current?.endRecording()},Tn=async(C,k,M)=>{try{if(!Ie())throw new Error("Not connected to the server");await y.current?.callTool(C,k,M)}catch(I){throw I}},on=async()=>{Et(),await Pe(),await Be({forceNewSession:!0})},Sr=async()=>{await Be({forceNewSession:!0}),yt(ut.NEW_CHAT_STARTED)},xn=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),K(ge.NOT_CONNECTED),L({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},br=async()=>{if(Ie()){K(ge.CONNECTED);const C=d.current[d.current.length-1];if(C&&C.role===Ne.USER)try{y.current?.sendMessage({message:C.content,files:C.files||[],messageId:C.id,audio:C.audio})}catch{}}else if(K(ge.NOT_CONNECTED),f.current<2){f.current++;const{sessionId:C}=j.getState();await rt(C)}else f.current===2?(f.current++,re(!0),L({title:"Trying to connect..."})):(L({title:"Something went wrong!",description:"Please start a new chat."}),xe(!0))};return{sendMessage:$t,startSession:Be,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Ht,isReady:S,startRecording:yr,stopRecording:Qr,getPastSessions:async()=>{try{const C=await y.current?.getPastSessions();return!C||!C?.data?.length?[]:C.data}catch{return[]}},handleRetry:br,isValidFile:Jr,handleStartNewConnection:on,startNewChat:Sr,callTool:Tn,handleInitialTaskClick:async C=>{const{message:k}=C;if(!ie?.suggestions?.length||!k)return;const M=ie.suggestions.find(q=>q.value===k);if(_.current=[{role:"assistant",text:`${ie.text} ${M?.response||""}`}],!M||!M.response){await $t(C);return}gr(),c(q=>[...q,{id:Date.now().toString(),content:k,role:Ne.USER,timestamp:qt(Date.now()),isStored:!1}]),Ae(!0),await Qu(1e3),Ae(!1);const I=Date.now().toString();_r(I),c(q=>[...q,{id:I,content:M.response||"Please try again",role:Ne.ASSISTANT,timestamp:qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(C,k,M)=>{if(Ie())try{await y.current?.sendMessageFeedback(k,C,M)}catch{}},sendSessionFeedback:async(C,k)=>{if(!(!Ie()||!C?.length&&!k))try{await y.current?.sendSessionFeedback(C,k)}catch{}},clearElicitationState:async(C,k)=>{const M=j.getState().elicitationState,I=C?M[C]:void 0;try{await $t({message:k||"User aborted elicitation",tool_declined:!0,tool_result:I?.tool_result,tool_key:C})}catch{}finally{C&&I&&Ue(C,{...I,active:!1,disabled:!0})}},notifyTypingStarted:rn}};function Ge(e){const t=X(e);return $(()=>{t.current=e}),ue(((...n)=>t.current(...n)),[])}function xp(e){return e==="full"?R.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?R.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":R.SYNAPSE_CHANNELS?.WIDGET??"widget"}const kp=32,Op=100,Ap=320;function Rp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ip({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=V(!1),c=X(null),d=X(!1),h=X("auto"),u=X(!0),p=ue(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=ue(S=>Rp()?"auto":S,[]),g=ue(S=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(S)}),a(!1))},[p,E]),f=ue(S=>{d.current=!0,h.current=S,c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null,d.current&&(d.current=!1,g(h.current))}))},[g]);return $(()=>()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),d.current=!1},[]),$(()=>{e&&f(t||n?"auto":"smooth")},[e,t,n,f]),$(()=>{if(!e||!u.current)return;const S=setTimeout(()=>f("auto"),Ap);return()=>clearTimeout(S)},[r,e,f]),$(()=>{let S=!1,m=null,_=null,y=0;const O=()=>{if(S)return;const T=p(),v=i.current?.parentElement;if(!T||!v){requestAnimationFrame(O);return}const x=()=>{const{scrollTop:N,scrollHeight:D,clientHeight:W}=T;return D-N-W<=kp};u.current=!0;let b=0;const w=()=>{if(b>0){b--;return}u.current=x()};T.addEventListener("scroll",w,{passive:!0}),_=()=>T.removeEventListener("scroll",w),m=new ResizeObserver(()=>{if(!u.current)return;const N=Date.now();N-y<Op||(y=N,b++,f("auto"))}),m.observe(v)};return O(),()=>{S=!0,m?.disconnect(),_?.()}},[p,f]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:g,scheduleScrollToBottom:f}}const cs="eka-medassist-agent-config",fc="feedback_hidden",ds="upfront_consent_accepted";function us(e,t){try{const n=localStorage.getItem(cs);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function gc(e,t){try{const n=localStorage.getItem(cs),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(cs,JSON.stringify(r))}catch{}}function Mp({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=em(),d=Ge(()=>{r===R.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==R.VOICE_AGENT_STATE.IDLE,[u,p]=V(""),[E,g]=V(!1),[f,S]=V(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=ue(()=>S(U=>U==="full"?"widget":"full"),[]),_=Xl()?"mobile":f,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),O=Math.min(Math.max(n.sidePanelWidth??nm,rm),om),T=n.sidePanelMode??"push",[v,x]=V([]),b=X(!1),[w,N]=V(!1),[D,W]=V(!1),[G,Ce]=V(()=>!!n.theme?.upfrontConsent&&!us(t,ds)),pe=X(null),ie=j(U=>U.startNewConnection),_e=j(U=>U.showRetryButton),F=j(U=>U.clearError),de=j(U=>U.error),Oe=j(U=>U.connectionStatus),B=j(U=>U.recordingStatus),Z=j(U=>U.isWaitingForResponse),L=j(U=>U.isStreaming),K=j(U=>U.setError),re=j(U=>U.sessionId),xe=j(U=>U.initialMessage),J=j(U=>U.sessionInitialMessages),Ae=j(U=>U.elicitationState),Ye=j(U=>U.level),{incomingMessages:ae,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:Tt,notifyTypingStarted:Yt,startSession:z,startNewChat:Re,isReady:be,startRecording:Le,stopRecording:We,handleRetry:Ue,isValidFile:_t,sendMessageFeedback:ht,clearElicitationState:Ve,sendSessionFeedback:rt,getPastSessions:$e}=Tp({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:xp(n.displayMode)}),Be=Ge(Ue),Ie=Ge(ht),Ht=Ge(Ve),Et=Ge(U=>{z({sessionId:U})}),Cn=Ge(()=>{Re()}),[tn,mr]=V(!1),[nn,yt]=V([]),[Zr,pr]=V(!0),fr=X($e);$(()=>{fr.current=$e});const rn=ue(async()=>{pr(!0);try{const U=await fr.current();yt(U)}catch{}finally{pr(!1)}},[]),gr=ue(async()=>{mr(!0),await rn()},[rn]),_r=ue(()=>{mr(!1)},[]),[Er,$t]=V(!1),Jr=ue(()=>$t(U=>!U),[]);$(()=>{_!=="full"||Ye!=="user"||rn()},[_,Ye,re,rn]),$(()=>{if(t){if(pe.current!==t){const U=j.getState();Wh(t),Xh(t),U.setAgentId(t),n.force&&U.clearSession(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(U.setDisplayMode(n.displayMode),U.setInitialDisplayMode(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&U.setContext(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&U.setInitialMessage(n.initialMessage),pe.current=t}e&&be&&!b.current&&(b.current=!0,z({forceNewSession:!1}))}},[e,be,t]),$(()=>{Dm([Jl])},[]),$(()=>()=>{s()},[]),$(()=>{!n.theme?.upfrontConsent||!t||us(t,ds)||Ce(!0)},[n.theme?.upfrontConsent,t]);const yr=ue(()=>{gc(t,ds),Ce(!1)},[t]),Qr=Ge(()=>{n.feedback&&!us(t,fc)?W(!0):n.onClose()}),Tn=Ge(async(U,se)=>{await rt(U,se),W(!1),n.onClose()}),on=Ge(()=>{W(!1),n.onClose()}),Sr=Ge(()=>{gc(t,fc),W(!1),n.onClose()}),xn=ue(()=>{W(!1)},[]),br=ae.length>0,C=ae.length===1,k=le(()=>{const U=ae[ae.length-1],se=U?.tool_keys?.[U.tool_keys.length-1];if(!se)return null;const ye=Ae[se];return ye?.active?{...ye,tool_key:se}:null},[ae,Ae]),M=le(()=>(re?J[re]:void 0)??xe??n?.initialMessage??null,[re,J,xe,n?.initialMessage]),I=le(()=>!!M?.text||!!M?.suggestions?.length,[M]),q=le(()=>I&&ae?.length===0&&!Pe,[ae,I,Pe]),oe=le(()=>k?k.component===R.SYNAPSE_COMPONENTS.MOBILE||k.component===R.SYNAPSE_COMPONENTS.OTP||k.component===R.SYNAPSE_COMPONENTS.EMAIL:!1,[k]),{scrollAreaRef:ce,messagesEndRef:he,showScrollButton:Me,scrollToBottom:Ke}=Ip({messageCount:ae.length,isStreaming:L,isFirstMessage:C,resolvedMode:_}),je=Oe===ge.CONNECTED,ve=Z||L,Je=le(()=>B===Se.IDLE?null:B===Se.LISTENING?"Listening...":B===Se.PROCESSING?"Processing...":B===Se.TRANSCRIBING?"Transcribing...":null,[B]),xt=Je&&B!==Se.IDLE?Je:Z||L?"Please wait for the response...":"Type a reply\u2026",mt=Ge(async(U,se)=>{if(ve)return;const ye=se?Tt:De,et=U?.message??u;v.length>0?(await ye({files:v,message:et.trim()}),x([]),N(!1)):et.trim()?await ye({...U,message:et.trim()}):U?.resend?await ye(U):U&&await ye(U),p(""),g(!1),N(!1)}),kt=Ge(U=>mt(U,q)),sn=Ge(U=>mt(U,!0)),Qe=Ge(U=>{if(U&&U.length>0){const se=U.filter(et=>_t(et));if(se.length===0)return;const ye=mc(se,v.length);if(ye){K(ye);return}U=se}x(se=>(N((se?.length??0)+(U?.length??0)>0),[...se,...U]))}),ee=ue(U=>{x(se=>{const ye=se.filter((et,kn)=>kn!==U);return N(ye.length>0),ye})},[]),at=Ge(async()=>{if(E)await We(),g(!1);else{if(ve)return;try{await Le(),g(!0)}catch{}}}),qe=Ge(U=>{U.trim()&&Yt(),p(U)}),St=le(()=>({value:u,onChange:qe,onSend:mt,onFileChange:Qe,onRemoveFile:ee,onRecording:at,isRecording:E,hasAttachment:w,attachmentFiles:v,isDisabled:ve,placeholder:xt,recordingStatus:B,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d}),[u,qe,mt,Qe,ee,at,E,w,v,ve,xt,B,n.allowed,h,d]),Mt=le(()=>n.feedback?{isOpen:D,config:n.feedback,onSubmit:Tn,onSkip:on,onClose:xn,onDontShowAgain:Sr}:void 0,[n.feedback,D,Tn,on,xn,Sr]),Pt=le(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:yr}:void 0,[n.theme?.upfrontConsent,G,yr]);return{showScrollButton:Me,toggleDisplayMode:m,resolvedMode:_,sidePanelMode:T,sidePanelWidth:O,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:ce,messagesEndRef:he,startNewConnection:ie,showRetryButton:_e,clearError:F,error:de,sessionId:re,activeElicitation:k,inConversation:br,isFirstMessage:C,isEmptyChat:q,isAuthComponent:oe,isConnected:je,isComposerDisabled:ve,isLoadingSessionMessages:Pe,initialMessage:M,incomingMessages:ae,sendMessageFeedback:Ie,clearElicitationState:Ht,handleRetry:Be,handleChatSendMessage:kt,handleEmptyStateSendMessage:sn,handleSelectSession:Et,handleStartNewChat:Cn,scrollToBottom:Ke,handleClose:Qr,chatComposerProps:St,feedbackModalProps:Mt,consentModalProps:Pt,isSessionDrawerOpen:tn,pastSessions:nn,isLoadingPastSessions:Zr,openSessionDrawer:gr,closeSessionDrawer:_r,userLevel:Ye,isSidebarCollapsed:Er,toggleSidebar:Jr,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c}}function Qt(){return Qt=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},Qt.apply(this,arguments)}const Pp=["children","options"],_c=["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"}),Ec={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Dp=["style","script","pre"],Lp=["src","href","data","formAction","srcDoc","action"],Up=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,Fp=/\n{2,}$/,yc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Vp=/^ *> ?/gm,jp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,zp=/^ {2,}\n/,Yp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Sc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,bc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Hp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,$p=/^(?:\n *)*\n/,Bp=/\r\n?/g,Gp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Wp=/^\[\^([^\]]+)]/,Kp=/\f/g,qp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,Xp=/^\s*?\[(x|\s)\]/,vc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,wc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Nc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,hs=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Zp=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Cc=/^<!--[\s\S]*?(?:-->)/,Jp=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,ms=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Qp=/^\{.*\}$/,ef=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,tf=/^<([^ >]+[:@\/][^ >]+)>/,nf=/-([a-z])?/gi,Tc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,rf=/^[^\n]+(?: \n|\n{2,})/,of=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,sf=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,af=/^\[([^\]]*)\] ?\[([^\]]*)\]/,lf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,cf=/\t/g,df=/(^ *\||\| *$)/g,uf=/^ *:-+: *$/,hf=/^ *:-+ *$/,mf=/^ *-+: *$/,$r=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Br="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",pf=RegExp(`^([*_])\\1${$r(1)}${Br}\\1\\1(?!\\1)`),ff=RegExp(`^([*_])${$r(0)}${Br}\\1(?!\\1)`),gf=RegExp(`^(==)${$r(0)}${Br}\\1`),_f=RegExp(`^(~~)${$r(0)}${Br}\\1`),Ef=/^(:[a-zA-Z0-9-_]+:)/,yf=/^\\([^0-9A-Za-z\s])/,Sf=/\\([^0-9A-Za-z\s])/g,bf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,vf=/^\n+/,wf=/^([ \t]*)/,Nf=/(?:^|\n)( *)$/,ps="(?:\\d+\\.)",fs="(?:[*+-])";function xc(e){return"( *)("+(e===1?ps:fs)+") +"}const kc=xc(1),Oc=xc(2);function Ac(e){return RegExp("^"+(e===1?kc:Oc))}const Cf=Ac(1),Tf=Ac(2);function Rc(e){return RegExp("^"+(e===1?kc:Oc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?ps:fs)+" )[^\\n]*)*(\\n|$)","gm")}const xf=Rc(1),kf=Rc(2);function Ic(e){const t=e===1?ps:fs;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Mc=Ic(1),Pc=Ic(2);function Dc(e,t){const n=t===1,r=n?Mc:Pc,o=n?xf:kf,i=n?Cf:Tf;return{t:s=>i.test(s),o:Nn(function(s,a){const c=Nf.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(Fp,`
|
|
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"),S=p.replace(f,"").replace(i,""),m=E===h.length-1,_=S.indexOf(`
|
|
42
42
|
|
|
43
|
-
`)!==-1||m&&u;u=_;const y=c.inline,
|
|
43
|
+
`)!==-1||m&&u;u=_;const y=c.inline,O=c.list;let T;c.list=!0,_?(c.inline=!1,T=dr(S)+`
|
|
44
44
|
|
|
45
|
-
`):(c.inline=!0,T=
|
|
46
|
-
`).map(function(d){return
|
|
45
|
+
`):(c.inline=!0,T=dr(S));const v=a(T,c);return c.inline=y,c.list=O,v}),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 Of=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Af=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function Lc(e){return typeof e=="string"}function dr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Gr(e,t){return e.startsWith(t)}function Rf(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Gr(e,n[r]))return!0;return!1}return n(e,t)}function ur(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 If(e){return mf.test(e)?"right":uf.test(e)?"center":hf.test(e)?"left":null}function Uc(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 Mf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(df,"").split("|").map(If):[],o=e[3]?(function(s,a,c){return s.trim().split(`
|
|
46
|
+
`).map(function(d){return Uc(d,a,c,!0)})})(e[3],t,n):[],i=Uc(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 Fc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function Nn(e){return e.inline=1,e}function en(e){return Nn(function(t,n){return n.inline?e.exec(t):null})}function zt(e){return Nn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function It(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Wr(e){return Nn(function(t){return e.exec(t)})}const Pf=/(javascript|vbscript|data(?!:image)):/i;function Df(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Pf.test(t))return null}catch{return null}return e}function Ct(e){return e&&e.replace(Sf,"$1")}function Kr(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 Lf(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 Uf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const gs=(e,t,n)=>({children:Kr(t,e[2],n)});function _s(){return{}}function Es(){return null}function Ff(...e){return e.filter(Boolean).join(" ")}function ys(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 Vf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?Qt({},Ec,t.namedCodesToUnicode):Ec;const n=t.slugify||ur,r=t.sanitizer||Df,o=t.createElement||tt,i=[yc,Sc,bc,t.enforceAtxHeadings?wc:vc,Nc,Tc,Mc,Pc],s=[...i,rf,hs,Cc,ms];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function c(m,_,...y){const O=ys(t.overrides,m+".props",{});return o((function(T,v){const x=ys(v,T);return x?typeof x=="function"||typeof x=="object"&&"render"in x?x:ys(v,T+".component",T):T})(m,t.overrides),Qt({},_,O,{className:Ff(_?.className,O.className)||void 0}),...y)}function d(m){m=m.replace(qp,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=lf.test(m)===!1);const y=f(g(_?m:dr(m).replace(vf,"")+`
|
|
47
47
|
|
|
48
|
-
`,{inline:_}));for(;
|
|
49
|
-
`);return _>0&&_<m.length-1&&(m[_+1]==="="||m[_+1]==="-")},o:
|
|
50
|
-
`],o:
|
|
51
|
-
`},21:{o:
|
|
48
|
+
`,{inline:_}));for(;Lc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const O=t.wrapper||(_?"span":"div");let T;if(y.length>1||t.forceWrapper)T=y;else{if(y.length===1)return T=y[0],typeof T=="string"?c("span",{key:"outer"},T):T;T=null}return o(O,{key:"outer"},T)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(Up);return y?y.reduce(function(O,T){const v=T.indexOf("=");if(v!==-1){const x=(function(D){return D.indexOf("-")!==-1&&D.match(Jp)===null&&(D=D.replace(nf,function(W,G){return G.toUpperCase()})),D})(T.slice(0,v)).trim(),b=(function(D){const W=D[0];return(W==='"'||W==="'")&&D.length>=2&&D[D.length-1]===W?D.slice(1,-1):D})(T.slice(v+1).trim()),w=_c[x]||x;if(w==="ref")return O;const N=O[w]=(function(D,W,G,Ce){return W==="style"?(function(pe){const ie=[];let _e="",F=!1,de=!1,Oe="";if(!pe)return ie;for(let Z=0;Z<pe.length;Z++){const L=pe[Z];if(L!=='"'&&L!=="'"||F||(de?L===Oe&&(de=!1,Oe=""):(de=!0,Oe=L)),L==="("&&_e.endsWith("url")?F=!0:L===")"&&F&&(F=!1),L!==";"||de||F)_e+=L;else{const K=_e.trim();if(K){const re=K.indexOf(":");if(re>0){const xe=K.slice(0,re).trim(),J=K.slice(re+1).trim();ie.push([xe,J])}}_e=""}}const B=_e.trim();if(B){const Z=B.indexOf(":");if(Z>0){const L=B.slice(0,Z).trim(),K=B.slice(Z+1).trim();ie.push([L,K])}}return ie})(G).reduce(function(pe,[ie,_e]){return pe[ie.replace(/(-[a-z])/g,F=>F[1].toUpperCase())]=Ce(_e,D,ie),pe},{}):Lp.indexOf(W)!==-1?Ce(Ct(G),D,W):(G.match(Qp)&&(G=Ct(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,x,b,r);typeof N=="string"&&(hs.test(N)||ms.test(N))&&(O[w]=d(N.trim()))}else T!=="style"&&(O[_c[T]||T]=!0);return O},{}):null}const u=[],p={},E={0:{t:[">"],o:It(yc),i:1,u(m,_,y){const[,O,T]=m[0].replace(Vp,"").match(jp);return{alert:O,children:_(T,y)}},l(m,_,y){const O={key:y.key};return m.alert&&(O.className="markdown-alert-"+n(m.alert.toLowerCase(),ur),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",O,_(m.children,y))}},1:{t:[" "],o:Wr(zp),i:1,u:_s,l:(m,_,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:It(Yp),i:1,u:_s,l:(m,_,y)=>c("hr",{key:y.key})},3:{t:[" "],o:It(bc),i:0,u:m=>({lang:void 0,text:Ct(dr(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>c("pre",{key:y.key},c("code",Qt({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:It(Sc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:zt(Hp),i:3,u:m=>({text:Ct(m[2])}),l:(m,_,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:It(Gp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Es},7:{t:["[^"],o:en(Wp),i:1,u:m=>({target:"#"+n(m[1],ur),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:en(Xp),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:It(t.enforceAtxHeadings?wc:vc),i:1,u:(m,_,y)=>({children:Kr(_,m[2],y),id:n(m[2],ur),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:It(Nc),i:1,u:(m,_,y)=>({children:Kr(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Wr(hs),i:1,u(m,_,y){const[,O]=m[3].match(wf),T=RegExp("^"+O,"gm"),v=m[3].replace(T,""),x=a(s,v)?Uf:Kr,b=m[1].toLowerCase(),w=Dp.indexOf(b)!==-1,N=(w?b:m[1]).trim(),D={attrs:h(N,m[2]),noInnerParse:w,tag:N};if(y.inAnchor=y.inAnchor||b==="a",w)D.text=m[3];else{const W=y.inHTML;y.inHTML=!0,D.children=x(_,v,y),y.inHTML=W}return y.inAnchor=!1,D},l:(m,_,y)=>c(m.tag,Qt({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:Wr(ms),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>c(m.tag,Qt({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Wr(Cc),i:1,u:()=>({}),l:Es},14:{t:["!["],o:zt(Af),i:1,u:m=>({alt:Ct(m[1]),target:Ct(m[2]),title:Ct(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:en(Of),i:3,u:(m,_,y)=>({children:Lf(_,m[1],y),target:Ct(m[2]),title:Ct(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:en(tf),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&&(Gr(m,"http://")||Gr(m,"https://")),o:en(ef),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Dc(c,1),33:Dc(c,2),19:{t:[`
|
|
50
|
+
`],o:It($p),i:3,u:_s,l:()=>`
|
|
51
|
+
`},21:{o:Nn(function(m,_){if(_.inline||_.simple||_.inHTML&&m.indexOf(`
|
|
52
52
|
|
|
53
53
|
`)===-1&&_.prevCapture.indexOf(`
|
|
54
54
|
|
|
55
|
-
`)===-1)return null;let y="",
|
|
56
|
-
`,
|
|
57
|
-
`).replace(Ap,"").replace(Bp," ")})(k),T)}})(E),g=(function(m,_){return function y(k,T={}){if(Array.isArray(k)){const x=T.key,N=[];let v=!1;for(let b=0;b<k.length;b++){T.key=b;const R=y(k[b],T),A=Nc(R);A&&v?N[N.length-1]+=R:R!==null&&N.push(R),v=A}return T.key=x,N}return(function(x,N,v){const b=m[x.type].l;return _?_(()=>b(x,N,v),x,N,v):b(x,N,v)})(k,y,T)}})(E,t.renderRule),S=d(e);return u.length?c("div",null,S,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,or),key:m.identifier},m.identifier,g(p(m.footnote,{inline:!0})))}))):S}const wf=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,_p);return Lt(bf(t??"",n),r)},Nf={disableParsingRawHTML:!0,forceBlock:!0};function Vr({children:e}){return l(wf,{options:Nf,children:e})}function Tc({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:M("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 xf=Xe(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Cf=Xe(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),Tf=Xe(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),kf=Xe(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Rf=Xe(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function ze({className:e}){return l("div",{className:M("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 sr({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(ze,{className:"h-8 w-20 rounded-full"}),l(ze,{className:"h-8 w-24 rounded-full"}),l(ze,{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(ze,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(ze,{className:"h-3 w-3/4 rounded"}),l(ze,{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(ze,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(ze,{className:"h-9 w-full rounded-lg"}),l(ze,{className:"h-9 w-full rounded-lg"}),l(ze,{className:"h-9 w-full rounded-lg"})]}),l(ze,{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(ze,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(ze,{className:"h-3 w-3/4 rounded"}),l(ze,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(ze,{className:"h-3 w-full rounded"}),l(ze,{className:"h-3 w-5/6 rounded"})]}),l(ze,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function jr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Of({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=F([]),[a,c]=F({}),[d,h]=F(!1),[u,f]=F(5),E=n.component,p=n.disabled,g=ye(()=>n.input,[n.input]);Y(()=>{E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&c(g.doctor_details)},[E,g?.doctor_details]),Y(()=>{n.disabled||(h(!1),f(5),s([]))},[g,n.disabled]);const S=async b=>{h(!0),await r({message:b.value,messageId:e,toolCalled:!0,selectedComponent:b,tool_key:t})},m=async(b,R,A,$=!0)=>{await r({toolCalled:$,selectedComponent:b,selected_id:b.doctor_id,message:R,tool_key:t,messageId:e,...A&&{tool_result:A}})},_=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 b=E===I.SYNAPSE_COMPONENTS.MULTI&&g?.options;return b?Array.isArray(b)?b.map((R,A)=>({id:`option-${A}`,label:R.label,value:R.value})):Object.keys(b).map((R,A)=>({id:`option-${A}`,label:R,value:R})):[]},T=ye(()=>{if(E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(b=>!!b&&!!b.doctor_id)},[E,g?.doctors]);if(!E)return null;const x=E===I.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,N=E===I.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,v=E===I.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return l("div",{className:"flex justify-end",children:[x&&l("div",{className:`flex ${x.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[x.slice(0,u).map((b,R)=>l(Tc,{disabled:p||o||d,text:b?.label||"",onClick:()=>S(b),className:"cursor-pointer"},R)),x.length>u&&l("button",{type:"button",disabled:p||o||d,onClick:()=>f(b=>b+5),className:M("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(jo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,x.length-u)," more"]})]}),E===I.SYNAPSE_COMPONENTS.MULTI&&g?.options&&l(He,{fallback:l(sr,{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(xf,{options:k(),selectedValues:i,onSelectionChange:s,disabled:p||o}),l(ce,{onClick:y,disabled:i.length===0||p||o,className:M("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"})]})}),T&&T.length>0?l(He,{fallback:l(sr,{variant:"card"}),children:l(Cf,{count:T.length>1?T.length+1:T.length,renderItem:(b,R)=>{if(T.length>1&&b===T.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:_,disabled:o||p,className:M("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:M("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(xh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const A=T[b];return l(He,{fallback:l(sr,{variant:"card"}),children:l(Tf,{doctor:A,doctorDetails:a?.[A.doctor_id],disabled:o,onSelect:m,isActive:R})},A.doctor_id)}})}):null,N&&l(He,{fallback:l(sr,{variant:"card"}),children:l(kf,{cards:N,onSelect:async b=>{await r({...b,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:p||o})}),v&&l(He,{fallback:l(sr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(Rf,{card:v})})})]})}function Af({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:f,onClearElicitationState:E,isAuthComponent:p,isFullScreen:g}){const S=t==="user",[m,_]=F(I.USER_FEEDBACK.NONE),y=W(x=>x.isStreaming),k=x=>{_(x),u(x)},T=!!(n?.trim()||r&&r.length>0||d||i||a);return l(ue,{children:[T&&l("div",{className:M("flex",S?"justify-end":"justify-start"),children:l("div",{className:M("flex gap-3",S?"flex-row-reverse":"flex-row",S?"max-w-[60%]":g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(qt,{className:M("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",S?"bg-primary text-primary-foreground shadow-sm":M("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!S&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!S&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:M("markdown-content",g&&!S?"text-base leading-6":"text-sm"),children:l(Vr,{children:`${n} ${!S&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l(ts,{files:r,isPreview:!1,className:""})}),i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!S&&!y&&o&&n&&m===I.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ce,{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:()=>k(I.USER_FEEDBACK.LIKE),children:l(Rr,{className:"h-3 w-3"})}),l(ce,{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:()=>k(I.USER_FEEDBACK.DISLIKE),children:l(Or,{className:"h-3 w-3"})})]})}),!a&&!S&&!y&&o&&m===I.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Rr,{className:"h-3 w-3"})})}),!a&&!S&&!y&&o&&m===I.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Or,{className:"h-3 w-3"})})}),p&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{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 x=s[s.length-1];x&&c[x]?.active&&E(x,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(x=>{const N=c[x];return N?l(Of,{messageId:e,tool_key:x,entry:N,onSendMessage:h,disabled:f||N.disabled},x):null}),a&&!S&&l("div",{className:"flex justify-start",children:l("div",{className:M("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(qt,{className:M("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",g&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:l("div",{className:M("markdown-content",g?"text-base leading-6":"text-sm"),children:l(Vr,{children:a})})}),!y&&o&&m===I.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ce,{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:()=>k(I.USER_FEEDBACK.LIKE),children:l(Rr,{className:"h-3 w-3"})}),l(ce,{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:()=>k(I.USER_FEEDBACK.DISLIKE),children:l(Or,{className:"h-3 w-3"})})]})}),!y&&o&&m===I.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Rr,{className:"h-3 w-3"})})}),!y&&o&&m===I.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Or,{className:"h-3 w-3"})})})]})})})]})}function If({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(ue,{children:[e&&l("div",{className:"flex justify-start",children:l("div",{className:M("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l(qt,{className:M("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:M("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Vr,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:M("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(Tc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}function Mf({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const c=W(u=>u.isWaitingForResponse),d=W(u=>u.elicitationState),h=W(u=>u.progressMessage);return e.length===0&&!h?l(If,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):l(ue,{children:[(e&&e.length>0||h)&&l(ue,{children:e.map((u,f)=>l("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:f===e.length-1?"last-message":void 0,children:l(Af,{id:u.id,role:u.role,content:u.content,files:u.files||[],toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,timestamp:u.timestamp,onSendMessage:t,isLastMessage:f===e.length-1,progressMessage:h,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:E=>n(E,u.id),onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),c&&l(Pf,{})]})}function Pf(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(qt,{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 kc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=Jl(),[c,d]=F(!0);return Y(()=>{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:M("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:M("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:M("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 Df=Xe(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function Lf({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:f,activeElicitation:E,isAuthComponent:p,isConnected:g,inConversation:S,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:T,startSession:x,sendMessageFeedback:N,clearElicitationState:v,handleRetry:b,scrollToBottom:R,chatComposerProps:A,isComposerDisabled:$,voiceAgentState:J,isMuted:oe,isVoiceAgentActive:_e,disconnectVoiceAgent:ie,resetVoiceAgent:he,toggleMute:U,handleClose:Te,isSessionDrawerOpen:de,pastSessions:V,isLoadingPastSessions:H,openSessionDrawer:D,closeSessionDrawer:B,userLevel:Ee,isSidebarCollapsed:Ne,toggleSidebar:se,showFeedbackModal:ne,handleSessionFeedbackSubmit:$e,handleSessionFeedbackSkip:Ge,handleDontShowAgain:We,handleCloseModal:Je,showConsentModal:Ot,handleConsentAccept:mt,handleSendMessage:it,sidePanelMode:L,sidePanelWidth:Oe,side:le,onSidePanelPushChange:Re}=gp({isOpen:e,agentId:t,config:n});Y(()=>{T.length||R("auto")},[T.length,R]);const Ze=ye(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),rt=o==="full"&&Ee==="user"?l(Bm,{sessions:V,activeSessionId:f,onSelectSession:xe=>x({sessionId:xe}),onNewChat:()=>x({forceNewSession:!0}),isCollapsed:Ne,onToggle:se,isLoading:H}):void 0;return l(gm,{enabled:!!n.resize,children:l(Kl,{isOpen:e,onClose:Te,feedbackModal:n.feedback?{isOpen:ne,config:n.feedback,onSubmit:$e,onSkip:Ge,onClose:Je,onDontShowAgain:We}:void 0,consentModal:n.theme?.upfrontConsent?{isOpen:Ot,onAccept:mt}:void 0,showCloseButton:n.showCloseButton,title:n.title,showStartNewChatButton:c,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:()=>x({forceNewSession:!0}),sessionId:f,environment:n.environment,mode:o,sidePanelMode:L,sidePanelWidth:Oe,side:le,onSidePanelPushChange:Re,onToggleDisplayMode:n.resize?r:void 0,theme:n.theme,isAuthComponent:p,activeElicitation:E,voiceAgentState:J,chatComposer:A,onOpenSessionDrawer:D,sessionDrawer:l(Km,{isOpen:de,onClose:B,sessions:V,activeSessionId:f,onSelectSession:xe=>{x({sessionId:xe})},onNewChat:()=>x({forceNewSession:!0})}),sidebar:rt,fullScreenEmptyState:_?xe=>l(Jm,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:at=>it(at,!0),disabled:$,composer:xe.composer,composerFooter:xe.composerFooter,connectionBanner:l(kc,{onRetry:b,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})}):void 0,children:_e?l(He,{fallback:l(Rc,{}),children:l(Df,{state:J,isMuted:oe,onEndCall:ie,onClose:he,onToggleMute:U,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l(He,{fallback:l(Rc,{}),children:l("div",{className:M("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(nl,{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:M("min-w-0 overflow-x-hidden",S?"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(nm,{}):l(ue,{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:Ze}),l(Mf,{messages:T,onSendMessage:xe=>it(xe,_),iconUrl:n.iconUrl,onToggleFeedback:N,onClearElicitationState:v,isAuthComponent:p,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),l("div",{ref:s})]})]})}),a&&l("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:l(ce,{onClick:()=>R("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(jo,{className:"w-5 h-5 text-text-primary"})})}),l(kc,{className:"mt-2",onRetry:b,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})]})})})})}function Rc(){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 Oc(e){return!!e&&e.startsWith("ResizeObserver loop")}function fs(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 Ff extends ot{constructor(){super(...arguments);O(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:fs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(jf,{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 Uf({error:e}){throw e}function Vf(e){const[t,n]=F(null);return Y(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Oc(i?.message)||Oc(i?.error?.message)||(i?.error?n(fs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(fs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(Ff,{...e,children:t?l(Uf,{error:t}):e.children})}function jf({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",f=ye(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]);return l(Kl,{isOpen:!0,onClose:o??(()=>{}),showCloseButton:i??!1,onStartNewSession:d,title:h,titleImg:n,iconUrl:r,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(bh,{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",f].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",f].join(" "),children:e?.message||String(e)}),l("div",{className:"mt-5 flex items-center justify-center gap-3",children:l(ce,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(_h,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})}function zf({agentId:e,config:t}){const[n,r]=F(t.displayMode==="full");Y(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(Vf,{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(Dh,{children:l(Lf,{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 Ac=(e,t,n)=>{const r=n||{},o=od(e);return o.render(l(ue,{children:l(zf,{agentId:t,config:r})})),o},Yf=e=>{try{const t=sessionStorage.getItem(nr(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{}}},Ic=e=>{const{refreshToken:t,sessToken:n}=Yf(e.agentId);return t&&n?Promise.resolve(null):I.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Mc=e=>I.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Ac,window.fetchAgentConfig=Mc,window.prefetchAuth=Ic);export{q as A,ce as B,jo as C,Q as D,dl as F,ul as I,zo as M,Eo as N,sn as P,bo as R,ns as S,ye as T,_n as X,dt as _,I as a,M as b,Fe as c,F as d,ue as e,Gt as f,Mc as fetchAgentConfig,mi as g,an as h,Ft as i,Vt as j,Qm as k,El as l,Zo as m,Ul as n,Qo as o,Zm as p,Ic as prefetchAuth,fe as q,Sl as r,Ac as renderMedAssist,Vr as s,Ql as t,l as u,qt as v,ep as w,yl as x,Y as y,vl as z};
|
|
55
|
+
`)===-1)return null;let y="",O=0;for(;;){const v=m.indexOf(`
|
|
56
|
+
`,O),x=m.slice(O,v===-1?void 0:v+1);if(a(i,x)||(y+=x,v===-1||!x.trim()))break;O=v+1}const T=dr(y);return T===""?null:[y,,T]}),i:3,u:gs,l:(m,_,y)=>c("p",{key:y.key},_(m.children,y))},22:{t:["["],o:en(of),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Es},23:{t:["!["],o:zt(sf),i:0,u:m=>({alt:m[1]?Ct(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:en(af),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:It(Tc),i:1,u:Mf,l(m,_,y){const O=m;return c("table",{key:y.key},c("thead",null,c("tr",null,O.header.map(function(T,v){return c("th",{key:v,style:Fc(O,v)},_(T,y))}))),c("tbody",null,O.cells.map(function(T,v){return c("tr",{key:v},T.map(function(x,b){return c("td",{key:b,style:Fc(O,b)},_(x,y))}))})))}},27:{o:Nn(function(m,_){let y;return Gr(m,":")&&(y=Ef.exec(m)),y||bf.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(Zp,(y,O)=>t.namedCodesToUnicode[O]||y)}},l:m=>m.text},28:{t:["**","__"],o:zt(pf),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:zt(ff),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:zt(yf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:zt(gf),i:3,u:gs,l:(m,_,y)=>c("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:zt(_f),i:3,u:gs,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(O,T){var v=[];if(T.prevCapture=T.prevCapture||"",O.trim())for(;O;)for(var x=0;x<_.length;){var b=_[x],w=m[b];if(!w.t||Rf(O,T,w.t)){var N=w.o(O,T);if(N&&N[0]){O=O.substring(N[0].length);var D=w.u(N,y,T);T.prevCapture+=N[0],D.type||(D.type=b),v.push(D);break}x++}else x++}return T.prevCapture="",v}return _.sort(function(O,T){return m[O].i-m[T].i||(O<T?-1:1)}),function(O,T){return y((function(v){return v.replace(Bp,`
|
|
57
|
+
`).replace(Kp,"").replace(cf," ")})(O),T)}})(E),f=(function(m,_){return function y(O,T={}){if(Array.isArray(O)){const v=T.key,x=[];let b=!1;for(let w=0;w<O.length;w++){T.key=w;const N=y(O[w],T),D=Lc(N);D&&b?x[x.length-1]+=N:N!==null&&x.push(N),b=D}return T.key=v,x}return(function(v,x,b){const w=m[v.type].l;return _?_(()=>w(v,x,b),v,x,b):w(v,x,b)})(O,y,T)}})(E,t.renderRule),S=d(e);return u.length?c("div",null,S,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,ur),key:m.identifier},m.identifier,f(g(m.footnote,{inline:!0})))}))):S}const jf=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,Pp);return Lt(Vf(t??"",n),r)},zf={disableParsingRawHTML:!0,forceBlock:!0};function Yf({children:e}){return l(jf,{options:zf,children:e})}const qr=Gt(Yf);function Vc({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:P("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 Hf=nt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),$f=nt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),Bf=nt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),Gf=nt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Wf=nt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function He({className:e}){return l("div",{className:P("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 hr({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(Xr,{}),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(Xr,{}),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(Xr,{}),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(Xr,{}),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 Xr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Kf({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=le(()=>n.input,[n.input]);$(()=>{E===R.SYNAPSE_COMPONENTS.DOCTOR_CARD&&f?.doctor_details&&c(f.doctor_details)},[E,f?.doctor_details]),$(()=>{n.disabled||(h(!1),p(5),s([]))},[f,n.disabled]);const S=async w=>{h(!0),await r({message:w.value,messageId:e,toolCalled:!0,selectedComponent:w,tool_key:t})},m=async(w,N,D,W=!0)=>{await r({toolCalled:W,selectedComponent:w,selected_id:w.doctor_id,message:N,tool_key:t,messageId:e,...D&&{tool_result:D}})},_=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})},O=()=>{const w=E===R.SYNAPSE_COMPONENTS.MULTI&&f?.options;return w?Array.isArray(w)?w.map((N,D)=>({id:`option-${D}`,label:N.label,value:N.value})):Object.keys(w).map((N,D)=>({id:`option-${D}`,label:N,value:N})):[]},T=le(()=>{if(E===R.SYNAPSE_COMPONENTS.DOCTOR_CARD)return f?.doctors?.filter(w=>!!w&&!!w.doctor_id)},[E,f?.doctors]);if(!E)return null;const v=E===R.SYNAPSE_COMPONENTS.PILL?f?.options:void 0,x=E===R.SYNAPSE_COMPONENTS.CARD?f?.cards:void 0,b=E===R.SYNAPSE_COMPONENTS.MEDIA_CARD?f?.media_card:void 0;return l("div",{className:"flex justify-end",children:[v&&l("div",{className:`flex ${v.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[v.slice(0,u).map((w,N)=>l(Vc,{disabled:g||o||d,text:w?.label||"",onClick:()=>S(w),className:"cursor-pointer"},N)),v.length>u&&l("button",{type:"button",disabled:g||o||d,onClick:()=>p(w=>w+5),className:P("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(Bo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,v.length-u)," more"]})]}),E===R.SYNAPSE_COMPONENTS.MULTI&&f?.options&&l(Xe,{fallback:l(hr,{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(Hf,{options:O(),selectedValues:i,onSelectionChange:s,disabled:g||o}),l(Ee,{onClick:y,disabled:i.length===0||g||o,className:P("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"})]})}),T&&T.length>0?l(Xe,{fallback:l(hr,{variant:"card"}),children:l($f,{count:T.length>1?T.length+1:T.length,renderItem:(w,N)=>{if(T.length>1&&w===T.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:_,disabled:o||g,className:P("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:P("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(Fh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const D=T[w];return l(Xe,{fallback:l(hr,{variant:"card"}),children:l(Bf,{doctor:D,doctorDetails:a?.[D.doctor_id],disabled:o,onSelect:m,isActive:N})},D.doctor_id)}})}):null,x&&l(Xe,{fallback:l(hr,{variant:"card"}),children:l(Gf,{cards:x,onSelect:async w=>{await r({...w,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:g||o})}),b&&l(Xe,{fallback:l(hr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(Wf,{card:b})})})]})}function jc({userFeedback:e,onToggleFeedback:t}){if(e===R.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(R.USER_FEEDBACK.LIKE),children:l(yl,{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(R.USER_FEEDBACK.DISLIKE),children:l(Sl,{className:"h-3 w-3"})})]})});if(e===R.USER_FEEDBACK.LIKE||e===R.USER_FEEDBACK.DISLIKE){const n=e===R.USER_FEEDBACK.LIKE?yl:Sl;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 S=t===Ne.USER,[m,_]=V(R.USER_FEEDBACK.NONE),y=j(v=>v.isStreaming),O=v=>{_(v),u(v,e)},T=!!(n?.trim()||r&&r.length>0||d||i||a);return l(me,{children:[T&&l("div",{className:P("flex",S?"justify-end":"justify-start"),children:l("div",{className:P("flex gap-3",S?"flex-row-reverse":"flex-row",S?"max-w-[60%]":f?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(Xt,{className:P("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",S?"bg-primary text-primary-foreground shadow-sm":P("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),f&&!S&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!S&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:P("markdown-content",f&&!S?"text-base leading-6":"text-sm"),children:l(qr,{children:`${n} ${!S&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l(is,{files:r,isPreview:!1,className:""})}),i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!S&&!y&&o&&(n||m!==R.USER_FEEDBACK.NONE)&&l(jc,{userFeedback:m,onToggleFeedback:O}),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 v=s[s.length-1];v&&c[v]?.active&&E(v,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(v=>{const x=c[v];return x?l(Kf,{messageId:e,tool_key:v,entry:x,onSendMessage:h,disabled:p||x.disabled},v):null}),a&&!S&&l("div",{className:"flex justify-start",children:l("div",{className:P("flex gap-3 flex-row",f?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(Xt,{className:P("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:P("markdown-content",f?"text-base leading-6":"text-sm"),children:l(qr,{children:a})})}),!y&&o&&l(jc,{userFeedback:m,onToggleFeedback:O})]})})})]})}const Xf=Gt(qf);function Zf({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:P("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l(Xt,{className:P("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:P("markdown-content",o?"text-base leading-6":"text-sm"),children:l(qr,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:P("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(Vc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}const Jf=[];function Qf({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(Zf,{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(Xf,{id:u.id,role:u.role,content:u.content,files:u.files||Jf,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(tg,{})]})}const eg=Gt(Qf);function tg(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(Xt,{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 zc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=lc(),[c,d]=V(!0);return $(()=>{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:P("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:P("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:P("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 ng=nt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function rg({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:S,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:O,incomingMessages:T,sendMessageFeedback:v,clearElicitationState:x,handleRetry:b,scrollToBottom:w,chatComposerProps:N,isComposerDisabled:D,voiceAgentState:W,isMuted:G,isVoiceAgentActive:Ce,disconnectVoiceAgent:pe,resetVoiceAgent:ie,toggleMute:_e,handleClose:F,isSessionDrawerOpen:de,pastSessions:Oe,isLoadingPastSessions:B,openSessionDrawer:Z,closeSessionDrawer:L,userLevel:K,isSidebarCollapsed:re,toggleSidebar:xe,feedbackModalProps:J,consentModalProps:Ae,handleChatSendMessage:Ye,handleEmptyStateSendMessage:ae,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:Tt,sidePanelWidth:Yt,side:z,onSidePanelPushChange:Re}=Mp({isOpen:e,agentId:t,config:n});$(()=>{T.length||w("auto")},[T.length,w]);const be=le(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=le(()=>o==="full"&&K==="user"?l(ic,{variant:"sidebar",sessions:Oe,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:xe,isLoading:B}):void 0,[o,K,Oe,p,Pe,De,re,xe,B]),We=le(()=>({onRetry:b,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:f}),[b,d,c,h,u,f]),Ue=le(()=>({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:Z}),[F,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,c,n.resize,r,Z]),_t=le(()=>l(ic,{variant:"drawer",isOpen:de,onClose:L,sessions:Oe,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:B}),[de,L,Oe,p,Pe,De,B]);return l(Rm,{enabled:!!n.resize,children:l(tc,{value:Ue,children:l(oc,{isOpen:e,feedbackModal:J,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:Tt,sidePanelWidth:Yt,side:z,onSidePanelPushChange:Re,theme:n.theme,isAuthComponent:g,activeElicitation:E,voiceAgentState:W,chatComposer:N,sessionDrawer:_t,sidebar:Le,fullScreenEmptyState:_?ht=>l(mp,{title:n.title,description:O?.text,suggestions:O?.suggestions,onSendMessage:ae,disabled:D,composer:ht.composer,composerFooter:ht.composerFooter,connectionBanner:l(zc,{...We})}):void 0,children:Ce?l(Xe,{fallback:l(Yc,{}),children:l(ng,{state:W,isMuted:G,onEndCall:pe,onClose:ie,onToggleMute:_e,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l(Xe,{fallback:l(Yc,{}),children:l("div",{className:P("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(al,{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:P("min-w-0 overflow-x-hidden",S?"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(_m,{}):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(eg,{messages:T,onSendMessage:Ye,onToggleFeedback:v,onClearElicitationState:x,isAuthComponent:g,isFullScreen:o==="full",initialMessage:O??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:()=>w("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(Bo,{className:"w-5 h-5 text-text-primary"})})}),l(zc,{className:"mt-2",...We})]})})})})})}function Yc(){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 Hc(e){return!!e&&e.startsWith("ResizeObserver loop")}function Ss(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 og extends lt{constructor(){super(...arguments);A(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:Ss(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(ag,{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 sg({error:e}){throw e}function ig(e){const[t,n]=V(null);return $(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Hc(i?.message)||Hc(i?.error?.message)||(i?.error?n(Ss(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(Ss(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(og,{...e,children:t?l(sg,{error:t}):e.children})}function ag({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=le(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]),E=le(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return l(tc,{value:E,children:l(oc,{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(Dh,{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(Ah,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function lg({agentId:e,config:t}){const[n,r]=V(t.displayMode==="full");$(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(ig,{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(Zh,{children:l(rg,{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 $c=(e,t,n)=>{const r=n||{},o=_d(e);return o.render(l(me,{children:l(lg,{agentId:t,config:r})})),o},cg=e=>{try{const t=sessionStorage.getItem(lr(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{}}},Bc=e=>{const{refreshToken:t,sessToken:n}=cg(e.agentId);return t&&n?Promise.resolve(null):R.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Gc=e=>R.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=$c,window.fetchAgentConfig=Gc,window.prefetchAuth=Bc);export{X as A,Ee as B,Bo as C,te as D,fl as F,gl as I,Go as M,Gt as N,un as P,xo as R,as as S,le as T,vn as X,pt as _,R as a,P as b,ze as c,V as d,me as e,Wt as f,Gc as fetchAgentConfig,Ei as g,hn as h,Ut as i,Vt as j,fp as k,Nl as l,rs as m,Gl as n,os as o,pp as p,Bc as prefetchAuth,ue as q,Tl as r,$c as renderMedAssist,qr as s,dc as t,l as u,Xt as v,gp as w,Cl as x,$ as y,xl as z};
|