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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var 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&&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:`
1
+ var qc=Object.defineProperty;var Xc=(e,t,n)=>t in e?qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>Xc(e,typeof t!="symbol"?t+"":t,n);var In,Q,Ns,Pt,Cs,xs,Ts,ro,br,Mn,ks,oo,so,io,Os,wr={},Nr=[],Zc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Pn=Array.isArray;function yt(e,t){for(var n in t)e[n]=t[n];return e}function ao(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?In.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 Dn(e,s,r,o,null)}function Dn(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ns,__i:-1,__u:0};return o==null&&Q.vnode!=null&&Q.vnode(i),i}function Rs(){return{current:null}}function me(e){return e.children}function lt(e,t){this.props=e,this.context=t}function 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 Jc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=yt({},t);i.__v=t.__v+1,Q.vnode&&Q.vnode(i),co(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,Ls(r,i,o),t.__e=t.__=null,i.__e!=n&&As(i)}}function As(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),As(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Pt.push(e)&&!Cr.__r++||Cs!=Q.debounceRendering)&&((Cs=Q.debounceRendering)||xs)(Cr)}function Cr(){try{for(var e,t=1;Pt.length;)Pt.length>t&&Pt.sort(Ts),e=Pt.shift(),t=Pt.length,Jc(e)}finally{Pt.length=Cr.__r=0}}function Is(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=Qc(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=co(e,E,p,o,i,s,a,c,d,h),g=E.__e,E.ref&&p.ref!=E.ref&&(p.ref&&ho(p.ref,null,E),h.push(E.ref,E.__c||g,E)),f==null&&g!=null&&(f=g),(m=!!(4&E.__u))||p.__k===E.__k?(c=Ms(E,c,e,m),m&&p.__e&&(p.__e=null)):typeof E.type=="function"&&S!==void 0?c=S:g&&(c=g.nextSibling),E.__u&=-7);return n.__e=f,c}function Qc(e,t,n,r,o){var i,s,a,c,d,h=n.length,u=h,p=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=Dn(null,s,null,null,null):Pn(s)?s=e.__k[i]=Dn(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Dn(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=ed(s,n,c,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=c&&(d==c-1?p--:d==c+1?p++:(d>c?p--:p++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=an(a)),Fs(a,a));return r}function Ms(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Ms(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=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 Tt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Pn(e)?e.some(function(n){Tt(n,t)}):t.push(e)),t}function ed(e,t,n,r){var o,i,s,a=e.key,c=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&c==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&c==d.type)return s}return-1}function Ps(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Zc.test(t)?n:n+"px"}function xr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ps(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ps(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ks,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Mn]=r[Mn]:(n[Mn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ds(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[br]==null)t[br]=oo++;else if(t[br]<n[Mn])return;return n(Q.event?Q.event(t):t)}}}function co(e,t,n,r,o,i,s,a,c,d){var h,u,p,E,g,f,S,m,_,y,k,x,w,T,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=Q.__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 lt(m,k),u.constructor=b,u.render=nd),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&b.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=yt({},u.__s)),yt(u.__s,b.getDerivedStateFromProps(m,u.__s))),E=u.props,g=u.state,u.__v=t,p)_&&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(C){C&&(C.__=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,k),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,g,f)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=Q.__r,w=0,_)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),Nr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++w<25);u.state=u.__s,u.getChildContext!=null&&(r=yt(yt({},r),u.getChildContext())),_&&!p&&u.getSnapshotBeforeUpdate!=null&&(f=u.getSnapshotBeforeUpdate(E,g)),T=h!=null&&h.type===me&&h.key==null?Us(h.props.children):h,a=Is(e,Pn(T)?T:[T],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),S&&(u.__E=u.__=null)}catch(C){if(t.__v=null,c||i!=null)if(C.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(v=i.length;v--;)ao(i[v]);uo(t)}else t.__e=n.__e,t.__k=n.__k,C.then||uo(t);Q.__e(C,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=td(n.__e,t,n,r,o,i,s,c,d);return(h=Q.diffed)&&h(t),128&t.__u?void 0:a}function uo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(uo))}function Ls(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);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 Us(e){return typeof e!="object"||e==null||e.__b>0?e:Pn(e)?e.map(Us):e.constructor!==void 0?null:yt({},e)}function td(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&&In.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||xr(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||xr(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=""),Is(t.type=="template"?e.content:e,Pn(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--;)ao(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||_=="progress"&&!g||_=="option"&&g!=S[d])&&xr(e,d,g,S[d],o),d="checked",f!=null&&f!=e[d]&&xr(e,d,f,S[d],o))}return e}function ho(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){Q.__e(o,n)}}function Fs(e,t,n){var r,o;if(Q.unmount&&Q.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ho(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Q.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function nd(e,t,n){return this.constructor(e,n)}function Ln(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=[],co(t,e=(!r&&n||t).__k=tt(me,null,[e]),o||wr,wr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?In.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Ls(i,e,s)}function Vs(e,t){Ln(e,t,Vs)}function rd(e,t,n){var r,o,i,s,a=yt({},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?In.call(arguments,2):n),Dn(e.type,a,r||e.key,o||e.ref,null)}function St(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,lo(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Os++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}In=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}},Ns=0,lt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=yt({},this.state),typeof e=="function"&&(e=e(yt({},n),this.props)),e&&yt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),lo(this))},lt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},lt.prototype.render=me,Pt=[],xs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ts=function(e,t){return e.__v.__b-t.__v.__b},Cr.__r=0,ro=Math.random().toString(8),br="__d"+ro,Mn="__a"+ro,ks=/(PointerCapture)$|Capture$/i,oo=0,so=Ds(!1),io=Ds(!0),Os=0;var od=0;function l(e,t,n,r,o,i){t||(t={});var s,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?s=t[a]:c[a]=t[a];var d={type:e,props:c,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--od,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)c[a]===void 0&&(c[a]=s[a]);return Q.vnode&&Q.vnode(d),d}var kt,fe,mo,js,ln=0,zs=[],Ce=Q,Ys=Ce.__b,Hs=Ce.__r,$s=Ce.diffed,Bs=Ce.__c,Gs=Ce.unmount,Ws=Ce.__;function Gt(e,t){Ce.__h&&Ce.__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(qs,e)}function cn(e,t,n){var r=Gt(kt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):qs(void 0,t),function(a){var c=r.__N?r.__N[0]:r.__[0],d=r.t(c,a);c!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=fe,!fe.__f)){var o=function(a,c,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,c,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var E=p.__[0];p.__=p.__N,p.__N=void 0,E!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,c,d)||u};fe.__f=!0;var i=fe.shouldComponentUpdate,s=fe.componentWillUpdate;fe.componentWillUpdate=function(a,c,d){if(this.__e){var h=i;i=void 0,o(a,c,d),i=h}s&&s.call(this,a,c,d)},fe.shouldComponentUpdate=o}return r.__N||r.__}function $(e,t){var n=Gt(kt++,3);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__H.__h.push(n))}function mt(e,t){var n=Gt(kt++,4);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,fe.__h.push(n))}function X(e){return ln=5,ae(function(){return{current:e}},[])}function po(e,t,n){ln=6,mt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ae(e,t){var n=Gt(kt++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ue(e,t){return ln=8,ae(function(){return e},t)}function vt(e){var t=fe.context[e.__c],n=Gt(kt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(fe)),t.props.value):e.__}function fo(e,t){Ce.useDebugValue&&Ce.useDebugValue(t?t(e):e)}function sd(e){var t=Gt(kt++,10),n=V();return t.__=e,fe.componentDidCatch||(fe.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=Gt(kt++,11);if(!e.__){for(var t=fe.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function id(){for(var e;e=zs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Tr),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],Ce.__e(n,e.__v)}}}Ce.__b=function(e){fe=null,Ys&&Ys(e)},Ce.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ws&&Ws(e,t)},Ce.__r=function(e){Hs&&Hs(e),kt=0;var t=(fe=e.__c).__H;t&&(mo===fe?(t.__h=[],fe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Tr),t.__h.some(_o),t.__h=[],kt=0)),mo=fe},Ce.diffed=function(e){$s&&$s(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(zs.push(t)!==1&&js===Ce.requestAnimationFrame||((js=Ce.requestAnimationFrame)||ad)(id)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=fe=null},Ce.__c=function(e,t){t.some(function(n){try{n.__h.some(Tr),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],Ce.__e(r,n.__v)}}),Bs&&Bs(e,t)},Ce.unmount=function(e){Gs&&Gs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Tr(r)}catch(o){t=o}}),n.__H=void 0,t&&Ce.__e(t,n.__v))};var Ks=typeof requestAnimationFrame=="function";function ad(e){var t,n=function(){clearTimeout(r),Ks&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ks&&(t=requestAnimationFrame(n))}function Tr(e){var t=fe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),fe=t}function _o(e){var t=fe;e.__c=e.__(),fe=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function qs(e,t){return typeof t=="function"?t(e):t}function Xs(e,t){for(var n in t)e[n]=t[n];return e}function yo(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function So(e,t){var n=t(),r=V({t:{__:n,u:t}}),o=r[0].t,i=r[1];return mt(function(){o.__=n,o.u=t,vo(o)&&i({t:o})},[e,n,t]),$(function(){return vo(o)&&i({t:o}),e(function(){vo(o)&&i({t:o})})},[e]),n}function vo(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 bo(e){e()}function wo(e){return e}function No(){return[!1,bo]}var Co=mt;function kr(e,t){this.props=e,this.context=t}function Wt(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,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 yo(this.props,e)||yo(this.state,t)};var Zs=Q.__b;Q.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Zs&&Zs(e)};var ld=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function te(e){function t(n){var r=Xs({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=ld,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Js=function(e,t){return e==null?null:Tt(Tt(e).map(t))},ot={map:Js,forEach:Js,count:function(e){return e?Tt(e).length:0},only:function(e){var t=Tt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Tt},cd=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)}cd(e,t,n,r)};var Qs=Q.unmount;function ei(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Xs({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return ei(r,t,n)})),e}function ti(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ti(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function Xe(){this.__u=0,this.o=null,this.__b=null}function ni(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function 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),Qs&&Qs(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=ni(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(c):c())};n.__R=s;var a=n.__P;n.__P=null;var c=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ti(d,d.__c.__P,d.__c.__O)}var h;for(r.setState({__a:r.__b=null});h=r.o.pop();)h.__P=a,h.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},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]=ei(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 ri=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function dd(e){return this.getChildContext=function(){return e.context},e.children}function ud(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ln(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)}}}Ln(tt(dd,{context:t.context},e.__v),t.v)}function oi(e,t){var n=tt(ud,{__v:e,h:t});return n.containerInfo=t,n}(dn.prototype=new lt).__a=function(e){var t=this,n=ni(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),ri(t,e,r)):o()};n?n(i):i()}},dn.prototype.render=function(e){this.i=null,this.l=new Map;var t=Tt(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){ri(e,n,t)})};var si=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,hd=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,md=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,pd=/[A-Z0-9]/g,fd=typeof document<"u",gd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Ln(e,t),typeof n=="function"&&n(),e?e.__c:null}function ii(e,t,n){return Vs(e,t),typeof n=="function"&&n(),e?e.__c:null}lt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(lt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ai=Q.event;Q.event=function(e){return ai&&(e=ai(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var To,_d={configurable:!0,get:function(){return this.class}},li=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||fd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||gd(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":md.test(s)&&(s=c):c=s="oninput":i&&hd.test(s)?s=s.replace(pd,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&o[s=c]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=Tt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=Tt(n.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",_d)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=si,li&&li(e)};var ci=Q.__r;Q.__r=function(e){ci&&ci(e),To=e.__c};var di=Q.diffed;Q.diffed=function(e){di&&di(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),To=null};var ui={ReactCurrentDispatcher:{current:{readContext:function(e){return To.__n[e.__c].props.value},useCallback:ue,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:$,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:cn,useRef:X,useState:V,useSyncExternalStore:So,useTransition:No}}},Ed="18.3.1";function hi(e){return tt.bind(null,e)}function st(e){return!!e&&e.$$typeof===si}function mi(e){return st(e)&&e.type===me}function pi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Dt(e){return st(e)?rd.apply(null,arguments):e}function ko(e){return!!e.__k&&(Ln(null,e),!0)}function fi(e){return e&&(e.base||e.nodeType===1&&e)||null}var gi=function(e,t){return e(t)},_i=function(e,t){var n=Q.debounceRendering;Q.debounceRendering=function(o){return o()};var r=e(t);return Q.debounceRendering=n,r},Ei=st,Un={useState:V,useId:go,useReducer:cn,useEffect:$,useLayoutEffect:mt,useInsertionEffect:Co,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:bo,useRef:X,useImperativeHandle:po,useMemo:ae,useCallback:ue,useContext:vt,useDebugValue:fo,version:"18.3.1",Children:ot,render:xo,hydrate:ii,unmountComponentAtNode:ko,createPortal:oi,createElement:tt,createContext:St,createFactory:hi,cloneElement:Dt,createRef:Rs,Fragment:me,isValidElement:st,isElement:Ei,isFragment:mi,isMemo:pi,findDOMNode:fi,Component:lt,PureComponent:kr,memo:Wt,forwardRef:te,flushSync:_i,unstable_batchedUpdates:gi,StrictMode:me,Suspense:Xe,SuspenseList:dn,lazy:nt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:ot,Component:lt,Fragment:me,PureComponent:kr,StrictMode:me,Suspense:Xe,SuspenseList:dn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ui,cloneElement:Dt,createContext:St,createElement:tt,createFactory:hi,createPortal:oi,createRef:Rs,default:Un,findDOMNode:fi,flushSync:_i,forwardRef:te,hydrate:ii,isElement:Ei,isFragment:mi,isMemo:pi,isValidElement:st,lazy:nt,memo:Wt,render:xo,startTransition:bo,unmountComponentAtNode:ko,unstable_batchedUpdates:gi,useCallback:ue,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:$,useErrorBoundary:sd,useId:go,useImperativeHandle:po,useInsertionEffect:Co,useLayoutEffect:mt,useMemo:ae,useReducer:cn,useRef:X,useState:V,useSyncExternalStore:So,useTransition:No,version:Ed},Symbol.toStringTag,{value:"Module"}));function yd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function yi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ro(...e){return t=>{let n=!1;const r=e.map(o=>{const i=yi(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():yi(e[o],null)}}}}function Lt(...e){return ue(Ro(...e),e)}function Sd(e){const t=vd(e),n=te((r,o)=>{const{children:i,...s}=r,a=ot.toArray(i),c=a.find(wd);if(c){const d=c.props.children,h=a.map(u=>u===c?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:st(d)?Dt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function vd(e){const t=te((n,r)=>{const{children:o,...i}=n;if(st(o)){const s=Cd(o),a=Nd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Dt(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var bd=Symbol("radix.slottable");function wd(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===bd}function Nd(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Cd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var xd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],un=xd.reduce((e,t)=>{const n=Sd(`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}},{}),Kt=globalThis?.document?mt:()=>{};function Td(e,t){return cn((n,r)=>t[n][r]??n,e)}var hn=e=>{const{present:t,children:n}=e,r=kd(t),o=typeof n=="function"?n({present:r.isPresent}):ot.only(n),i=Lt(r.ref,Od(o));return typeof n=="function"||r.isPresent?Dt(o,{ref:i}):null};hn.displayName="Presence";function kd(e){const[t,n]=V(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,c]=Td(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return $(()=>{const d=Or(r.current);i.current=a==="mounted"?d:"none"},[a]),Kt(()=>{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]),Kt(()=>{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 Od(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Si(e,t=[]){let n=[];function r(i,s){const a=St(s),c=n.length;n=[...n,s];const d=u=>{const{scope:p,children:E,...g}=u,f=p?.[e]?.[c]||a,S=ae(()=>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=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>St(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Rd(o,...t)]}function Rd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Ut(e){const t=X(e);return $(()=>{t.current=e}),ae(()=>(...n)=>t.current?.(...n),[])}var Ad=St(void 0);function Id(e){const t=vt(Ad);return e||t||"ltr"}function Md(e,[t,n]){return Math.min(n,Math.max(t,e))}function Ft(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Pd(e,t){return cn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[vi]=Si(Ao),[Dd,ct]=vi(Ao),bi=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,k]=V(0),[x,w]=V(!1),[T,v]=V(!1),b=Lt(t,D=>c(D)),C=Id(o);return l(Dd,{scope:n,type:r,dir:C,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:E,onScrollbarXChange:g,scrollbarXEnabled:x,onScrollbarXEnabledChange:w,scrollbarY:f,onScrollbarYChange:S,scrollbarYEnabled:T,onScrollbarYEnabledChange:v,onCornerWidthChange:_,onCornerHeightChange:k,children:l(un.div,{dir:C,...s,ref:b,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});bi.displayName=Ao;var wi="ScrollAreaViewport",Ni=te((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ct(wi,n),a=X(null),c=Lt(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})})]})});Ni.displayName=wi;var bt="ScrollAreaScrollbar",Io=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(bt,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(Ld,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(Ud,{...r,ref:t,forceMount:n}):o.type==="auto"?l(Ci,{...r,ref:t,forceMount:n}):o.type==="always"?l(Mo,{...r,ref:t}):null});Io.displayName=bt;var Ld=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(bt,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(Ci,{"data-state":i?"visible":"hidden",...r,ref:t})})}),Ud=te((e,t)=>{const{forceMount:n,...r}=e,o=ct(bt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Mr(()=>c("SCROLL_END"),100),[a,c]=Pd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return $(()=>{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(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ft(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Ft(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Ci=te((e,t)=>{const n=ct(bt,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(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=te((e,t)=>{const{orientation:n="vertical",...r}=e,o=ct(bt,e.__scopeScrollArea),i=X(null),s=X(0),[a,c]=V({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ri(a.viewport,a.content),h={...r,sizes:a,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,E){return Hd(p,s.current,a,E)}return n==="horizontal"?l(Fd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,E=Ai(p,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?l(Vd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,E=Ai(p,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Fd=te((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(bt,e.__scopeScrollArea),[s,a]=V(),c=X(null),d=Lt(t,c,i.onScrollbarXChange);return $(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ti,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":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),Mi(p,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ar(s.paddingLeft),paddingEnd:Ar(s.paddingRight)}})}})}),Vd=te((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(bt,e.__scopeScrollArea),[s,a]=V(),c=X(null),d=Lt(t,c,i.onScrollbarYChange);return $(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Ti,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":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),Mi(p,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ar(s.paddingTop),paddingEnd:Ar(s.paddingBottom)}})}})}),[jd,xi]=vi(bt),Ti=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(bt,n),[g,f]=V(null),S=Lt(t,b=>f(b)),m=X(null),_=X(""),y=E.viewport,k=r.content-r.viewport,x=Ut(h),w=Ut(c),T=Mr(u,10);function v(b){if(m.current){const C=b.clientX-m.current.left,D=b.clientY-m.current.top;d({x:C,y:D})}}return $(()=>{const b=C=>{const D=C.target;g?.contains(D)&&x(C,k)};return document.addEventListener("wheel",b,{passive:!1}),()=>document.removeEventListener("wheel",b,{passive:!1})},[y,g,k,x]),$(w,[r,w]),mn(g,T),mn(E.content,T),l(jd,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Ut(i),onThumbPointerUp:Ut(s),onThumbPositionChange:w,onThumbPointerDown:Ut(a),children:l(un.div,{...p,ref:S,style:{position:"absolute",...p.style},onPointerDown:Ft(e.onPointerDown,b=>{b.button===0&&(b.target.setPointerCapture(b.pointerId),m.current=g.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),v(b))}),onPointerMove:Ft(e.onPointerMove,v),onPointerUp:Ft(e.onPointerUp,b=>{const C=b.target;C.hasPointerCapture(b.pointerId)&&C.releasePointerCapture(b.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Rr="ScrollAreaThumb",ki=te((e,t)=>{const{forceMount:n,...r}=e,o=xi(Rr,e.__scopeScrollArea);return l(hn,{present:n||o.hasThumb,children:l(zd,{ref:t,...r})})}),zd=te((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ct(Rr,n),s=xi(Rr,n),{onThumbPositionChange:a}=s,c=Lt(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=$d(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:Ft(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:Ft(e.onPointerUp,s.onThumbPointerUp)})});ki.displayName=Rr;var Po="ScrollAreaCorner",Oi=te((e,t)=>{const n=ct(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(Yd,{...e,ref:t}):null});Oi.displayName=Po;var Yd=te((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ct(Po,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 Ar(e){return e?parseInt(e,10):0}function Ri(e,t){const n=e/t;return isNaN(n)?0:n}function Ir(e){const t=Ri(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Hd(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 Ii([c,d],u)(e)}function Ai(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=Md(e,c);return Ii([0,s],[0,a])(d)}function Ii(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mi(e,t){return e>0&&e<t}var $d=(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=Ut(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=Ut(t);Kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Pi=bi,Bd=Ni,Gd=Oi;function Wd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var pn={},Fn={},Di={},Vn={},jn={},zn={},Li;function Do(){if(Li)return zn;Li=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.EventEmitter=void 0;let e=class{constructor(){R(this,"eventListeners",new Map)}on(t,n){const r=this.eventListeners.get(t)||new Set;r.add(n),this.eventListeners.set(t,r)}off(t,n){const r=this.eventListeners.get(t);r&&(r.delete(n),r.size===0&&this.eventListeners.delete(t))}emit(t,...n){const r=this.eventListeners.get(t);r&&r.forEach(o=>o(...n))}removeAllListeners(){this.eventListeners.clear()}};return zn.EventEmitter=e,zn}var fn={},Ui;function Yn(){return Ui||(Ui=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 Fi;function Lo(){if(Fi)return jn;Fi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.BaseConnection=void 0;const e=Do(),t=Yn();let n=class{constructor(){R(this,"status",t.ConnectionStatus.CONNECTING);R(this,"queue",[]);R(this,"eventEmitter",new e.EventEmitter);R(this,"disconnectionDetails",null);R(this,"onErrorCallback",null);R(this,"onDisconnectCallback",null);R(this,"onMessageCallback",null);R(this,"onOpenCallback",null);R(this,"onStatusChangeCallback",null)}getStatus(){return this.status}onOpen(r){this.onOpenCallback=r}onMessage(r){if(this.onMessageCallback=r,this.queue.length>0){const o=[...this.queue];this.queue.length=0,queueMicrotask(()=>{o.forEach(i=>{this.onMessageCallback?.(i)})})}}onDisconnect(r){this.onDisconnectCallback=r;const o=this.disconnectionDetails;o&&queueMicrotask(()=>{this.onDisconnectCallback?.(o)})}onError(r){this.onErrorCallback=r}on(r,o){this.eventEmitter.on(r,o)}off(r,o){this.eventEmitter.off(r,o)}emit(r,...o){this.eventEmitter.emit(r,...o)}onStatusChange(r){this.onStatusChangeCallback=r,queueMicrotask(()=>{r(this.status)})}disconnect(r){this.disconnectionDetails||(this.disconnectionDetails=r,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.onDisconnectCallback?.(r))}handleMessage(r){this.onMessageCallback?this.onMessageCallback(r):this.queue.push(r)}updateStatus(r){this.status!==r&&(this.status=r,this.onStatusChangeCallback?.(r))}};return jn.BaseConnection=n,jn}var Vi={},ji;function it(){return ji||(ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=x,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(v,b=e.SynapseErrorCode.UNKNOWN,C={}){super(v);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=b,this.timestamp=new Date,this.cause=C.cause,this.context=C.context,this.hint=C.hint,this.reason=C.reason,this.displayMessage=C.displayMessage||C?.hint||v,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(v,b,C,D){const W=n.makeMessage(b,C,v);super(W,e.SynapseErrorCode.API,{cause:C,context:{status:b,hasBody:!!C},hint:b&&b>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:v||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=b,this.error=C,this.headers=D}static makeMessage(v,b,C){const D=b instanceof Error?b.message:C;return v&&D?`HTTP ${v}: ${D}`:v?`${v} status code (no body)`:D||"(no status code or body)"}static generate(v,b,C,D){if(!v)return new r({message:C});const W=b?.error,G=W&&typeof W=="object"&&!Array.isArray(W)?W:void 0;switch(v){case 400:return new i(C||"Bad Request",v,G,D);case 401:return new s(C||"Unauthorized",v,G,D);case 403:return new a(C||"Permission Denied",v,G,D);case 404:return new c(C||"Not Found",v,G,D);case 405:return new d(C||"Method Not Allowed",v,G,D);case 429:return new h(C||"Rate Limit Exceeded",v,G,D);case 500:return new u(C||"Internal Server Error",v,G,D);default:return new n(C||"API Error",v,G,D)}}}e.APIError=n;class r extends n{constructor({message:T}={}){super(T||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:T}={}){super(T||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(T,v,b,C){super(T,v,b,C),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.CONNECTION,v),this.name="ConnectionError"}}e.ConnectionError=p;class E extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.RECORDING,v),this.name="RecordingError"}}e.RecordingError=E;class g extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.AUTH,v),this.name="AuthenticationError"}}e.AuthenticationError=g;class f extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.FILE,v),this.name="FileError"}}e.FileError=f;class S extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.SESSION,v),this.name="SessionError"}}e.SessionError=S;class m extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.MESSAGE,v),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.STORE,v),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.CONFIGURATION,v),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(T,v={}){super(T,e.SynapseErrorCode.VALIDATION,v),this.name="ValidationError"}}e.ValidationError=k;function x(w,T,v,b={}){if(w instanceof T)return w;const C={...b,context:{...w instanceof t?w.context:void 0,...b.context},hint:b.hint??(w instanceof t?w.hint:void 0),reason:b.reason??(w instanceof t?w.reason:void 0),cause:b.cause??w};if(w instanceof t)return new T(w.message,C);const D=w instanceof Error&&w.message?w.message:v;return new T(D,C)}})(Vi)),Vi}var zi;function Yi(){if(zi)return Vn;zi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.WebSocketConnection=void 0;const e=Lo(),t=Yn(),n=it();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const c=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(c)}}handleError(s){}handleClose(s){const a=s.wasClean,c=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(c===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):c===1001||c===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):c===4001||c===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):c===4401||c===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(c===4401?"Session token expired":"Session credentials rejected")):c===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):c===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:c,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const c=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(c),c}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return Vn.WebSocketConnection=r,Vn}var Hn={},Hi={},$i;function Bi(){return $i||($i=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})(Hi)),Hi}var Gi;function Wi(){if(Gi)return Hn;Gi=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.SSEConnection=void 0;const e=Lo(),t=Yn(),n=Bi(),r=it();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const c=new AbortController;this.activeStreamController=c,this.streamChat(a,c)}postChat(a,c,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(c),signal:d.signal})}async streamChat(a,c){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,c);if(h.status===401&&this.config.auth.onUnauthorized){const g=await this.config.auth.onUnauthorized();if(c.signal.aborted)return;g&&(h=await this.postChat(d,a,c))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),p=new TextDecoder;let E="";for(;;){const{done:g,value:f}=await u.read();if(g)break;E+=p.decode(f,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(c.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===c&&(this.activeStreamController=null)}}extractJsonObjects(a){let c=0;for(;c<a.length;){const d=a.indexOf("{",c);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const p=JSON.parse(u);this.handleMessage(p)}catch(p){const E=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(E)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let p=c;p<a.length;p++){const E=a[p];if(h){u?u=!1:E==="\\"?u=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")d++;else if(E==="}"&&(d--,d===0))return p}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Hn.SSEConnection=o,Hn}var Ki;function qi(){return Ki||(Ki=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Yi(),n=Wi(),r=it();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(Di)),Di}var $n={},Xi;function Uo(){if(Xi)return $n;Xi=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.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 $n.getConfig=r,$n}var Bn={},Gn={},Zi;function Pr(){if(Zi)return Gn;Zi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.HttpClient=void 0;const e=it();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const c=this.buildUrl(r,o?.params),d=await fetch(c,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(c){if(s=c,a===i||!(c instanceof TypeError&&c.message==="Failed to fetch"||c instanceof DOMException&&c.name==="AbortError"||c instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Gn.HttpClient=t,Gn}var Wn={},Kn={},Ji;function qn(){if(Ji)return Kn;Ji=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.BaseResource=void 0;let e=class{constructor(t){R(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return Kn.BaseResource=e,Kn}var Qi;function ea(){if(Qi)return Wn;Qi=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.Session=void 0;const e=qn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:c}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...c&&{nps_base5:c}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return Wn.Session=t,Wn}var Xn={},ta;function Fo(){if(ta)return Xn;ta=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.Config=void 0;const e=qn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return Xn.Config=t,Xn}var na={},ra;function oa(){return ra||(ra=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Pr(),n=Uo(),r=Fo(),o=new Map,i=(c,d)=>`${c.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(c){const d=c.serverUrl||(0,n.getConfig)(c.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,c.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":c.agentId,...c.channel&&{"x-channel":c.channel}}}),E=new r.Config(p).retrieve(c.agentId);return E.catch(()=>{o.get(h)===E&&o.delete(h)}),o.set(h,E),E}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(na)),na}var Zn={},sa;function Vo(){if(sa)return Zn;sa=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.Auth=void 0;const e=qn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Zn.Auth=t,Zn}var Jn={},gn={},ia;function jo(){return ia||(ia=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 Qn={},aa;function zo(){if(aa)return Qn;aa=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.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 Qn.ErrorUtils=t,Qn}var la={},ca;function da(){return ca||(ca=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=Pr(),n=Uo(),r=zo(),o=Vo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),p=i.get(u);if(p)return p;const E=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),g=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return g.catch(f=>{r.ErrorUtils.isAuthError(f)||i.get(u)===g&&i.delete(u)}),i.set(u,g),g}function c(d){const h=i.get(d);return h&&i.delete(d),h}})(la)),la}var ua;function Kd(){if(ua)return Jn;ua=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.TokenManager=void 0;const e=it(),t=jo(),n=zo(),r=da();let o=class{constructor(i,s,a,c){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=c.partnerAuthToken,this.refreshToken=c.refreshToken,this.onTokenExchange=c.onTokenExchange,this._level=c.level,this._userId=c.userId,c.sessToken&&(this.sessToken=c.sessToken,this.httpClient.setAuthorization(c.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(c.serverUrl,a,c.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,c){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,c,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return Jn.TokenManager=o,Jn}var er={},ha;function qd(){var n;if(ha)return er;ha=1,Object.defineProperty(er,"__esModule",{value:!0}),er.VoiceResource=void 0;const e=qn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return er.VoiceResource=t,er}var ma;function pa(){if(ma)return Bn;ma=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.ResourceManager=void 0;const e=Pr(),t=ea(),n=it(),r=Fo(),o=oa(),i=Vo(),s=Kd(),a=qd();class c{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:p,intent:E,user_location:g,referer:f,...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 Bn.ResourceManager=c,Bn}var tr={},fa={},ga;function Yo(){return ga||(ga=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MULTI_SELECT_ADDITIONAL_OPTION=e.SOCKET_EVENTS=e.SOCKET_CONTENT_TYPES=void 0,e.IsValidSocketMesssage=t,e.SOCKET_CONTENT_TYPES={TEXT:"text",AUDIO:"audio",FILE:"file",TOOL_CALL:"tool",TIPS:"tips",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},e.SOCKET_EVENTS={PING:"ping",PONG:"pong",CHAT:"chat",STREAM:"stream",AUTH:"auth",END_OF_STREAM:"eos",SYNC:"sync",ERROR:"err",CONNECTION_ESTABLISHED:"conn"},e.MULTI_SELECT_ADDITIONAL_OPTION={NOTA:"none_of_the_above",AOTA:"all_of_the_above"};function t(n){return[e.SOCKET_EVENTS.PING,e.SOCKET_EVENTS.PONG,e.SOCKET_EVENTS.ERROR,e.SOCKET_EVENTS.SYNC,e.SOCKET_EVENTS.CONNECTION_ESTABLISHED,e.SOCKET_EVENTS.CHAT,e.SOCKET_EVENTS.STREAM,e.SOCKET_EVENTS.END_OF_STREAM].includes(n.ev)}})(fa)),fa}var _a={},Ea;function Xd(){return Ea||(Ea=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=it();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.filter(a=>a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const c=s[a].url,d=await fetch(c,{method:"PUT",body:this.pendingFiles[a],headers:{"Content-Type":this.pendingFiles[a].type,"x-ms-blob-type":"BlockBlob"}});if(!d.ok)throw new t.FileError(`Failed to upload ${this.pendingFiles[a].name} to URL ${a+1}: ${d.status} ${d.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(s[a].id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[]}}e.Filemanager=n})(_a)),_a}var pt={},ya;function Dr(){if(ya)return pt;ya=1,Object.defineProperty(pt,"__esModule",{value:!0}),pt.SYNAPSE_REALTIME_RESERVED_EVENTS=pt.SYNAPSE_REALTIME_ERROR_CODES=pt.SYNAPSE_REALTIME_EVENTS=pt.SYNAPSE_MESSAGE_TYPES=void 0;const e=Yo();return pt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,pt.SYNAPSE_REALTIME_EVENTS={CONNECTED:"connected",DISCONNECTED:"disconnected",PROGRESS_MESSAGE:"progress_message",MESSAGE_CHUNK:"message_chunk",TIPS_MESSAGE:"tips_message",END_OF_STREAM:"end_of_stream",ERROR:"error",TOOL_CALL:"tool_call",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},pt.SYNAPSE_REALTIME_ERROR_CODES={SESSION_INACTIVE:"session_not_found",SESSION_TOKEN_EXPIRED:"sess_token_expired",INVALID_EVENT:"invalid_event",INVALID_CONTENT_TYPE:"invalid_content",PARSING_ERROR:"parsing",FILE_UPLOAD_INPROGRESS:"file_upload_inprogress",TIMEOUT:"timeout",SERVER_ERROR:"server_error",SESSION_TOKEN_MISMATCH:"session_token_mismatch",PROMPT_FETCH_ERROR:"prompt_fetch_error",INVALID_FILE_REQUEST:"invalid_file_request",SESSION_NOT_OWNED:"session_not_owned"},pt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},pt}var nr={},Sa;function Zd(){if(Sa)return nr;Sa=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.AudioManager=void 0;const e=it();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return nr.AudioManager=t,nr}var va;function ba(){if(va)return tr;va=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.MessageManager=void 0;const e=Yo(),t=Xd(),n=Dr(),r=Zd(),o=it();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:c,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(c&&c.length>0){const p=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:c,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:c,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...c&&{audio:c},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},...E&&{initial_prompts:E}};return}const g=this.connection;let f;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const 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 tr.MessageManager=i,tr}var wa={},Na;function Jd(){return Na||(Na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.outcomeForHttpStatus=e.outcomeForCloseCode=e.RECOVERY_OUTCOME=void 0,e.RECOVERY_OUTCOME={REFRESH_AND_RETRY:"refresh_and_retry",FORBIDDEN:"forbidden",SESSION_GONE:"session_gone",RETRY_LATER:"retry_later",SESSION_NOT_OWNED:"session_not_owned"};const t={4401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,4403:e.RECOVERY_OUTCOME.FORBIDDEN,4404:e.RECOVERY_OUTCOME.SESSION_GONE,1013:e.RECOVERY_OUTCOME.RETRY_LATER},n={401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,403:e.RECOVERY_OUTCOME.FORBIDDEN,404:e.RECOVERY_OUTCOME.SESSION_GONE,429:e.RECOVERY_OUTCOME.RETRY_LATER,503:e.RECOVERY_OUTCOME.RETRY_LATER},r=i=>i===void 0?void 0:t[i];e.outcomeForCloseCode=r;const o=i=>i===void 0?void 0:n[i];e.outcomeForHttpStatus=o})(wa)),wa}var rr={},or={},Ca;function Qd(){if(Ca)return or;Ca=1,Object.defineProperty(or,"__esModule",{value:!0}),or.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),c=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(c)};c()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return or.VoiceAudioAnalyser=t,or}var _n={},xa;function Ta(){return xa||(xa=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 ka;function eu(){if(ka)return rr;ka=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.VoiceAgent=void 0;const e=Do(),t=Qd(),n=it(),r=Ta(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const E=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),p())}})}let d=class{constructor(h,u,p){R(this,"config");R(this,"resourceManager");R(this,"getCredentials");R(this,"emitter",new e.EventEmitter);R(this,"remoteAnalyser",new t.VoiceAudioAnalyser);R(this,"localAnalyser",new t.VoiceAudioAnalyser);R(this,"pc",null);R(this,"pcId",null);R(this,"dataChannel",null);R(this,"localStream",null);R(this,"remoteAudio",null);R(this,"_state",r.VOICE_AGENT_STATE.IDLE);R(this,"_isMuted",!1);R(this,"manuallyDisconnected",!1);R(this,"_hasConnectionFailureNotified",!1);R(this,"_userSpeaking",!1);R(this,"_silenceTimer",null);R(this,"_cachedIceServers",null);R(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=p}get state(){return this._state}get isMuted(){return this._isMuted}on(h,u){this.emitter.on(h,u)}off(h,u){this.emitter.off(h,u)}async connect(){const h=await this.getCredentials();this.setState(r.VOICE_AGENT_STATE.CONNECTING),this._hasConnectionFailureNotified=!1;try{if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available. Please ensure you are using a secure (HTTPS) connection.");const u=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=u;const p=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:p,iceTransportPolicy:"all"});this.pc=E,this.dataChannel=E.createDataChannel("pipecat-events",{ordered:!0}),this.dataChannel.onopen=()=>{},this.dataChannel.onclose=()=>this.handleConnectionFailure(new Error("Data channel closed"),"Voice connection failed"),this.dataChannel.onerror=()=>this.handleConnectionFailure(new Error("Data channel error"),"Voice connection failed"),u.getAudioTracks().forEach(_=>E.addTrack(_,u)),E.ontrack=_=>this.handleRemoteTrack(_),E.onconnectionstatechange=()=>{E.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(E.connectionState==="failed"||E.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},E.oniceconnectionstatechange=()=>{(E.iceConnectionState==="connected"||E.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):E.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const g=await E.createOffer();await E.setLocalDescription(g);const f=this.config.iceGatheringTimeoutMs??o;await c(E,f);const 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 rr.VoiceAgent=d,rr}var Oa;function tu(){if(Oa)return Fn;Oa=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.SynapseSDK=void 0;const e=qi(),t=Yn(),n=Uo(),r=pa(),o=ba(),i=Dr(),s=Do(),a=it(),c=jo(),d=Jd(),h=Yo(),u=eu();class p{constructor(g){R(this,"connection",null);R(this,"messageManager");R(this,"resourceManager");R(this,"sessionConfig",null);R(this,"config");R(this,"connectionType");R(this,"isRefreshingSession",!1);R(this,"isRecovering",!1);R(this,"forceConsumed",!1);R(this,"connectionAttempts",0);R(this,"sdkEventEmitter",new s.EventEmitter);R(this,"_voice",null);R(this,"pendingNetworkReconnect",!1);R(this,"boundOnlineHandler",null);R(this,"isReconnecting",!1);R(this,"reconnectTimer",null);R(this,"boundVisibilityHandler",null);R(this,"isSessionNotOwned",!1);this.config={...g,environment:g.environment||"production"},this.connectionType=g.connectionType||e.ConnectionType.HTTP_STREAM;const f=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||f,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange: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:k}){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},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(w){this.emitError(w)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(g,f,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=(k,...x)=>{y(k,...x),this.sdkEventEmitter.emit(k,...x)}}async createNewSession(){return await this.resourceManager.createSession(this.config.userId,this.config.context)}setupEventHandlers(){if(!this.connection)return;this.connection.onOpen(()=>{switch(this.connectionType){case e.ConnectionType.SOCKET:this.onSocketConnectionOpen();break;case e.ConnectionType.HTTP_STREAM:this.messageManager.handleConnectionEstablished();break}}),this.connection.onMessage(f=>{this.onIncomingSocketMessage(f)}),this.connection.onError(f=>{this.onRealtimeConnectionError(f)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const g=this.connection;this.connection.onDisconnect(async f=>{if(this.connection!==g||f.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const 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 Fn.SynapseSDK=p,Fn}var Ra={},Aa;function nu(){return Aa||(Aa=1,Object.defineProperty(Ra,"__esModule",{value:!0})),Ra}var Lr={},Ia;function ru(){return Ia||(Ia=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.USER_FEEDBACK=void 0,Lr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Lr}var Ma={},Pa;function ou(){return Pa||(Pa=1,Object.defineProperty(Ma,"__esModule",{value:!0})),Ma}var sr={},Da;function su(){if(Da)return sr;Da=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.ToolCall=void 0;const e=qn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return sr.ToolCall=t,sr}var Ze={},La;function iu(){if(La)return Ze;La=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 Ua={},Fa;function au(){return Fa||(Fa=1,Object.defineProperty(Ua,"__esModule",{value:!0})),Ua}var Va={},ja;function lu(){return ja||(ja=1,Object.defineProperty(Va,"__esModule",{value:!0})),Va}var ir={},za;function cu(){if(za)return ir;za=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(ir.SYNAPSE_CONVERSATION=e={})),ir}var En={},Ya;function du(){return Ya||(Ya=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(Ta(),e)})(En)),En}var Ha;function uu(){return Ha||(Ha=1,(function(e){var t=pn&&pn.__createBinding||(Object.create?(function(w,T,v,b){b===void 0&&(b=v);var C=Object.getOwnPropertyDescriptor(T,v);(!C||("get"in C?!T.__esModule:C.writable||C.configurable))&&(C={enumerable:!0,get:function(){return T[v]}}),Object.defineProperty(w,b,C)}):(function(w,T,v,b){b===void 0&&(b=v),w[b]=T[v]})),n=pn&&pn.__exportStar||function(w,T){for(var v in w)v!=="default"&&!Object.prototype.hasOwnProperty.call(T,v)&&t(T,w,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=tu();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Lo();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Yi();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Wi();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=qi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Yn(),e);var c=pa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(nu(),e);var d=ea();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(ru(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=da();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(ou(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var E=oa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var g=su();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return g.ToolCall}}),n(iu(),e);var f=ba();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return f.MessageManager}}),n(Dr(),e),n(au(),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 _=jo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return _.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return _.SYNAPSE_RECOVERY_REASON}});var y=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(lu(),e);var k=Bi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var x=Dr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(cu(),e),n(du(),e)})(pn)),pn}var A=uu();function $a(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=$a(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ba(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=$a(e))&&(r&&(r+=" "),r+=t);return r}const hu=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},mu=(e,t)=>({classGroupId:e,validator:t}),Ga=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Ur="-",Wa=[],pu="arbitrary..",fu=e=>{const t=_u(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return gu(o);const i=o.split(Ur),s=i[0]===""&&i.length>1?1:0;return Ka(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?hu(a,s):s:a||Wa}return n[o]||Wa}}},Ka=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=Ka(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(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}},gu=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?pu+r:void 0})(),_u=e=>{const{theme:t,classGroups:n}=e;return Eu(n,t)},Eu=(e,t)=>{const n=Ga();for(const r in e){const o=e[r];Ho(o,n,r,t)}return n},Ho=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];yu(s,t,n,r)}},yu=(e,t,n,r)=>{if(typeof e=="string"){Su(e,t,n);return}if(typeof e=="function"){vu(e,t,n,r);return}bu(e,t,n,r)},Su=(e,t,n)=>{const r=e===""?t:qa(t,e);r.classGroupId=n},vu=(e,t,n,r)=>{if(wu(e)){Ho(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(mu(n,e))},bu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];Ho(c,qa(t,a),n,r)}},qa=(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=Ga(),n.nextPart.set(s,a)),n=a}return n},wu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Nu=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},$o="!",Xa=":",Cu=[],Za=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),xu=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,c=0,d;const h=o.length;for(let f=0;f<h;f++){const S=o[f];if(s===0&&a===0){if(S===Xa){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($o)?(p=u.slice(0,-1),E=!0):u.startsWith($o)&&(p=u.slice(1),E=!0);const g=d&&d>c?d-c:void 0;return Za(i,E,p,g)};if(t){const o=t+Xa,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Za(Cu,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Tu=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",c=t.has(s);a||c?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},ku=e=>({cache:Nu(e.cacheSize),parseClassName:xu(e),sortModifiers:Tu(e),...fu(e)}),Ou=/\s+/,Ru=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Ou);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:E,baseClassName:g,maybePostfixModifierPosition:f}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let 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?_+$o:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,S);for(let w=0;w<x.length;++w){const T=x[w];s.push(y+T)}c=h+(c.length>0?" "+c:c)}return c},Au=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ja(n))&&(o&&(o+=" "),o+=r);return o},Ja=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ja(e[r]))&&(n&&(n+=" "),n+=t);return n},Iu=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=ku(d),r=n.cache.get,o=n.cache.set,i=a,a(c)},a=c=>{const d=r(c);if(d)return d;const h=Ru(c,n);return o(c,h),h};return i=s,(...c)=>i(Au(...c))},Mu=[],Ve=e=>{const t=n=>n[e]||Mu;return t.isThemeGetter=!0,t},Qa=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,el=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Pu=/^\d+\/\d+$/,Du=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Lu=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Uu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Fu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Vu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,yn=e=>Pu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Vt=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Ot=e=>Du.test(e),ju=()=>!0,zu=e=>Lu.test(e)&&!Uu.test(e),tl=()=>!1,Yu=e=>Fu.test(e),Hu=e=>Vu.test(e),$u=e=>!Y(e)&&!H(e),Bu=e=>Sn(e,il,tl),Y=e=>Qa.test(e),qt=e=>Sn(e,al,zu),Go=e=>Sn(e,Xu,ne),nl=e=>Sn(e,ol,tl),Gu=e=>Sn(e,sl,Hu),Fr=e=>Sn(e,ll,Yu),H=e=>el.test(e),ar=e=>vn(e,al),Wu=e=>vn(e,Zu),rl=e=>vn(e,ol),Ku=e=>vn(e,il),qu=e=>vn(e,sl),Vr=e=>vn(e,ll,!0),Sn=(e,t,n)=>{const r=Qa.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},vn=(e,t,n=!1)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n:!1},ol=e=>e==="position"||e==="percentage",sl=e=>e==="image"||e==="url",il=e=>e==="length"||e==="size"||e==="bg-size",al=e=>e==="length",Xu=e=>e==="number",Zu=e=>e==="family-name",ll=e=>e==="shadow",Ju=()=>{const e=Ve("color"),t=Ve("font"),n=Ve("text"),r=Ve("font-weight"),o=Ve("tracking"),i=Ve("leading"),s=Ve("breakpoint"),a=Ve("container"),c=Ve("spacing"),d=Ve("radius"),h=Ve("shadow"),u=Ve("inset-shadow"),p=Ve("text-shadow"),E=Ve("drop-shadow"),g=Ve("blur"),f=Ve("perspective"),S=Ve("aspect"),m=Ve("ease"),_=Ve("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),H,Y],w=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],v=()=>[H,Y,c],b=()=>[yn,"full","auto",...v()],C=()=>[Vt,"none","subgrid",H,Y],D=()=>["auto",{span:["full",Vt,H,Y]},Vt,H,Y],W=()=>[Vt,"auto",H,Y],G=()=>["auto","min","max","fr",H,Y],Ne=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...v()],_e=()=>[yn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],F=()=>[e,H,Y],ce=()=>[...k(),rl,nl,{position:[H,Y]}],Ae=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Ku,Bu,{size:[H,Y]}],Z=()=>[Bo,ar,qt],L=()=>["","none","full",d,H,Y],K=()=>["",ne,ar,qt],re=()=>["solid","dashed","dotted","double"],Te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[ne,Bo,rl,nl],Ie=()=>["","none",g,H,Y],He=()=>["none",ne,H,Y],ie=()=>["none",ne,H,Y],De=()=>[ne,H,Y],Le=()=>[yn,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ot],breakpoint:[Ot],color:[ju],container:[Ot],"drop-shadow":[Ot],ease:["in","out","in-out"],font:[$u],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ot],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ot],shadow:[Ot],spacing:["px",ne],text:[Ot],"text-shadow":[Ot],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:x()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset: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:[Vt,"auto",H,Y]}],basis:[{basis:[yn,"full","auto",a,...v()]}],"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:[Vt,"first","last","none",H,Y]}],"grid-cols":[{"grid-cols":C()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":C()}],"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:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...Ne(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...Ne()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":Ne()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],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:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"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,ar,qt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,H,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,Y]}],"font-family":[{font:[Wu,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,Go]}],leading:[{leading:[i,...v()]}],"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,qt]}],"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:v()}],"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:ce()}],"bg-repeat":[{bg:Ae()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Vt,H,Y],radial:["",H,Y],conic:[Vt,H,Y]},qu,Gu]}],"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,ar,qt]}],"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,qt]}],"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":[...Te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Te()}],"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":k()}],"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:ce()}],"mask-repeat":[{mask:Ae()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",H,Y]}],filter:[{filter:["","none",H,Y]}],blur:[{blur:Ie()}],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":Ie()}],"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":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",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":x()}],rotate:[{rotate:He()}],"rotate-x":[{"rotate-x":He()}],"rotate-y":[{"rotate-y":He()}],"rotate-z":[{"rotate-z":He()}],scale:[{scale:ie()}],"scale-x":[{"scale-x":ie()}],"scale-y":[{"scale-y":ie()}],"scale-z":[{"scale-z":ie()}],"scale-3d":["scale-3d"],skew:[{skew:De()}],"skew-x":[{"skew-x":De()}],"skew-y":[{"skew-y":De()}],transform:[{transform:[H,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Le()}],"translate-x":[{"translate-x":Le()}],"translate-y":[{"translate-y":Le()}],"translate-z":[{"translate-z":Le()}],"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":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",H,Y]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[ne,ar,qt,Go]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Qu=Iu(Ju);function P(...e){return Qu(Ba(e))}function Xt(e){if(!e&&e!==0)return"";const t=e instanceof Date?e:new Date(typeof e=="number"?e:Number(e)||e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}const eh=e=>{switch(e){case A.SYNAPSE_COMPONENTS.DOCTOR_CARD:case A.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},th=e=>new Promise(t=>setTimeout(t,e)),cl=te(({className:e,children:t,...n},r)=>l(Pi,{ref:r,className:P("relative overflow-hidden",e),...n,children:[l(Bd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(dl,{}),l(Gd,{})]}));cl.displayName=Pi.displayName;const dl=te(({className:e,orientation:t="vertical",...n},r)=>l(Io,{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(ki,{className:"relative flex-1 rounded-full bg-border"})}));dl.displayName=Io.displayName;var nh=Symbol.for("react.lazy"),jr=Oo[" use ".trim().toString()];function rh(e){return typeof e=="object"&&e!==null&&"then"in e}function ul(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===nh&&"_payload"in e&&rh(e._payload)}function hl(e){const t=sh(e),n=te((r,o)=>{let{children:i,...s}=r;ul(i)&&typeof jr=="function"&&(i=jr(i._payload));const a=ot.toArray(i),c=a.find(ah);if(c){const d=c.props.children,h=a.map(u=>u===c?ot.count(d)>1?ot.only(null):st(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:st(d)?Dt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var oh=hl("Slot");function sh(e){const t=te((n,r)=>{let{children:o,...i}=n;if(ul(o)&&typeof jr=="function"&&(o=jr(o._payload)),st(o)){const s=ch(o),a=lh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Dt(o,a)}return ot.count(o)>1?ot.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ih=Symbol("radix.slottable");function ah(e){return st(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ih}function lh(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function ch(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const ml=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,pl=Ba,dh=(e,t)=>n=>{var r;if(t?.variants==null)return pl(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n?.[d],u=i?.[d];if(h===null)return null;const p=ml(h)||ml(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,...E}=h;return Object.entries(E).every(g=>{let[f,S]=g;return Array.isArray(S)?S.includes({...i,...a}[f]):{...i,...a}[f]===S})?[...d,u,p]:d},[]);return pl(e,s,c,n?.class,n?.className)},uh=dh("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Ee=te(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?oh:"button",{className:P(uh({variant:t,size:n,className:e})),ref:i,...o}));Ee.displayName="Button";const hh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),mh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),fl=e=>{const t=mh(e);return t.charAt(0).toUpperCase()+t.slice(1)},gl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),ph=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const gh=te(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>tt("svg",{ref:c,...fh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:gl("lucide",o),...!i&&!ph(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>tt(d,h)),...Array.isArray(i)?i:[i]])),Ye=(e,t)=>{const n=te(({className:r,...o},i)=>tt(gh,{ref:i,iconNode:t,className:gl(`lucide-${hh(fl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=fl(e),n},_h=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=Ye("chevron-down",_h),Eh=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],yh=Ye("ellipsis-vertical",Eh),Sh=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],_l=Ye("file-text",Sh),vh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],El=Ye("info",vh),bh=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],wh=Ye("maximize-2",bh),Nh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Ch=Ye("menu",Nh),xh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],lr=Ye("message-square-plus",xh),Th=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Ko=Ye("mic",Th),kh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Oh=Ye("minimize-2",kh),Rh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yl=Ye("plus",Rh),Ah=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Ih=Ye("rotate-ccw",Ah),Mh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Sl=Ye("square",Mh),Ph=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],vl=Ye("thumbs-up",Ph),Dh=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],bl=Ye("thumbs-down",Dh),Lh=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Uh=Ye("triangle-alert",Lh),Fh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],bn=Ye("x",Fh),Vh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],jh=Ye("zoom-in",Vh),wl=e=>{let t;const n=new Set,r=(a,c)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=c??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},zh=(e=>e?wl(e):wl),Yh=e=>e;function Hh(e,t=Yh){const n=Un.useSyncExternalStore(e.subscribe,Un.useCallback(()=>t(e.getState()),[e,t]),Un.useCallback(()=>t(e.getInitialState()),[e,t]));return Un.useDebugValue(n),n}const $h=e=>{const t=zh(e),n=r=>Hh(t,r);return Object.assign(n,t),n},Bh=(e=>$h);function Gh(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var o;const i=a=>a===null?null:JSON.parse(a,void 0),s=(o=n.getItem(r))!=null?o:null;return s instanceof Promise?s.then(i):i(s)},setItem:(r,o)=>n.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>n.removeItem(r)}}const qo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qo(r)(n)}}}},Wh=(e,t)=>(n,r,o)=>{let i={storage:Gh(()=>localStorage),partialize:f=>f,version:0,merge:(f,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 qo(d.getItem.bind(d))(i.name).then(_=>{if(_)if(typeof _.version=="number"&&_.version!==i.version){if(i.migrate){const y=i.migrate(_.state,_.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[k,x]=_;if(E=i.merge(x,(y=r())!=null?y:p),n(E,!0),k)return h()}).then(()=>{m?.(E,void 0),E=r(),s=!0,c.forEach(_=>_(E))}).catch(_=>{m?.(void 0,_)})};return o.persist={setOptions:f=>{i={...i,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>s,onHydrate:f=>(a.add(f),()=>{a.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},i.skipHydration||g(),E||p},Kh=Wh,we={USER:"user",ASSISTANT:"assistant"};var ye=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(ye||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let dt="";const cr=e=>`med-assist-store-${e}`,qh=e=>{wn(),dt=cr(e)},Xh=200;let ft=null,dr=null;function wn(){if(dr&&(clearTimeout(dr),dr=null),!!ft){try{sessionStorage.setItem(ft.key,JSON.stringify(ft.value))}catch{}ft=null}}typeof window<"u"&&(window.addEventListener("pagehide",wn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&wn()}));const Zh={getItem:()=>{if(!dt)return null;if(ft?.key===dt)return ft.value;try{const e=sessionStorage.getItem(dt);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{dt&&(ft&&ft.key!==dt&&wn(),ft={key:dt,value:t},dr||(dr=setTimeout(wn,Xh)))},removeItem:()=>{ft?.key===dt&&(ft=null),dt&&sessionStorage.removeItem(dt)}},Nl={sessionId:"",isStreaming:!1,recordingStatus:ye.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:ge.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},Cl={...Nl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=Bh()(Kh((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:ge.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:ye.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),isMobile:!1,setIsMobile:n=>e({isMobile:n}),displayMode:"widget",setDisplayMode:n=>e({displayMode:n}),toggleDisplayMode:()=>e({displayMode:t().displayMode==="full"?"widget":"full"}),initialDisplayMode:"widget",setInitialDisplayMode:n=>e({initialDisplayMode:n}),chats:{},addMessageToSession:(n,r)=>{e(o=>({chats:{...o.chats,[n]:[...o.chats[n]||[],r]}}))},updateMessageInSession:(n,r,o)=>e(i=>({chats:{...i.chats,[n]:(i.chats[n]||[]).map(s=>s.id===r?{...s,...o}:s)}})),getMessagesForSession:n=>t().chats[n]||[],setMessagesForSession:(n,r)=>e(o=>({chats:{...o.chats,[n]:r}})),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),clearSession:async()=>{e(Nl),await sessionStorage.removeItem(dt||cr(t().agentId))},clearUser:()=>{e(Cl),sessionStorage.removeItem(dt||cr(t().agentId))}}),{name:"med-assist-store",storage:Zh,partialize:e=>({agentId:e.agentId,userId:e.userId,context:e.context,chats:e.chats,sessionId:e.sessionId,refreshToken:e.refreshToken,sessToken:e.sessToken,level:e.level,initialMessage:e.initialMessage,sessionInitialMessages:e.sessionInitialMessages,connectionStatus:e.connectionStatus,elicitationState:e.elicitationState})})),Jh=e=>{const t=cr(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(Cl),n&&j.setState(n)},Xo=St(null),Qh=({children:e})=>{const[t,n]=V(null);return l(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},em=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},tm=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},nm=()=>{const[e,t]=V(A.VOICE_AGENT_STATE.IDLE),[n,r]=V(!1),o=em(),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(A.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(A.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(A.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(A.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}},Zt=te(({className:e,...t},n)=>l("div",{ref:n,className:P("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));Zt.displayName="Card";const xl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("flex flex-col space-y-1.5 p-6",e),...t}));xl.displayName="CardHeader";const Tl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("font-semibold leading-none tracking-tight",e),...t}));Tl.displayName="CardTitle";const rm=te(({className:e,...t},n)=>l("div",{ref:n,className:P("text-sm text-muted-foreground",e),...t}));rm.displayName="CardDescription";const kl=te(({className:e,...t},n)=>l("div",{ref:n,className:P("p-6 pt-0",e),...t}));kl.displayName="CardContent";const Ol=te(({className:e,...t},n)=>l("div",{ref:n,className:P("flex items-center p-6 pt-0",e),...t}));Ol.displayName="CardFooter";const Zo=5,Rl=3,Al=10*1024*1024,zr={width:384,height:600},Yr=20,om=400,sm=320,im=560,am=150;function lm({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]),mt(()=>{!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),k=Math.max(0,window.innerHeight-zr.height-Yr),x=Math.max(0,Math.min(_.x,y)),w=Math.max(0,Math.min(_.y,k));return x===_.x&&w===_.y?_:{x,y:w}})},m=()=>{f!==null&&clearTimeout(f),f=setTimeout(S,am)};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),k=Math.max(0,Math.min(S,_)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[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 Jo="#6B5CE0",cm="#F0F0F0",Hr={background:cm,backgroundImage:void 0,primary:Jo,textColor:"black"},dm="rgba(0, 0, 0, 0.4)",um="24px";function hm(e){if(e==="dark")return"white";if(e==="light")return"black"}function mm(e){const t=e?.primary??e?.primaryColor??Hr.primary,n=e?.textColor??hm(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 pm(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const c=(o+i)/2;if(o!==i){const h=o-i;switch(a=c>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(c*100);return`${s} ${a}% ${d}%`}function fm(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,c=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(c=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),c=Math.round(c*100);const h=Math.round(d*100);return`${a} ${c}% ${h}%`}function gm(e){const t=e.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(!t)throw new Error("Invalid HSL format");return`${t[1]} ${t[2]}% ${t[3]}%`}function Qo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return pm(t);if(t.startsWith("rgb"))return fm(t);if(t.startsWith("hsl"))return gm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Il(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Il(e)>.5?"0 0% 9%":"0 0% 98%"}function _m(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return"0 0% 96%";const n=t[1],r=Math.max(0,parseInt(t[2],10)-5);return`${n} ${r}% 96%`}function Em(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return{50:"262 83% 98%",100:"262 83% 96%",200:"262 83% 92%",300:"262 83% 85%",400:"262 83% 75%",500:"262 83% 58%",600:"262 83% 50%",700:"262 83% 40%",800:"262 83% 30%",900:"262 83% 20%"};const n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);return{50:`${n} ${Math.max(0,r-20)}% ${Math.min(98,o+40)}%`,100:`${n} ${Math.max(0,r-15)}% ${Math.min(96,o+35)}%`,200:`${n} ${Math.max(0,r-10)}% ${Math.min(92,o+30)}%`,300:`${n} ${Math.max(0,r-5)}% ${Math.min(85,o+20)}%`,400:`${n} ${r}% ${Math.min(75,o+10)}%`,500:`${n} ${r}% ${o}%`,600:`${n} ${Math.min(100,r+5)}% ${Math.max(50,o-10)}%`,700:`${n} ${Math.min(100,r+10)}% ${Math.max(40,o-20)}%`,800:`${n} ${Math.min(100,r+15)}% ${Math.max(30,o-30)}%`,900:`${n} ${Math.min(100,r+20)}% ${Math.max(20,o-40)}%`}}function Ml(e,t){const n=t.primary??Jo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,g)=>{const f=e instanceof ShadowRoot?e.host:e;f instanceof HTMLElement&&f.style.setProperty(E,g)};let c;try{c=Qo(n)}catch{c=Qo(Jo)}a("--primary",c),a("--primary-foreground",es(c)),a("--ring",c),a("--border-primary",c);const d=Em(c);for(const[E,g]of Object.entries(d))a(`--primary-${E}`,g);const h=es(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const E=i?"#191919":"#F0F0F0";try{a("--background",Qo(E))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${c} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",_m(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${c})`),a("--header-stroke",`hsl(${c} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${c} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${c} / 0.3)`)),s&&!o){const E=Il(h)>.5;a("--header-tagline",E?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",c):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${p}-${E})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",c),a("--accent-foreground",es(c)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",um),a("--theme-background-overlay",dm),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function Jt({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 ts(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Pl(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(ts,{}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[l("div",{className:"px-2 pt-2 pb-1",children:l(Jt,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Jt,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Jt,{className:"h-9 w-9 rounded-full"}),l(Jt,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function ym(){const e=[{role:we.ASSISTANT,size:"h-16 w-[70%]"},{role:we.USER,size:"h-9 w-[45%]"},{role:we.ASSISTANT,size:"h-24 w-[75%]"},{role:we.USER,size:"h-9 w-[35%]"},{role:we.ASSISTANT,size:"h-16 w-[65%]"}];return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(ts,{}),e.map((t,n)=>l("div",{className:P("flex",t.role===we.USER?"justify-end":"justify-start"),children:l(Jt,{className:P("rounded-lg",t.size)})},n))]})}function Sm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return l("div",{"aria-hidden":"true",children:[l(ts,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Jt,{className:P("h-5 rounded-md",t[r%t.length])}),l(Jt,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function vm(e,t=[]){let n=[];function r(i,s){const a=St(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=ae(()=>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=vt(E);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>St(s));return function(s){const a=s?.[e]||i;return ae(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,bm(o,...t)]}function bm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ae(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var wm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=wm.reduce((e,t)=>{const n=hl(`Primitive.${t}`),r=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}},{}),Dl={exports:{}},rs={};const Nm=Wd(Oo);var Ll;function Cm(){if(Ll)return rs;Ll=1;var e=Nm;function t(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,p){var E=p(),g=r({inst:{value:E,getSnapshot:p}}),f=g[0].inst,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 rs.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,rs}var Ul;function xm(){return Ul||(Ul=1,Dl.exports=Cm()),Dl.exports}var Tm=xm();function km(){return Tm.useSyncExternalStore(Om,()=>!0,()=>!1)}function Om(){return()=>{}}var os="Avatar",[Rm]=vm(os),[Am,Fl]=Rm(os),Vl=te((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=V("idle");return l(Am,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(ns.span,{...r,ref:t})})});Vl.displayName=os;var jl="AvatarImage",zl=te((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Fl(jl,n),a=Im(r,i),c=Ut(d=>{o(d),s.onImageLoadingStatusChange(d)});return Kt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(ns.img,{...i,ref:t,src:r}):null});zl.displayName=jl;var Yl="AvatarFallback",Hl=te((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Fl(Yl,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(ns.span,{...o,ref:t}):null});Hl.displayName=Yl;function $l(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Im(e,{referrerPolicy:t,crossOrigin:n}){const r=km(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=V(()=>$l(i,e));return Kt(()=>{a($l(i,e))},[i,e]),Kt(()=>{const c=u=>()=>{a(u)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Bl=Vl,Gl=zl,Wl=Hl;const ss=te(({className:e,...t},n)=>l(Bl,{ref:n,className:P("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Bl.displayName;const Kl=te(({className:e,...t},n)=>l(Gl,{ref:n,className:P("aspect-square h-full w-full",e),...t}));Kl.displayName=Gl.displayName;const is=te(({className:e,...t},n)=>l(Wl,{ref:n,className:P("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Wl.displayName;const ql=St(!1);function Mm({enabled:e,children:t}){return l(ql.Provider,{value:e,children:t})}function Pm(){return vt(ql)}const Xl="(max-width: 768px), (pointer: coarse)",Zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Dm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Xl)?.matches??!1,t=Zl.test(navigator?.userAgent??"");return e||t}function Jl(){const[e,t]=V(Dm);return $(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Xl),r=Zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Lm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:c=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Jl(),p=Pm(),E=j(C=>C.displayMode)==="side_panel",g=p&&!u&&!E,f=j(C=>C.displayMode)==="full",S=j(C=>C.initialDisplayMode)==="full",m=!f&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",_=j(C=>C.connectionStatus),y=j(C=>C.level)==="user",[k,x]=V(!1),w=X(null),T=ae(()=>a===A.VOICE_AGENT_STATE.CONNECTED||a===A.VOICE_AGENT_STATE.CONNECTING||a===A.VOICE_AGENT_STATE.LISTENING||a===A.VOICE_AGENT_STATE.SPEAKING||a===A.VOICE_AGENT_STATE.THINKING,[a]),v=ue(()=>{k||(x(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,x(!1)},6e3),s())},[k,s]);$(()=>{_===ge.CONNECTED&&(x(!1),w.current&&clearTimeout(w.current))},[_]);const b=(()=>{switch(_){case ge.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case ge.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case ge.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return l("div",{className:"px-6 py-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative flex-shrink-0",children:[l(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?l("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):l("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),l("div",{className:P("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",b.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:b.text})})]})]}),l("div",{className:P("flex items-center",!g&&"gap-1"),children:[!T&&!y&&l(Ee,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:v,disabled:k,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(lr,{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(yh,{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(Oh,{className:"w-8 h-8"}):l(wh,{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(bn,{className:"w-8 h-8"})})]})]})})}const as=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}));as.displayName="Textarea";function Ql({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=V(!1),[s,a]=V(""),c=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";$(()=>{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(_l,{className:"h-5 w-5"})}),l("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&l("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&l("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:l(bn,{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(bn,{className:"h-3 w-3"})})]})}function ls({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return l("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return l(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&l("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return l(Ql,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),ec=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Um=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},tc=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),Fm=nt(()=>ec().then(e=>({default:e.ElicitationInput})));function Vm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:c,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:E,allowed:g,showStartNewChatButton:f,onStartNewChat:S,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:x}){const w=X(null),T=X(null),v=e.trim().length>0||a,b=!g||g.includes(A.SYNAPSE_CONVERSATION.AUDIO),C=!g||g.includes(A.SYNAPSE_CONVERSATION.VOICE),D=v||!b,W=v,G=!g||g.includes(A.SYNAPSE_CONVERSATION.FILE),Ne=(d||p!==ye.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)]":Ne?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),se=B=>{const Z=Array.from(B.target.files||[]);Z.length>0&&r(Z)},_e=()=>{d||(w.current&&(w.current.value=""),w.current?.click())},F=B=>{B.key==="Enter"&&!B.shiftKey&&W&&!d&&(B.preventDefault(),n())},ce=B=>{B.style.height="auto",B.style.overflow="hidden";const Z=B.scrollHeight,L=x?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"},Ae=B=>{ce(B.currentTarget)};return $(()=>{T.current&&ce(T.current)},[e]),$(()=>{d||T.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(lr,{className:"w-5 h-5","aria-hidden":!0})]})}):l(me,{children:y?l(Xe,{fallback:l(Pl,{}),children:l(Fm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):x?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"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(ls,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:w,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:se,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:l(as,{ref:T,onInput:Ae,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress: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===ye.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(yl,{className:"w-6 h-6",strokeWidth:1.5})})}),l("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className: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(Sl,{className:"w-4 h-4"})}):b&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:Ne,className:P("h-10 w-10 shrink-0 p-2",pe),title:"Start recording","aria-label":"Start recording",children:l(Ko,{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(cs,{className:"w-4 h-4 text-primary-foreground"})}):b&&C&&!s&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:w,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:se,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(ls,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(as,{ref:T,onInput:Ae,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!0,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===ye.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(yl,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,className: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(Sl,{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(cs,{className:"w-4 h-4 text-primary-foreground"})}):b&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:Ne,className:P("h-10 w-10 shrink-0",pe),title:"Start recording","aria-label":"Start recording",children:l(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),b&&C&&!s&&l(Ee,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const jm=Wt(Vm),nc=St(null),rc=nc.Provider;function zm(){const e=vt(nc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function Ym({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(bn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Hm(){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(Ym,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?l("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:l("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const $m="Before we begin",Bm=e=>`A quick note on how ${e} works and handles your information.`,Gm=e=>[`This assistant is powered by AI. Replies are generated automatically and can be wrong, so please check anything important before you act on it. Don't use it in an urgent or emergency situation \u2014 contact ${e} directly or call your local emergency number.`,`To help you, ${e} and our authorised technology partners process what you share here \u2014 your contact details and your messages \u2014 under contractual and security safeguards, on secure servers. We use it only to provide this service, and keep it only as long as needed or as the law requires.`];function Wm(e,t){return(Array.isArray(e)?e:e.split(/\n\s*\n|\n/)).map(n=>String(n??"").replace(/\{\{\s*name\s*\}\}/gi,t).trim()).filter(Boolean)}const oc=(e,t)=>{if(t){const n=Wm(t,e);if(n.length)return n}return Gm(e)},Km="I agree and consent",qm="By continuing, you consent to the above.",Xm="Continue";function sc({botName:e,consentContent:t,isFullScreen:n}){return l(me,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:P("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:$m}),l("p",{className:P("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Bm(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:oc(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 Zm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(ds,{isOpen:e,onClose:t,children:l("div",{className: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(sc,{botName:n,consentContent:o,isFullScreen:s}):l("div",{className:"flex flex-col gap-2",children:[l("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),oc(n,o).map((a,c)=>l("p",{className: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 Jm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=V(!1);return e?l(ds,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className: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(sc,{botName:t,consentContent:n,isFullScreen:o}),l("div",{className:"flex flex-col gap-1.5",children:[l("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[l("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),l("div",{"aria-hidden":"true",className: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:Km})]}),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:qm})]}),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:Xm})]})}):null}const Qm=nt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),ep=nt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),tp=nt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),np=nt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),rp=nt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),op=[{label:"Took longer than expected",value:"took_longer"},{label:"Asking too many questions",value:"too_many_questions"},{label:"Irrelevant response",value:"irrelevant_response"},{label:"Other",value:"other"}],sp=[{Icon:Qm,label:"Bad",score:1},{Icon:ep,label:"Poor",score:2},{Icon:tp,label:"Okay",score:3},{Icon:np,label:"Good",score:4},{Icon:rp,label:"Great!",score:5}];function ip(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function ap({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=V(null),[d,h]=V(new Set),[u,p]=V(!1),E=s&&a!==null?ip(a,t):t.form?.default?.length?t.form.default:op,g=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},f=_=>{c(_),h(new Set)},S=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(ds,{isOpen:e,onClose:o,children:l("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[l("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),l("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[l("div",{className:"flex flex-col gap-1",children:[t.title&&l("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&l("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&l("div",{className:"flex items-center justify-between gap-1",children:sp.map(({Icon:_,label:y,score:k})=>{const x=a===k,w=a!==null&&!x;return l("button",{onClick:()=>f(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[l("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${w?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:l(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 ${x?"text-primary/50 font-medium":w?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&E.length>0&&l("div",{className:"flex flex-col gap-2",children:E.map(_=>l("div",{onClick:()=>g(_.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(_.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:_.label},_.value))}),l(Ee,{disabled:!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 ic({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:c,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:E,activeElicitation:g,voiceAgentState:f,theme:S,feedbackModal:m,consentModal:_}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:w,tagline:T,iconUrl:v,onStartNewSession:b,showStartNewChatButton:C,onToggleDisplayMode:D,onOpenSessionDrawer:W}=zm(),[G,Ne]=V(!1),[pe,se]=V(!1),[_e,F]=V(!1),ce=X(null),Ae=j(z=>z.level),B=c,Z=B==="full",L=B==="side_panel",K=X(null),[re,Te]=V("");$(()=>{K.current!==null&&K.current!==B&&Te(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=ae(()=>mm(S),[S]),Ie=j(z=>z.setIsMobile),He=!!E,ie=ue(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);mt(()=>{if(!ce.current)return;const z=B==="full"?{...J,headerTinted:!1}:J;Ml(ce.current,z),B==="full"&&!J.backgroundImage?(ce.current.style.setProperty("--background","0 0% 100%"),ce.current.style.setProperty("--widget-bg-overlay","transparent")):(ce.current.style.removeProperty("--background"),ce.current.style.removeProperty("--widget-bg-overlay"),Ml(ce.current,J))},[J,B]),$(()=>{const z=()=>{const Me=window?.innerWidth??0,Se=navigator?.userAgent?.toLowerCase()??"",Ue=Me<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(Se);Ne(Ue),Ie(Ue)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),mt(()=>{if(!e||!G||!ce.current)return;const z=ce.current;let Me=null,Se=null,Ue=null,Ke=window.visualViewport?.offsetTop??0,Fe=0;const gt=2,ut=80;if(window.visualViewport){const je=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,ke=window.visualViewport.offsetTop;Me=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${ke}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Ge}px`,z.style.maxHeight=`${Ge}px`,z.style.minHeight=`${Ge}px`,Se&&clearTimeout(Se),Se=setTimeout(()=>{z.style.transition=""},100)})}},rt=()=>{je()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,ke=Date.now();Math.abs(Ge-Ke)<gt||ke-Fe<ut||(Fe=ke,Ke=Ge,Me=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",rt),window.visualViewport.addEventListener("scroll",Be),je(),()=>{Me&&cancelAnimationFrame(Me),Se&&clearTimeout(Se),Ue&&clearTimeout(Ue),window.visualViewport?.removeEventListener("resize",rt),window.visualViewport?.removeEventListener("scroll",Be),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const je=()=>{z&&(z.style.transition="none",z.style.top="0",z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height="100svh",z.style.maxHeight="100svh",setTimeout(()=>{z.style.transition=""},100))};return window.addEventListener("resize",je),je(),()=>{window.removeEventListener("resize",je),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),$(()=>{if(e&&!(L&&d==="push")){const z=ce.current,Me=window.scrollY,Se=document.body.style.cssText,Ue=document.documentElement.style.overflow,Ke=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Me}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",Ke>0&&!G&&(document.body.style.paddingRight=`${Ke}px`);let Fe=0;const gt=je=>{Fe=je.touches[0].clientY},ut=je=>{if(je.touches.length!==1)return;const rt=Fe-je.touches[0].clientY;Fe=je.touches[0].clientY;let Be=je.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:ke,scrollHeight:Yt,clientHeight:_t}=Be,rn=ke<=0&&rt<0,on=ke+_t>=Yt-1&&rt>0;if(!rn&&!on)return;break}Be=Be.parentElement}je.preventDefault()};return z&&(z.addEventListener("touchstart",gt,{passive:!0}),z.addEventListener("touchmove",ut,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",gt),z.removeEventListener("touchmove",ut)),document.body.style.cssText=Se,document.documentElement.style.overflow=Ue,window.scrollTo(0,Me)}}},[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:De,elementRef:Le}=lm({enabled:e&&!G&&!Z&&!L});$(()=>{ce.current&&(Le.current=ce.current)},[Le]);const Nt=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"),zt=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:ce,"data-mode":B,className:Nt,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:`${De.x}px`,top:`${De.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 Wc=Object.defineProperty;var Kc=(e,t,n)=>t in e?Wc(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(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)?`
38
+ `}),l(Zt,{className:zt,"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(Zm,{isOpen:_e,onClose:()=>F(!1),botName:x,explicitDisclaimer:S?.explicitDisclaimer,consentContent:S?.consentContent,isFullScreen:Z}),_?.isOpen&&l(Jm,{isOpen:!0,botName:x,consentContent:S?.consentContent,onAccept:_.onAccept,isFullScreen:Z}),m?.isOpen&&l(ap,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),Z&&n,Ae==="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(Lm,{onClose:y,showCloseButton:k,title:x,titleImg:w,tagline:T,iconUrl:v,startNewConversation:b,voiceAgentState:f,headerTinted:Z?!1:J.headerTinted,onToggleDisplayMode:D,onOpenSessionDrawer:Z?void 0:W})}),(()=>{const z=Z&&!!o,Me=s&&f===A.VOICE_AGENT_STATE.IDLE?l(Xe,{fallback:l(Pl,{}),children:l(jm,{value:s.value,onChange:s.onChange,onSend:He?ie:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||He&&pe,isMobile:G,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:J,onStartNewChat:b,showStartNewChatButton:C,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:E,activeElicitationState:g,isFullScreen:Z&&!z})}):null,Se={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Ue=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:Se,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:Se,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:Se,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:Se,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:Se,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:Se,children:"Eka Care"})]}),l(El,{className:"w-3 h-3"})]})]}),Ke=o&&Z?o({composer:z?Me:null,composerFooter:z?Ue:null}):null;return l(me,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Ke??t,l(Hm,{})]}),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:Me}),Ue]})]})})()]})]})]})}function lp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function cp(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),o=new Date(e.getFullYear(),e.getMonth(),e.getDate());return o.getTime()===n.getTime()?"Today":o.getTime()===r.getTime()?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}function dp(e){const t=new Date(e.c_at),n=cp(t),r=lp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function up(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function hp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=dp(e);return l("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),l("div",{className:"flex items-center gap-2 w-full min-w-0",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&l(up,{})]})]})}function ac({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?l(Sm,{}):e.length===0?l("div",{className:"flex items-center justify-center h-full px-4 text-center",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):l(me,{children:e.map(o=>l(hp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function lc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:c,onClose:d}=e;return l(me,{children:[l("div",{className: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(bn,{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(lr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),l("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:l(ac,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return l("div",{id:"synapse-session-sidebar","data-collapsed":s,className: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(Ch,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?l("button",{type:"button",onClick:o,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:l(lr,{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(lr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&l("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:l(ac,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function mp(){const e=new Date().getHours();return e>=5&&e<12?"Good morning. How are you feeling today?":e>=12&&e<17?"Good afternoon. How are you feeling right now?":e>=17&&e<21?"Good evening. How are you doing this evening?":"Up late? I'm here whenever you need me."}const pp=180;function fp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=c=>{const d=c.label||c.value||"";d&&n({message:c.value||d,messageId:Date.now().toString()})};return l("div",{className:"flex-1 flex flex-col overflow-y-auto",children:l("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[l("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=pp&&l("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:mp()}),e&&l("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&l("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((c,d)=>{const h=c.label||c.value||"";return h?l("button",{type:"button",onClick:()=>a(c),disabled:r,className: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 Qt={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Nn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function gp(e,t){return`${e}:${t}`}function cc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function dc(){const[e,t]=V(typeof navigator<"u"?navigator.onLine:!0);return $(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const uc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_p=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Ep=e=>{const t=new Date(e),n=t.toLocaleDateString(void 0,{weekday:"short"}),r=t.toLocaleDateString(void 0,{day:"2-digit"}),o=t.toLocaleDateString(void 0,{month:"short"});return{weekday:n,dayNum:r,month:o}},yp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},hc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Sp=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===A.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),c=n||a,d=n&&r?wp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:hc(c,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const c=a.date?s.findIndex(d=>d.date===a.date):-1;if(c===-1)s.push({...a});else{const d=s[c];s[c]={...d,...uc(a),slots:a.slots??d.slots}}}return s},vp=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,c=s.end_date||o.end_date;r[i]={...s,...uc(o),availability:Sp({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},mc=e=>!!e&&Array.isArray(e.doctors),bp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==A.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!mc(e)||!mc(t))return e;const r=e.format||t.format;return{...t,doctors:vp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},wp=(e,t)=>{const n=new Date(e),r=new Date(t),o=Math.round((r.getTime()-n.getTime())/(1e3*60*60*24));return o>=0?o+1:3},pc=(e,t)=>`${e}::${t}`,Np=e=>e<1e12?e*1e3:e,Cp=(e,t)=>`${e}::${t}::answer`,xp=e=>!!e?.tool_id&&!!e?.component;function Tp(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(xp),i=r.timestamp?Xt(Np(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===we.USER?we.USER:we.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>pc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[pc(r.id,s.tool_id)]={tool_id:s.tool_id,messageId:r.id,component:s.component,input:s.input,active:!1,disabled:!0,...s.answer&&{answer:s.answer}},s.answer&&t.push({id:Cp(r.id,s.tool_id),content:s.answer,role:we.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const kp=Math.round(Al/(1024*1024)),fc=(e,t=0)=>e.length+t>Rl?{title:`You can only upload up to ${Rl} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Al?{title:`Total file size limit of ${kp} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,gc="initial-bot-message",en=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Op=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=V([]),d=X([]),[h,u]=V(!1),[p,E]=V(!1),g=X(new Map),f=X(0),[S,m]=V(!1),_=X([]),y=X(null),k=X({}),x=X({}),w=X(null),T=tm(),v=X(null),{isOnline:b}=dc(),C=X(!1),D=X([]),W=j(N=>N.agentId),G=j(N=>N.sessionId),Ne=j(N=>N.isStreaming),pe=j(N=>N.isWaitingForResponse),se=j(N=>N.initialMessage),_e=j(N=>N.userId),F=j(N=>N.fileUploadPerSession),{setSessionId:ce,setRefreshToken:Ae,setSessToken:B,setLevel:Z,setError:L,setConnectionStatus:K,setShowRetryButton:re,setStartNewConnection:Te,setIsStreaming:J,setIsWaitingForResponse:Ie,setProgressMessage:He,setRecordingStatus:ie,clearSession:De,clearUser:Le,addMessageToSession:Nt,getMessagesForSession:zt,setMessagesForSession:z,updateMessageInSession:Me,setUserId:Se,setFileUploadPerSession:Ue,setToastMessage:Ke,upsertElicitationState:Fe,setElicitationState:gt,setInitialMessage:ut,setSessionInitialMessage:je}=j.getState();$(()=>{if(!b)L({title:"No internet connection",description:"Please check your internet connection."}),K(ge.NOT_CONNECTED);else if(!S)K(ge.CONNECTING);else if(ke())K(ge.CONNECTED),_t();else{const{showRetryButton:N,startNewConnection:O,error:M}=j.getState();(N||O||M)&&!ke()&&_t(),w.current!==null&&!O&&!xn()&&rt(j.getState().sessionId||void 0)}},[b,S]),$(()=>{G&&(c(N=>{const O=new Set(N.map(I=>I.id)),M=[...N];for(const I of zt(G)||[])O.has(I.id)||(O.add(I.id),M.push(I));return M}),_.current=[])},[G]),$(()=>{if(m(!1),!W)return;const N=new A.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:O=>{if(pr(O),typeof navigator<"u"&&!navigator.onLine){K(ge.NOT_CONNECTED),L({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case A.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(Le(),y.current?.clearTokens(),sn()):vr();return}case A.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:vr();return;case A.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:L(null),K(ge.NOT_CONNECTED),Te(!0);return;case A.SYNAPSE_RECOVERY_REASON.RETRY_LATER:K(ge.CONNECTING);return}switch(O.code){case A.SynapseErrorCode.API:case A.SynapseErrorCode.SESSION:{const M=O;M.status===404||M?.context?.status===404?Te(!0):(K(ge.NOT_CONNECTED),L({title:"Something went wrong!",description:en(O)}),re(!0));break}case A.SynapseErrorCode.RECORDING:L({title:"Recording failed",description:en(O)});break;case A.SynapseErrorCode.CONNECTION:ke()||(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:en(O)})));break;default:L({title:"Something went wrong",description:en(O)}),re(!0);break}},onTokenExchange:O=>{const M=j.getState().userId;(O?.user_id&&M&&O.user_id!==M||O?.userid_change_detected)&&De(),O?.refresh_token&&Ae(O.refresh_token),O?.sess_token&&B(O.sess_token),O?.level&&Z(O.level),O?.user_id&&Se(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=N,T(N),m(!0),()=>{m(!1),Yt(),y.current=null,T(null),v.current&&(clearTimeout(v.current),v.current=null)}},[W,e,o]),$(()=>{d.current=a},[a]),$(()=>{const N=d.current[d.current.length-1];!N?.role||!G||(N?.role===we.USER&&!N.isStored?(c(O=>{const M=[...O];return M[M.length-1]={...N,isStored:!0},M}),Nt(G,{...N,isStored:!0})):!Ne&&!N.isStored&&(c(O=>{const M=[...O];return M[M.length-1]={...N,isStored:!0},M}),Nt(G,{...N,isStored:!0})))},[a,Ne]),$(()=>()=>{const N=d.current[d.current.length-1],O=j.getState().sessionId;N&&!N?.isStored&&O&&((j.getState().chats[O]||[]).some(M=>M.id===N.id)||Nt(O,{...N,isStored:!0}))},[]),$(()=>(v.current&&(clearTimeout(v.current),v.current=null),pe&&!Ne?v.current=setTimeout(()=>{Ie(!1),v.current=null},3e4):Ne&&v.current&&(clearTimeout(v.current),v.current=null),()=>{v.current&&(clearTimeout(v.current),v.current=null)}),[pe,Ne,Ie]);const rt=async N=>{w.current=performance.now();try{const O=await y.current?.startSession(N?{session_id:N}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===N),ce(O.session_id)),O?.user_id&&Se(O.user_id),O?.initial_message){ut(O.initial_message);const M=O.session_id||N;M&&je(M,O.initial_message)}O?.error?.msg&&Ke(O.error.msg)}catch(O){if(O?.reason)return;const M=O;M.status===404||M.context?.status==404?(L(null),K(ge.NOT_CONNECTED),Te(!0)):(L({title:"Connection Lost!",description:en(O)}),re(!0))}},Be=async N=>{const O=j.getState().chats[N];if(O?.length)return c(O),O;const M=g.current.get(N);if(M)return M;const I=(async()=>{try{const q=await y.current?.getSessionMessages(N);if(!q?.length)return[];const{messages:oe,elicitations:le}=Tp(q);return Object.keys(le).length&&gt({...j.getState().elicitationState,...le}),z(N,oe),c(oe),oe}catch{return[]}finally{g.current.delete(N)}})();g.current.set(N,I),E(!0);try{return await I}finally{E(!1)}},Ge=async({forceNewSession:N=!1,sessionId:O}={})=>{try{if(!y.current){L({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),N){K(ge.CONNECTING),c([]),await De(),await y?.current?.endSession(),_t(),await rt(),_r();return}const M=j.getState()?.sessionId,I=O||M||void 0;I!==M&&(Yt(),c([]),I&&await Be(I)),await rt(I),_r()}catch{}finally{u(!1)}},ke=()=>y.current?.isConnected()??!1,Yt=()=>{y.current?.endSession()},_t=()=>{f.current=0;const{showRetryButton:N,startNewConnection:O,error:M}=j.getState();N&&re(!1),O&&Te(!1),M&&L(null)},rn=()=>{Tn(Qt.CONNECTION_ESTABLISHED)},on=()=>{let N;try{N=y.current?.getSessionConfig()?.session_id}catch{N=void 0}return N||j.getState().sessionId||void 0},xn=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Tn=(N,O={})=>{const M=on();!M||k.current[N]===M||(k.current[N]=M,cc(N,{sessionId:M,resumed:x.current[M]??!1,...O}))},Zr=(N,O={})=>{const M=on();cc(N,{...M&&{sessionId:M},...O})},At=(N,O,M={})=>{Zr(Qt.SESSION_ERROR,{reason:gp(N,O),...M})},pr=N=>{if(ke())return;const O=N?.code,M=[A.SynapseErrorCode.RECORDING,A.SynapseErrorCode.FILE,A.SynapseErrorCode.MESSAGE,A.SynapseErrorCode.VALIDATION,A.SynapseErrorCode.CONFIGURATION,A.SynapseErrorCode.STORE];if(O&&M.includes(O))return;const I=typeof N?.status=="number"?N.status:void 0,q=N?.error,oe=typeof q?.code=="string"?q.code:typeof q?.type=="string"?q.type:void 0,le={...I!==void 0&&{status:I}};if(N?.reason===A.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||N?.reason===A.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===A.SynapseErrorCode.AUTH||I===401||I===403){At(Nn.AUTH,N?.reason??oe??O??"auth_error",le);return}const he=O===A.SynapseErrorCode.API&&I===void 0;if(O===A.SynapseErrorCode.CONNECTION||I===0||he){At(Nn.CONNECTION,N?.reason??oe??(he?"timeout":O)??"connection_error",le);return}At(Nn.SESSION,N?.reason??oe??O??"session_error",le)},fr=N=>{switch(N){case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:At(Nn.SESSION,N);return;case A.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:At(Nn.CONNECTION,N);return}},Ht=()=>{Tn(Qt.FIRST_MESSAGE_SENT)},Jr=[Qt.CONNECTION_ESTABLISHED,Qt.FIRST_MESSAGE_SENT,Qt.FIRST_BOT_REPLY],Qr=()=>{for(const N of Jr)delete k.current[N];ke()&&xn()&&rn()},gr=N=>{N!==gc&&Tn(Qt.FIRST_BOT_REPLY,{messageId:N})},_r=()=>{const N=y.current;if(!N)return;for(const[M,I]of D.current)N.off(M,I);D.current=[];const O=(M,I)=>{N.on(M,I),D.current.push([M,I])};O(A.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,M=>{const I=M;if(I.data?.text&&I.messageId){const q=j.getState();q.isStreaming||(Ie(!1),J(!0),_t()),q.connectionStatus!==ge.CONNECTED&&ke()&&K(ge.CONNECTED);const oe=I.data.text,le=I.messageId,he=C.current;C.current=!1;const Pe=d.current[d.current.length-1];!(Pe&&Pe.id===le&&Pe.role===we.ASSISTANT)&&gr(le),c(qe=>{const xe=qe[qe.length-1];if(xe&&xe.id===le&&xe.role===we.ASSISTANT){const Oe=[...qe],Je=he&&xe.content.length>0&&!/\s$/.test(xe.content)&&!/^\s/.test(oe)?`
39
39
 
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,`
40
+ `:"";return Oe[Oe.length-1]={...xe,content:xe.content+Je+oe},Oe}else return[...qe,{id:le,content:oe,role:we.ASSISTANT,timestamp:Xt(Date.now()),isStored:!1}]})}}),O(A.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{C.current=!1,J(!1),He(null),Ie(!1)}),O(A.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{_t(),K(ge.CONNECTED),rn()}),O(A.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,M=>{C.current=!0;const I=M;if(!I?.messageId||!I?.data||!I?.data?.details?.component||!I?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ie(!1);const{messageId:q,data:oe}=I,le=oe.tool_id,he=`${q}::${le}`,Pe=j.getState().elicitationState[he],qe=oe.details?.component,xe=I?.data?.details?._meta?.tool_result,Oe=oe.details?.input,Je=bp(Pe?.input,Oe,qe);let ht=I.data.details?._meta?.disp_toast_msg;const It=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case A.SYNAPSE_EICITATION_STATUS.PROGRESS:{const ee=I?.data?.details?.input||{},at=It.reduce((U,ve)=>(ee[ve]!==void 0&&(U[ve]=ee[ve]),U),{}),et={...Pe?.server_input||{},...at},Et=It.filter(U=>!et[U]),Mt=I.data.details?._meta?.mcp_meta_fields||[];Fe(he,{tool_id:le,active:!0,disabled:!1,input:Je,server_input:et,messageId:q,required:It,component:qe,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:xe,orientation:I.data.details?._meta?.orientation,...Mt.length&&{mcp_meta_fields:Mt},...Et?{toolSelectionNames:Et}:{},...Pe?.hide_show_more!==void 0?{hide_show_more:Pe.hide_show_more}:{}});break}case A.SYNAPSE_EICITATION_STATUS.SUCCESS:{Fe(he,{...Pe||{},tool_id:le,disabled:!0,active:eh(qe),messageId:q,component:qe,input:Je,tool_result:xe,send_to_llm:!0});break}case A.SYNAPSE_EICITATION_STATUS.FAILURE:{Fe(he,{...Pe||{},tool_id:le,active:!1,messageId:q,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:xe,disabled:!0});break}default:Fe(he,{tool_id:le,disabled:!1,active:!1,messageId:q,tool_result:xe,input:Je,component:qe})}ht&&Ke(ht);const Ct=I?.data?.details?._meta?.user_hint;c(ee=>{let at=ee[ee.length-1]?.id===q?ee.length-1:ee.findIndex?.(et=>et.id===q);if(at==-1){const et={id:q,content:I.data?.details?.input?.text||"",role:we.ASSISTANT,tool_keys:[he],isResponseFromTool:!0,isStored:!1,...Ct?{userHint:Ct}:{}};return[...ee,et]}else{const et={...ee[at],isResponseFromTool:!0,tool_keys:[...new Set([...ee[at].tool_keys||[],he])],...Ct?{userHint:Ct}:{}};ee[at]=et;const Et=j.getState().sessionId;Et&&Me(Et,q,et)}return[...ee]});const Bt=I?.data?.details?._meta?.disp_message,Qe=j.getState().elicitationState;if((!Qe[he]?.active||Qe[he]?.send_to_llm)&&(Bt||Object.keys(xe||{}).length))try{$t({message:Bt||"",tool_result:xe,toolCalled:!0,tool_key:he})}catch{}}),O(A.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,M=>{if(M?.reason===A.DisconnectionReason.CLIENT_CLOSED)return;const I=M;At(Nn.CONNECTION,I?.reason??"unknown",{...typeof I?.code=="number"&&{closeCode:I.code}}),w.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."}),Te(!0))}),O(A.SYNAPSE_REALTIME_EVENTS.ERROR,M=>{const I=M?.data?.code;switch(fr(I),I){case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:Te(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:L({title:"Session not found",description:"Please start a new chat from onError callback"}),Te(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:sn();return;case A.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case A.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case A.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(f.current<1){f.current++,On();return}L({title:"Error parsing request",description:"please try again"}),re(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:L({title:"Request timed out",description:"please try again"}),re(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:L({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:L({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;case A.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:L({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return;default:L({title:"Something went wrong",description:"please try again"}),re(!0),ie(ye.IDLE);return}}),O(A.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:we.USER,timestamp:Xt(Date.now()),isStored:!0}]),ie(ye.IDLE)),J(!1),Ie(!1),He(null)}),O(A.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,M=>{C.current=!0;const I=M;I.data?.text&&(Ie(!1),He(I.data.text))}),O(A.SYNAPSE_REALTIME_EVENTS.TOOL_START,M=>{C.current=!0;const I=M;if(I.data?.name&&I.messageId){const q=I.messageId;c(oe=>{const le=oe[oe.length-1];if(le&&le.id===q&&le.role===we.ASSISTANT){const he=[...oe];he[he.length-1]={...le,toolCallStatus:`Calling tool: ${I.data.name}...`};const Pe=j.getState().sessionId;return Pe&&Me(Pe,q,{toolCallStatus:`Calling tool: ${I.data.name}...`}),he}return oe})}}),O(A.SYNAPSE_REALTIME_EVENTS.TOOL_END,M=>{C.current=!0;const I=M;if(I.data?.name&&I.messageId){const q=I.messageId;c(oe=>{const le=oe[oe.length-1];if(le&&le.id===q&&le.role===we.ASSISTANT){const he=[...oe];he[he.length-1]={...le,toolCallStatus:"Tool call completed."};const Pe=j.getState().sessionId;return Pe&&Me(Pe,q,{toolCallStatus:"Tool call completed."}),he}return oe})}})},$t=async({message:N,files:O,audio:M,toolCalled:I,selectedComponent:q,resend:oe,tool_declined:le,tool_result:he,tool_key:Pe})=>{const qe=j.getState().elicitationState,xe=Object.values(qe).some(Oe=>Oe.active);if(!(!I&&(!O||O.length===0)&&!N?.trim()&&!M?.audio&&!q&&!xe&&!he&&!Object.keys(he||{}).length)){if(O&&O.length>0){const Oe=fc(O);if(Oe){L(Oe);return}}if(O&&O.length>0&&O.length+F>Zo){const Oe=Zo-F;L({title:`You can only upload up to ${Zo} files per session`,description:`${Oe<=0?"Maximum file upload limit reached":`You have ${Oe} file${Oe===1?"":"s"} upload${Oe===1?"":"s"} left`}`});return}else O&&O.length&&Ue(F+O.length);L(null),re(!1),ke()&&K(ge.CONNECTED);try{const Oe=a.length<=2&&_.current.length==1?_.current:null;let Je=null,ht=null;const It=a.length-1,Ct=It>=0?a[It]:null,Bt=j.getState().elicitationState,Qe=Pe||null,ee=Qe?Bt[Qe]:void 0,at=ee?.component===A.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===A.SYNAPSE_COMPONENTS.CARD?!!ee&&!he&&!!ee.active:!!ee?.active,et=!!(O||[]).length||!!M?.audio||!!le||!at||!I,Et=q?q.label:void 0,Mt=ee?.component===A.SYNAPSE_COMPONENTS.PILL&&typeof Et=="string"?Et:null;if(!et&&at&&Qe&&ee?.messageId){const de=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(Re=>!ee.server_input?.[Re])??[],ze=de.reduce((Re,be)=>{if(q){const An=q[be];An!==void 0&&(Re[be]=An)}else de.length===1&&(Re[be]=N);return Re},{}),xt=ee.mcp_meta_fields?.reduce((Re,be)=>(de.includes(be)?Re[be]=ze[be]:ee.server_input?.[be]&&(Re[be]=ee.server_input[be]),oe&&!Re.is_resend&&(Re.is_resend=oe),Re),{}),to=Object.keys(ee.server_input||{})?.reduce((Re,be)=>{const An=!Object.keys(xt||{})?.includes(be),ws=!!ee.server_input?.[be];return(oe?An&&ws:An&&ee.required?.includes(be)&&ws)&&(Re[be]=ee.server_input?.[be]),Re},{}),no=oe?{}:(ee.required||de).reduce((Re,be)=>(Object.keys(xt||{}).includes(be)||(ze[be]!==void 0?Re[be]=ze[be]:q&&q[be]!==void 0&&(Re[be]=q[be])),Re),{}),Rn={...to||{},...no,...Object.keys(xt||{}).length&&{mcp_meta_fields:xt}};if(!Object.keys(Rn).length)return;await Fe(Qe,{...ee,server_input:{...ee.server_input||{},...Rn}});try{await kn(ee.tool_id,ee.messageId,Rn),Je=!0}catch(Re){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${en(Re)}`}}),ht="Tool call failed",Fe(Qe,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${en(Re)}`}})}}else{const de=Ct?.id,ze=de?Object.entries(qe).filter(([to,no])=>{const[Rn]=to.split("::");return Rn===de&&no.active}):[],xt=he??ee?.tool_result;await y.current?.sendMessage({message:N??"",files:O,audio:M,...Oe&&{initial_prompts:Oe},...le||ze.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...xt&&{tool_result:xt}})}(N||O&&O.length>0||M?.audio||Mt||ht)&&(Je||Ht(),c(de=>{if(Je)return de;const ze=de.length===0&&se?.text?[{id:gc,content:se.text,role:we.ASSISTANT,timestamp:Xt(Date.now()),isStored:!1}]:[];return[...de,...ze,{id:Date.now().toString(),content:Mt||ht||N||"",files:O||[],audio:M,role:we.USER,timestamp:Xt(Date.now()),isStored:!1}]}),Je||Ie(!0),Je=null);const U=j.getState().elicitationState,ve=new Set;Qe&&ve.add(Qe),Ct?.tool_keys?.forEach(de=>ve.add(de)),ve.forEach(de=>{const ze=U[de];ze&&Fe(de,{...ze,...et&&{active:!1,disabled:!0},...de===Qe?{response_value:{...ze?.response_value||{},label:Mt||N||""}}:{}})})}catch{}}},Er=N=>N.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(N.type)?(L({title:`File type not supported: ${N.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):N.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,eo=async()=>{try{await y.current?.startRecording({onChunks:async N=>{ie(ye.PROCESSING),await $t({audio:N}),ie(ye.TRANSCRIBING)},onError(N){ie(ye.IDLE)}}),ie(ye.LISTENING)}catch(N){throw ie(ye.IDLE),N}},yr=()=>{y.current?.endRecording()},kn=async(N,O,M)=>{try{if(!ke())throw new Error("Not connected to the server");await y.current?.callTool(N,O,M)}catch(I){throw I}},sn=async()=>{_t(),await De(),await Ge({forceNewSession:!0})},Sr=async()=>{await Ge({forceNewSession:!0})},vr=()=>{Le(),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."})},On=async()=>{if(ke()){K(ge.CONNECTED);const N=d.current[d.current.length-1];if(N&&N.role===we.USER)try{y.current?.sendMessage({message:N.content,files:N.files||[],messageId:N.id,audio:N.audio})}catch{}}else if(K(ge.NOT_CONNECTED),f.current<2){f.current++;const{sessionId:N}=j.getState();await rt(N)}else f.current===2?(f.current++,re(!0),L({title:"Trying to connect..."})):(L({title:"Something went wrong!",description:"Please start a new chat."}),Te(!0))};return{sendMessage:$t,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Yt,isReady:S,startRecording:eo,stopRecording:yr,getPastSessions:async()=>{try{const N=await y.current?.getPastSessions();return!N||!N?.data?.length?[]:N.data}catch{return[]}},handleRetry:On,isValidFile:Er,handleStartNewConnection:sn,startNewChat:Sr,callTool:kn,handleInitialTaskClick:async N=>{const{message:O}=N;if(!se?.suggestions?.length||!O)return;const M=se.suggestions.find(q=>q.value===O);if(_.current=[{role:"assistant",text:`${se.text} ${M?.response||""}`}],!M||!M.response){await $t(N);return}Ht(),c(q=>[...q,{id:Date.now().toString(),content:O,role:we.USER,timestamp:Xt(Date.now()),isStored:!1}]),Ie(!0),await th(1e3),Ie(!1);const I=Date.now().toString();gr(I),c(q=>[...q,{id:I,content:M.response||"Please try again",role:we.ASSISTANT,timestamp:Xt(Date.now()),isStored:!1}])},sendMessageFeedback:async(N,O,M)=>{if(ke())try{await y.current?.sendMessageFeedback(O,N,M)}catch{}},sendSessionFeedback:async(N,O)=>{if(!(!ke()||!N?.length&&!O))try{await y.current?.sendSessionFeedback(N,O)}catch{}},clearElicitationState:async(N,O)=>{const M=j.getState().elicitationState,I=N?M[N]:void 0;try{await $t({message:O||"User aborted elicitation",tool_declined:!0,tool_result:I?.tool_result,tool_key:N})}catch{}finally{N&&I&&Fe(N,{...I,active:!1,disabled:!0})}},markWidgetOpened:Qr}};function We(e){const t=X(e);return $(()=>{t.current=e}),ue(((...n)=>t.current(...n)),[])}function Rp(e){return e==="full"?A.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?A.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":A.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Ap=32,Ip=100,Mp=320;function Pp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Dp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=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=>Pp()?"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"),Mp);return()=>clearTimeout(S)},[r,e,f]),$(()=>{let S=!1,m=null,_=null,y=0;const k=()=>{if(S)return;const x=p(),w=i.current?.parentElement;if(!x||!w){requestAnimationFrame(k);return}const T=()=>{const{scrollTop:C,scrollHeight:D,clientHeight:W}=x;return D-C-W<=Ap};u.current=!0;let v=0;const b=()=>{if(v>0){v--;return}u.current=T()};x.addEventListener("scroll",b,{passive:!0}),_=()=>x.removeEventListener("scroll",b),m=new ResizeObserver(()=>{if(!u.current)return;const C=Date.now();C-y<Ip||(y=C,v++,f("auto"))}),m.observe(w)};return k(),()=>{S=!0,m?.disconnect(),_?.()}},[p,f]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:g,scheduleScrollToBottom:f}}const us="eka-medassist-agent-config",_c="feedback_hidden",hs="upfront_consent_accepted";function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function Ec(e,t){try{const n=localStorage.getItem(us),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(us,JSON.stringify(r))}catch{}}function Lp({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=nm(),d=We(()=>{r===A.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==A.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"),[]),_=Jl()?"mobile":f,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??om,sm),im),x=n.sidePanelMode??"push",[w,T]=V([]),v=X(!1),[b,C]=V(!1),[D,W]=V(!1),[G,Ne]=V(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=X(null),se=j(U=>U.startNewConnection),_e=j(U=>U.showRetryButton),F=j(U=>U.clearError),ce=j(U=>U.error),Ae=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),Te=j(U=>U.initialMessage),J=j(U=>U.sessionInitialMessages),Ie=j(U=>U.elicitationState),He=j(U=>U.level),{incomingMessages:ie,isLoadingSessionMessages:De,sendMessage:Le,handleInitialTaskClick:Nt,markWidgetOpened:zt,startSession:z,startNewChat:Me,isReady:Se,startRecording:Ue,stopRecording:Ke,handleRetry:Fe,isValidFile:gt,sendMessageFeedback:ut,clearElicitationState:je,sendSessionFeedback:rt,getPastSessions:Be}=Op({environment:n.environment,connectionType:n.connectionType,baseUrl:n.baseUrl?n.baseUrl:void 0,context:n?.context,...n?.authToken&&{authToken:n.authToken},...n?.force&&{force:n.force},channel:Rp(n.displayMode)}),Ge=We(Fe),ke=We(ut),Yt=We(je),_t=We(U=>{z({sessionId:U})}),rn=We(()=>{Me()}),[on,xn]=V(!1),[Tn,Zr]=V([]),[At,pr]=V(!0),fr=X(Be);$(()=>{fr.current=Be});const Ht=ue(async()=>{pr(!0);try{const U=await fr.current();Zr(U)}catch{}finally{pr(!1)}},[]),Jr=ue(async()=>{xn(!0),await Ht()},[Ht]),Qr=ue(()=>{xn(!1)},[]),[gr,_r]=V(!1),$t=ue(()=>_r(U=>!U),[]);$(()=>{_!=="full"||He!=="user"||Ht()},[_,He,re,Ht]),$(()=>{if(t){if(pe.current!==t){const U=j.getState();qh(t),Jh(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&&Se&&!v.current&&(v.current=!0,z({forceNewSession:!1}))}},[e,Se,t]),$(()=>{e&&zt()},[e]),$(()=>{Um([ec])},[]),$(()=>()=>{s()},[]),$(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||Ne(!0)},[n.theme?.upfrontConsent,t]);const Er=ue(()=>{Ec(t,hs),Ne(!1)},[t]),eo=We(()=>{n.feedback&&!ms(t,_c)?W(!0):n.onClose()}),yr=We(async(U,ve)=>{await rt(U,ve),W(!1),n.onClose()}),kn=We(()=>{W(!1),n.onClose()}),sn=We(()=>{Ec(t,_c),W(!1),n.onClose()}),Sr=ue(()=>{W(!1)},[]),vr=ie.length>0,On=ie.length===1,N=ae(()=>{const U=ie[ie.length-1],ve=U?.tool_keys?.[U.tool_keys.length-1];if(!ve)return null;const de=Ie[ve];return de?.active?{...de,tool_key:ve}:null},[ie,Ie]),O=ae(()=>(re?J[re]:void 0)??Te??n?.initialMessage??null,[re,J,Te,n?.initialMessage]),M=ae(()=>!!O?.text||!!O?.suggestions?.length,[O]),I=ae(()=>M&&ie?.length===0&&!De,[ie,M,De]),q=ae(()=>N?N.component===A.SYNAPSE_COMPONENTS.MOBILE||N.component===A.SYNAPSE_COMPONENTS.OTP||N.component===A.SYNAPSE_COMPONENTS.EMAIL:!1,[N]),{scrollAreaRef:oe,messagesEndRef:le,showScrollButton:he,scrollToBottom:Pe}=Dp({messageCount:ie.length,isStreaming:L,isFirstMessage:On,resolvedMode:_}),qe=Ae===ge.CONNECTED,xe=Z||L,Oe=ae(()=>B===ye.IDLE?null:B===ye.LISTENING?"Listening...":B===ye.PROCESSING?"Processing...":B===ye.TRANSCRIBING?"Transcribing...":null,[B]),Je=Oe&&B!==ye.IDLE?Oe:Z||L?"Please wait for the response...":"Type a reply\u2026",ht=We(async(U,ve)=>{if(xe)return;const de=ve?Nt:Le,ze=U?.message??u;w.length>0?(await de({files:w,message:ze.trim()}),T([]),C(!1)):ze.trim()?await de({...U,message:ze.trim()}):U?.resend?await de(U):U&&await de(U),p(""),g(!1),C(!1)}),It=We(U=>ht(U,I)),Ct=We(U=>ht(U,!0)),Bt=We(U=>{if(U&&U.length>0){const ve=U.filter(ze=>gt(ze));if(ve.length===0)return;const de=fc(ve,w.length);if(de){K(de);return}U=ve}T(ve=>(C((ve?.length??0)+(U?.length??0)>0),[...ve,...U]))}),Qe=ue(U=>{T(ve=>{const de=ve.filter((ze,xt)=>xt!==U);return C(de.length>0),de})},[]),ee=We(async()=>{if(E)await Ke(),g(!1);else{if(xe)return;try{await Ue(),g(!0)}catch{}}}),at=We(U=>{p(U)}),et=ae(()=>({value:u,onChange:at,onSend:ht,onFileChange:Bt,onRemoveFile:Qe,onRecording:ee,isRecording:E,hasAttachment:b,attachmentFiles:w,isDisabled:xe,placeholder:Je,recordingStatus:B,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d}),[u,at,ht,Bt,Qe,ee,E,b,w,xe,Je,B,n.allowed,h,d]),Et=ae(()=>n.feedback?{isOpen:D,config:n.feedback,onSubmit:yr,onSkip:kn,onClose:Sr,onDontShowAgain:sn}:void 0,[n.feedback,D,yr,kn,Sr,sn]),Mt=ae(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Er}:void 0,[n.theme?.upfrontConsent,G,Er]);return{showScrollButton:he,toggleDisplayMode:m,resolvedMode:_,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:le,startNewConnection:se,showRetryButton:_e,clearError:F,error:ce,sessionId:re,activeElicitation:N,inConversation:vr,isFirstMessage:On,isEmptyChat:I,isAuthComponent:q,isConnected:qe,isComposerDisabled:xe,isLoadingSessionMessages:De,initialMessage:O,incomingMessages:ie,sendMessageFeedback:ke,clearElicitationState:Yt,handleRetry:Ge,handleChatSendMessage:It,handleEmptyStateSendMessage:Ct,handleSelectSession:_t,handleStartNewChat:rn,scrollToBottom:Pe,handleClose:eo,chatComposerProps:et,feedbackModalProps:Et,consentModalProps:Mt,isSessionDrawerOpen:on,pastSessions:Tn,isLoadingPastSessions:At,openSessionDrawer:Jr,closeSessionDrawer:Qr,userLevel:He,isSidebarCollapsed:gr,toggleSidebar:$t,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c}}function tn(){return tn=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},tn.apply(this,arguments)}const Up=["children","options"],yc=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce((e,t)=>(e[t.toLowerCase()]=t,e),{class:"className",for:"htmlFor"}),Sc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Fp=["style","script","pre"],Vp=["src","href","data","formAction","srcDoc","action"],jp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,zp=/\n{2,}$/,vc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Yp=/^ *> ?/gm,Hp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,$p=/^ {2,}\n/,Bp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,bc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,wc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Gp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,Wp=/^(?:\n *)*\n/,Kp=/\r\n?/g,qp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Xp=/^\[\^([^\]]+)]/,Zp=/\f/g,Jp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,Qp=/^\s*?\[(x|\s)\]/,Nc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,xc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,ef=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Tc=/^<!--[\s\S]*?(?:-->)/,tf=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,nf=/^\{.*\}$/,rf=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,of=/^<([^ >]+[:@\/][^ >]+)>/,sf=/-([a-z])?/gi,kc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,af=/^[^\n]+(?: \n|\n{2,})/,lf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,cf=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,df=/^\[([^\]]*)\] ?\[([^\]]*)\]/,uf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,hf=/\t/g,mf=/(^ *\||\| *$)/g,pf=/^ *:-+: *$/,ff=/^ *:-+ *$/,gf=/^ *-+: *$/,$r=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Br="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",_f=RegExp(`^([*_])\\1${$r(1)}${Br}\\1\\1(?!\\1)`),Ef=RegExp(`^([*_])${$r(0)}${Br}\\1(?!\\1)`),yf=RegExp(`^(==)${$r(0)}${Br}\\1`),Sf=RegExp(`^(~~)${$r(0)}${Br}\\1`),vf=/^(:[a-zA-Z0-9-_]+:)/,bf=/^\\([^0-9A-Za-z\s])/,wf=/\\([^0-9A-Za-z\s])/g,Nf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Cf=/^\n+/,xf=/^([ \t]*)/,Tf=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Oc(e){return"( *)("+(e===1?gs:_s)+") +"}const Rc=Oc(1),Ac=Oc(2);function Ic(e){return RegExp("^"+(e===1?Rc:Ac))}const kf=Ic(1),Of=Ic(2);function Mc(e){return RegExp("^"+(e===1?Rc:Ac)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Rf=Mc(1),Af=Mc(2);function Pc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Dc=Pc(1),Lc=Pc(2);function Uc(e,t){const n=t===1,r=n?Dc:Lc,o=n?Rf:Af,i=n?kf:Of;return{t:s=>i.test(s),o:Cn(function(s,a){const c=Tf.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(zp,`
41
41
  `).match(o);let u=!1;return{items:h.map(function(p,E){const g=i.exec(p)[0].length,f=RegExp("^ {1,"+g+"}","gm"),S=p.replace(f,"").replace(i,""),m=E===h.length-1,_=S.indexOf(`
42
42
 
43
- `)!==-1||m&&u;u=_;const y=c.inline,O=c.list;let T;c.list=!0,_?(c.inline=!1,T=dr(S)+`
43
+ `)!==-1||m&&u;u=_;const y=c.inline,k=c.list;let x;c.list=!0,_?(c.inline=!1,x=ur(S)+`
44
44
 
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,"")+`
45
+ `):(c.inline=!0,x=ur(S));const w=a(x,c);return c.inline=y,c.list=k,w}),ordered:n,start:d}},l:(s,a,c)=>e(s.ordered?"ol":"ul",{key:c.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,c))}))}}const If=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Mf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function Fc(e){return typeof e=="string"}function ur(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 Pf(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 hr(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 Df(e){return gf.test(e)?"right":pf.test(e)?"center":ff.test(e)?"left":null}function Vc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const c=i[i.length-1];c.push.apply(c,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((c,d,h)=>{c.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=c}),a(),n.inTable=o,i}function Lf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(mf,"").split("|").map(Df):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
+ `).map(function(d){return Vc(d,a,c,!0)})})(e[3],t,n):[],i=Vc(e[1],t,n,!!o.length);return n.inline=!1,o.length?{align:r,cells:o,header:i,type:"25"}:{children:i,type:"21"}}function jc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function Cn(e){return e.inline=1,e}function nn(e){return Cn(function(t,n){return n.inline?e.exec(t):null})}function jt(e){return Cn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Rt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Wr(e){return Cn(function(t){return e.exec(t)})}const Uf=/(javascript|vbscript|data(?!:image)):/i;function Ff(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Uf.test(t))return null}catch{return null}return e}function wt(e){return e&&e.replace(wf,"$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 Vf(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 jf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Es=(e,t,n)=>({children:Kr(t,e[2],n)});function ys(){return{}}function Ss(){return null}function zf(...e){return e.filter(Boolean).join(" ")}function vs(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function Yf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?tn({},Sc,t.namedCodesToUnicode):Sc;const n=t.slugify||hr,r=t.sanitizer||Ff,o=t.createElement||tt,i=[vc,bc,wc,t.enforceAtxHeadings?Cc:Nc,xc,kc,Dc,Lc],s=[...i,af,ps,Tc,fs];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function c(m,_,...y){const k=vs(t.overrides,m+".props",{});return o((function(x,w){const T=vs(w,x);return T?typeof T=="function"||typeof T=="object"&&"render"in T?T:vs(w,x+".component",x):x})(m,t.overrides),tn({},_,k,{className:zf(_?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(Jp,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=uf.test(m)===!1);const y=f(g(_?m:ur(m).replace(Cf,"")+`
47
47
 
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(`
48
+ `,{inline:_}));for(;Fc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(_?"span":"div");let x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?c("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(jp);return y?y.reduce(function(k,x){const w=x.indexOf("=");if(w!==-1){const T=(function(D){return D.indexOf("-")!==-1&&D.match(tf)===null&&(D=D.replace(sf,function(W,G){return G.toUpperCase()})),D})(x.slice(0,w)).trim(),v=(function(D){const W=D[0];return(W==='"'||W==="'")&&D.length>=2&&D[D.length-1]===W?D.slice(1,-1):D})(x.slice(w+1).trim()),b=yc[T]||T;if(b==="ref")return k;const C=k[b]=(function(D,W,G,Ne){return W==="style"?(function(pe){const se=[];let _e="",F=!1,ce=!1,Ae="";if(!pe)return se;for(let Z=0;Z<pe.length;Z++){const L=pe[Z];if(L!=='"'&&L!=="'"||F||(ce?L===Ae&&(ce=!1,Ae=""):(ce=!0,Ae=L)),L==="("&&_e.endsWith("url")?F=!0:L===")"&&F&&(F=!1),L!==";"||ce||F)_e+=L;else{const K=_e.trim();if(K){const re=K.indexOf(":");if(re>0){const Te=K.slice(0,re).trim(),J=K.slice(re+1).trim();se.push([Te,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();se.push([L,K])}}return se})(G).reduce(function(pe,[se,_e]){return pe[se.replace(/(-[a-z])/g,F=>F[1].toUpperCase())]=Ne(_e,D,se),pe},{}):Vp.indexOf(W)!==-1?Ne(wt(G),D,W):(G.match(nf)&&(G=wt(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,T,v,r);typeof C=="string"&&(ps.test(C)||fs.test(C))&&(k[b]=d(C.trim()))}else x!=="style"&&(k[yc[x]||x]=!0);return k},{}):null}const u=[],p={},E={0:{t:[">"],o:Rt(vc),i:1,u(m,_,y){const[,k,x]=m[0].replace(Yp,"").match(Hp);return{alert:k,children:_(x,y)}},l(m,_,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),hr),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,_(m.children,y))}},1:{t:[" "],o:Wr($p),i:1,u:ys,l:(m,_,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Rt(Bp),i:1,u:ys,l:(m,_,y)=>c("hr",{key:y.key})},3:{t:[" "],o:Rt(wc),i:0,u:m=>({lang:void 0,text:wt(ur(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>c("pre",{key:y.key},c("code",tn({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Rt(bc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:jt(Gp),i:3,u:m=>({text:wt(m[2])}),l:(m,_,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:Rt(qp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Ss},7:{t:["[^"],o:nn(Xp),i:1,u:m=>({target:"#"+n(m[1],hr),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:nn(Qp),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:Rt(t.enforceAtxHeadings?Cc:Nc),i:1,u:(m,_,y)=>({children:Kr(_,m[2],y),id:n(m[2],hr),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:Rt(xc),i:1,u:(m,_,y)=>({children:Kr(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Wr(ps),i:1,u(m,_,y){const[,k]=m[3].match(xf),x=RegExp("^"+k,"gm"),w=m[3].replace(x,""),T=a(s,w)?jf:Kr,v=m[1].toLowerCase(),b=Fp.indexOf(v)!==-1,C=(b?v:m[1]).trim(),D={attrs:h(C,m[2]),noInnerParse:b,tag:C};if(y.inAnchor=y.inAnchor||v==="a",b)D.text=m[3];else{const W=y.inHTML;y.inHTML=!0,D.children=T(_,w,y),y.inHTML=W}return y.inAnchor=!1,D},l:(m,_,y)=>c(m.tag,tn({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:Wr(fs),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>c(m.tag,tn({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Wr(Tc),i:1,u:()=>({}),l:Ss},14:{t:["!["],o:jt(Mf),i:1,u:m=>({alt:wt(m[1]),target:wt(m[2]),title:wt(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:nn(If),i:3,u:(m,_,y)=>({children:Vf(_,m[1],y),target:wt(m[2]),title:wt(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:nn(of),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:nn(rf),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Uc(c,1),33:Uc(c,2),19:{t:[`
50
+ `],o:Rt(Wp),i:3,u:ys,l:()=>`
51
+ `},21:{o:Cn(function(m,_){if(_.inline||_.simple||_.inHTML&&m.indexOf(`
52
52
 
53
53
  `)===-1&&_.prevCapture.indexOf(`
54
54
 
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};
55
+ `)===-1)return null;let y="",k=0;for(;;){const w=m.indexOf(`
56
+ `,k),T=m.slice(k,w===-1?void 0:w+1);if(a(i,T)||(y+=T,w===-1||!T.trim()))break;k=w+1}const x=ur(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,_,y)=>c("p",{key:y.key},_(m.children,y))},22:{t:["["],o:nn(lf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:jt(cf),i:0,u:m=>({alt:m[1]?wt(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:nn(df),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:Rt(kc),i:1,u:Lf,l(m,_,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(x,w){return c("th",{key:w,style:jc(k,w)},_(x,y))}))),c("tbody",null,k.cells.map(function(x,w){return c("tr",{key:w},x.map(function(T,v){return c("td",{key:v,style:jc(k,v)},_(T,y))}))})))}},27:{o:Cn(function(m,_){let y;return Gr(m,":")&&(y=vf.exec(m)),y||Nf.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(ef,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:jt(_f),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:jt(Ef),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:jt(bf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:jt(yf),i:3,u:Es,l:(m,_,y)=>c("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:jt(Sf),i:3,u:Es,l:(m,_,y)=>c("del",{key:y.key},_(m.children,y))}};t.disableParsingRawHTML===!0&&(delete E[11],delete E[13]);const g=(function(m){var _=Object.keys(m);function y(k,x){var w=[];if(x.prevCapture=x.prevCapture||"",k.trim())for(;k;)for(var T=0;T<_.length;){var v=_[T],b=m[v];if(!b.t||Pf(k,x,b.t)){var C=b.o(k,x);if(C&&C[0]){k=k.substring(C[0].length);var D=b.u(C,y,x);x.prevCapture+=C[0],D.type||(D.type=v),w.push(D);break}T++}else T++}return x.prevCapture="",w}return _.sort(function(k,x){return m[k].i-m[x].i||(k<x?-1:1)}),function(k,x){return y((function(w){return w.replace(Kp,`
57
+ `).replace(Zp,"").replace(hf," ")})(k),x)}})(E),f=(function(m,_){return function y(k,x={}){if(Array.isArray(k)){const w=x.key,T=[];let v=!1;for(let b=0;b<k.length;b++){x.key=b;const C=y(k[b],x),D=Fc(C);D&&v?T[T.length-1]+=C:C!==null&&T.push(C),v=D}return x.key=w,T}return(function(w,T,v){const b=m[w.type].l;return _?_(()=>b(w,T,v),w,T,v):b(w,T,v)})(k,y,x)}})(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,hr),key:m.identifier},m.identifier,f(g(m.footnote,{inline:!0})))}))):S}const Hf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,c={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(c[s]=o[s]);return c})(e,Up);return Dt(Yf(t??"",n),r)},$f={disableParsingRawHTML:!0,forceBlock:!0};function Bf({children:e}){return l(Hf,{options:$f,children:e})}const qr=Wt(Bf);function zc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?l("div",{onClick:i?void 0:o,className: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 Gf=nt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Wf=nt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),Kf=nt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),qf=nt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Xf=nt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function $e({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 mr({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($e,{className:"h-8 w-20 rounded-full"}),l($e,{className:"h-8 w-24 rounded-full"}),l($e,{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($e,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l($e,{className:"h-3 w-3/4 rounded"}),l($e,{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($e,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l($e,{className:"h-9 w-full rounded-lg"}),l($e,{className:"h-9 w-full rounded-lg"}),l($e,{className:"h-9 w-full rounded-lg"})]}),l($e,{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($e,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l($e,{className:"h-3 w-3/4 rounded"}),l($e,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l($e,{className:"h-3 w-full rounded"}),l($e,{className:"h-3 w-5/6 rounded"})]}),l($e,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Xr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Zf({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=V([]),[a,c]=V({}),[d,h]=V(!1),[u,p]=V(5),E=n.component,g=n.disabled,f=ae(()=>n.input,[n.input]);$(()=>{E===A.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 b=>{h(!0),await r({message:b.value,messageId:e,toolCalled:!0,selectedComponent:b,tool_key:t})},m=async(b,C,D,W=!0)=>{await r({toolCalled:W,selectedComponent:b,selected_id:b.doctor_id,message:C,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})},k=()=>{const b=E===A.SYNAPSE_COMPONENTS.MULTI&&f?.options;return b?Array.isArray(b)?b.map((C,D)=>({id:`option-${D}`,label:C.label,value:C.value})):Object.keys(b).map((C,D)=>({id:`option-${D}`,label:C,value:C})):[]},x=ae(()=>{if(E===A.SYNAPSE_COMPONENTS.DOCTOR_CARD)return f?.doctors?.filter(b=>!!b&&!!b.doctor_id)},[E,f?.doctors]);if(!E)return null;const w=E===A.SYNAPSE_COMPONENTS.PILL?f?.options:void 0,T=E===A.SYNAPSE_COMPONENTS.CARD?f?.cards:void 0,v=E===A.SYNAPSE_COMPONENTS.MEDIA_CARD?f?.media_card:void 0;return l("div",{className:"flex justify-end",children:[w&&l("div",{className:`flex ${w.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[w.slice(0,u).map((b,C)=>l(zc,{disabled:g||o||d,text:b?.label||"",onClick:()=>S(b),className:"cursor-pointer"},C)),w.length>u&&l("button",{type:"button",disabled:g||o||d,onClick:()=>p(b=>b+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(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,w.length-u)," more"]})]}),E===A.SYNAPSE_COMPONENTS.MULTI&&f?.options&&l(Xe,{fallback:l(mr,{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(Gf,{options:k(),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"})]})}),x&&x.length>0?l(Xe,{fallback:l(mr,{variant:"card"}),children:l(Wf,{count:x.length>1?x.length+1:x.length,renderItem:(b,C)=>{if(x.length>1&&b===x.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(jh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const D=x[b];return l(Xe,{fallback:l(mr,{variant:"card"}),children:l(Kf,{doctor:D,doctorDetails:a?.[D.doctor_id],disabled:o,onSelect:m,isActive:C})},D.doctor_id)}})}):null,T&&l(Xe,{fallback:l(mr,{variant:"card"}),children:l(qf,{cards:T,onSelect:async b=>{await r({...b,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:g||o})}),v&&l(Xe,{fallback:l(mr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(Xf,{card:v})})})]})}function Yc({userFeedback:e,onToggleFeedback:t}){if(e===A.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(A.USER_FEEDBACK.LIKE),children:l(vl,{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(A.USER_FEEDBACK.DISLIKE),children:l(bl,{className:"h-3 w-3"})})]})});if(e===A.USER_FEEDBACK.LIKE||e===A.USER_FEEDBACK.DISLIKE){const n=e===A.USER_FEEDBACK.LIKE?vl:bl;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 Jf({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===we.USER,[m,_]=V(A.USER_FEEDBACK.NONE),y=j(w=>w.isStreaming),k=w=>{_(w),u(w,e)},x=!!(n?.trim()||r&&r.length>0||d||i||a);return l(me,{children:[x&&l("div",{className: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(Zt,{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(ls,{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!==A.USER_FEEDBACK.NONE)&&l(Yc,{userFeedback:m,onToggleFeedback:k}),g&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(Ee,{variant:"link",size:"sm",className:"h-6 px-0 text-[12px] font-medium text-primary border-b border-dashed border-primary rounded-none bg-transparent no-underline hover:no-underline hover:bg-transparent active:bg-transparent focus-visible:bg-transparent rounded-none",onClick:()=>{const w=s[s.length-1];w&&c[w]?.active&&E(w,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(w=>{const T=c[w];return T?l(Zf,{messageId:e,tool_key:w,entry:T,onSendMessage:h,disabled:p||T.disabled},w):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(Zt,{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(Yc,{userFeedback:m,onToggleFeedback:k})]})})})]})}const Qf=Wt(Jf);function eg({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(Zt,{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(zc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}const tg=[];function ng({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(eg,{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(Qf,{id:u.id,role:u.role,content:u.content,files:u.files||tg,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(og,{})]})}const rg=Wt(ng);function og(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(Zt,{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 Hc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=dc(),[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 sg=nt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function ig({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:k,incomingMessages:x,sendMessageFeedback:w,clearElicitationState:T,handleRetry:v,scrollToBottom:b,chatComposerProps:C,isComposerDisabled:D,voiceAgentState:W,isMuted:G,isVoiceAgentActive:Ne,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:_e,handleClose:F,isSessionDrawerOpen:ce,pastSessions:Ae,isLoadingPastSessions:B,openSessionDrawer:Z,closeSessionDrawer:L,userLevel:K,isSidebarCollapsed:re,toggleSidebar:Te,feedbackModalProps:J,consentModalProps:Ie,handleChatSendMessage:He,handleEmptyStateSendMessage:ie,handleSelectSession:De,handleStartNewChat:Le,sidePanelMode:Nt,sidePanelWidth:zt,side:z,onSidePanelPushChange:Me}=Lp({isOpen:e,agentId:t,config:n});$(()=>{x.length||b("auto")},[x.length,b]);const Se=ae(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Ue=ae(()=>o==="full"&&K==="user"?l(lc,{variant:"sidebar",sessions:Ae,activeSessionId:p,onSelectSession:De,onNewChat:Le,isCollapsed:re,onToggle:Te,isLoading:B}):void 0,[o,K,Ae,p,De,Le,re,Te,B]),Ke=ae(()=>({onRetry:v,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:f}),[v,d,c,h,u,f]),Fe=ae(()=>({onClose:F,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:Le,showStartNewChatButton:c,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:Z}),[F,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,Le,c,n.resize,r,Z]),gt=ae(()=>l(lc,{variant:"drawer",isOpen:ce,onClose:L,sessions:Ae,activeSessionId:p,onSelectSession:De,onNewChat:Le,isLoading:B}),[ce,L,Ae,p,De,Le,B]);return l(Mm,{enabled:!!n.resize,children:l(rc,{value:Fe,children:l(ic,{isOpen:e,feedbackModal:J,consentModal:Ie,sessionId:p,environment:n.environment,mode:o,sidePanelMode:Nt,sidePanelWidth:zt,side:z,onSidePanelPushChange:Me,theme:n.theme,isAuthComponent:g,activeElicitation:E,voiceAgentState:W,chatComposer:C,sessionDrawer:gt,sidebar:Ue,fullScreenEmptyState:_?ut=>l(fp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ie,disabled:D,composer:ut.composer,composerFooter:ut.composerFooter,connectionBanner:l(Hc,{...Ke})}):void 0,children:Ne?l(Xe,{fallback:l($c,{}),children:l(sg,{state:W,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:_e,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l(Xe,{fallback:l($c,{}),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(cl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[l("div",{className:"flex-1"}),l("div",{className: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(ym,{}):l(me,{children:[m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:Se}),l(rg,{messages:x,onSendMessage:He,onToggleFeedback:w,onClearElicitationState:T,isAuthComponent:g,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!f})]}),l("div",{ref:s})]})]})}),a&&l("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:l(Ee,{onClick:()=>b("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:l(Wo,{className:"w-5 h-5 text-text-primary"})})}),l(Hc,{className:"mt-2",...Ke})]})})})})})}function $c(){return l("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[l("div",{className:"flex-1 p-6 space-y-4",children:[l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),l("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Bc(e){return!!e&&e.startsWith("ResizeObserver loop")}function bs(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 ag extends lt{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:bs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(dg,{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 lg({error:e}){throw e}function cg(e){const[t,n]=V(null);return $(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Bc(i?.message)||Bc(i?.error?.message)||(i?.error?n(bs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(bs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(ag,{...e,children:t?l(lg,{error:t}):e.children})}function dg({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:c}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ae(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]),E=ae(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return l(rc,{value:E,children:l(ic,{isOpen:!0,environment:u,mode:a??"widget",theme:c,children:l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:l("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:l("div",{className:"w-full max-w-[320px] text-center",children:[l("div",{className:"mx-auto mb-4 grid place-items-center",children:l("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:l(Uh,{className:"h-8 w-8",style:{color:c?.primary??"hsl(var(--primary))"}})})}),l("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),l("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),l("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",p].join(" "),children:e?.message||String(e)}),l("div",{className:"mt-5 flex items-center justify-center gap-3",children:l(Ee,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(Ih,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function ug({agentId:e,config:t}){const[n,r]=V(t.displayMode==="full");$(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(cg,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:l(Qh,{children:l(ig,{isOpen:n,agentId:e,config:{...t,environment:t.environment??"production",onClose:o,title:t.title??"Medi Clinic",iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",theme:t.theme}})})})}const Gc=(e,t,n)=>{const r=n||{},o=yd(e);return o.render(l(me,{children:l(ug,{agentId:t,config:r})})),o},hg=e=>{try{const t=sessionStorage.getItem(cr(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Wc=e=>{const{refreshToken:t,sessToken:n}=hg(e.agentId);return t&&n?Promise.resolve(null):A.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Kc=e=>A.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Gc,window.fetchAgentConfig=Kc,window.prefetchAuth=Wc);export{X as A,Ee as B,Wo as C,te as D,_l as F,El as I,Ko as M,Wt as N,un as P,Oo as R,cs as S,ae as T,bn as X,mt as _,A as a,P as b,Ye as c,V as d,me as e,Kt as f,Kc as fetchAgentConfig,Si as g,hn as h,Lt as i,Ft as j,Ep as k,xl as l,ss as m,Kl as n,is as o,_p as p,Wc as prefetchAuth,ue as q,kl as r,Gc as renderMedAssist,qr as s,hc as t,l as u,Zt as v,yp as w,Tl as x,$ as y,Ol as z};