@eka-care/medassist-widget 0.1.134-0 → 0.1.135-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/medassist-widget.js +9 -9
- package/package.json +1 -1
package/dist/medassist-widget.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Qc=Object.defineProperty;var ed=(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)=>ed(e,typeof t!="symbol"?t+"":t,n);var Pn,Z,Ts,Ut,xs,Cs,ks,ro,Nr,Dn,Os,oo,so,io,Rs,Tr={},xr=[],td=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ln=Array.isArray;function St(e,t){for(var n in t)e[n]=t[n];return e}function ao(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function 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?Pn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return Un(e,s,r,o,null)}function Un(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ts,__i:-1,__u:0};return o==null&&Z.vnode!=null&&Z.vnode(i),i}function As(){return{current:null}}function me(e){return e.children}function lt(e,t){this.props=e,this.context=t}function dn(e,t){if(t==null)return e.__?dn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?dn(e):null}function nd(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=St({},t);i.__v=t.__v+1,Z.vnode&&Z.vnode(i),co(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??dn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Us(r,i,o),t.__e=t.__=null,i.__e!=n&&Is(i)}}function Is(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}),Is(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Ut.push(e)&&!Cr.__r++||xs!=Z.debounceRendering)&&((xs=Z.debounceRendering)||Cs)(Cr)}function Cr(){try{for(var e,t=1;Ut.length;)Ut.length>t&&Ut.sort(ks),e=Ut.shift(),t=Ut.length,nd(e)}finally{Ut.length=Cr.__r=0}}function Ms(e,t,n,r,o,i,s,a,l,d,h){var u,p,_,f,g,b,m,E=r&&r.__k||xr,y=t.length;for(l=rd(n,t,E,l,y),u=0;u<y;u++)(_=n.__k[u])!=null&&(p=_.__i!=-1&&E[_.__i]||Tr,_.__i=u,b=co(e,_,p,o,i,s,a,l,d,h),f=_.__e,_.ref&&p.ref!=_.ref&&(p.ref&&ho(p.ref,null,_),h.push(_.ref,_.__c||f,_)),g==null&&f!=null&&(g=f),(m=!!(4&_.__u))||p.__k===_.__k?(l=Ps(_,l,e,m),m&&p.__e&&(p.__e=null)):typeof _.type=="function"&&b!==void 0?l=b:f&&(l=f.nextSibling),_.__u&=-7);return n.__e=g,l}function rd(e,t,n,r,o){var i,s,a,l,d,h=n.length,u=h,p=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=Un(null,s,null,null,null):Ln(s)?s=e.__k[i]=Un(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Un(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,l=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=od(s,n,l,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?p--:d==l+1?p++:(d>l?p--:p++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=dn(a)),Vs(a,a));return r}function Ps(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=Ps(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function It(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ln(e)?e.some(function(n){It(n,t)}):t.push(e)),t}function od(e,t,n,r){var o,i,s,a=e.key,l=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&l==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&l==d.type)return s}return-1}function Ds(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||td.test(t)?n:n+"px"}function kr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ds(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ds(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Os,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Dn]=r[Dn]:(n[Dn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ls(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Nr]==null)t[Nr]=oo++;else if(t[Nr]<n[Dn])return;return n(Z.event?Z.event(t):t)}}}function co(e,t,n,r,o,i,s,a,l,d){var h,u,p,_,f,g,b,m,E,y,k,x,T,C,S,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=Z.__b)&&h(t);e:if(typeof v=="function")try{if(m=t.props,E=v.prototype&&v.prototype.render,y=(h=v.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(E?t.__c=u=new v(m,k):(t.__c=u=new lt(m,k),u.constructor=v,u.render=id),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),E&&u.__s==null&&(u.__s=u.state),E&&v.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=St({},u.__s)),St(u.__s,v.getDerivedStateFromProps(m,u.__s))),_=u.props,f=u.state,u.__v=t,p)E&&v.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),E&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(E&&v.getDerivedStateFromProps==null&&m!==_&&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(N){N&&(N.__=t)}),xr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),E&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(_,f,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=Z.__r,T=0,E)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),xr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++T<25);u.state=u.__s,u.getChildContext!=null&&(r=St(St({},r),u.getChildContext())),E&&!p&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(_,f)),C=h!=null&&h.type===me&&h.key==null?Fs(h.props.children):h,a=Ms(e,Ln(C)?C:[C],t,n,r,o,i,s,a,l,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(N){if(t.__v=null,l||i!=null)if(N.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(S=i.length;S--;)ao(i[S]);uo(t)}else t.__e=n.__e,t.__k=n.__k,N.then||uo(t);Z.__e(N,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=sd(n.__e,t,n,r,o,i,s,l,d);return(h=Z.diffed)&&h(t),128&t.__u?void 0:a}function uo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(uo))}function Us(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);Z.__c&&Z.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){Z.__e(i,o.__v)}})}function Fs(e){return typeof e!="object"||e==null||e.__b>0?e:Ln(e)?e.map(Fs):e.constructor!==void 0?null:St({},e)}function sd(e,t,n,r,o,i,s,a,l){var d,h,u,p,_,f,g,b=n.props||Tr,m=t.props,E=t.type;if(E=="svg"?o="http://www.w3.org/2000/svg":E=="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((_=i[d])&&"setAttribute"in _==!!E&&(E?_.localName==E:_.nodeType==3)){e=_,i[d]=null;break}}if(e==null){if(E==null)return document.createTextNode(m);e=document.createElementNS(o,E,m.is&&m),a&&(Z.__m&&Z.__m(t,i),a=!1),i=null}if(E==null)b===m||a&&e.data==m||(e.data=m);else{if(i=E=="textarea"&&m.defaultValue!=null?null:i&&Pn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(_=e.attributes[d]).name]=_.value;for(d in b)_=b[d],d=="dangerouslySetInnerHTML"?u=_:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||kr(e,d,null,_,o);for(d in m)_=m[d],d=="children"?p=_:d=="dangerouslySetInnerHTML"?h=_:d=="value"?f=_:d=="checked"?g=_:a&&typeof _!="function"||b[d]===_||kr(e,d,_,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),Ms(t.type=="template"?e.content:e,Ln(p)?p:[p],t,n,r,E=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&dn(n,0),a,l),i!=null)for(d=i.length;d--;)ao(i[d]);a&&E!="textarea"||(d="value",E=="progress"&&f==null?e.removeAttribute("value"):f!=null&&(f!==e[d]||E=="progress"&&!f||E=="option"&&f!=b[d])&&kr(e,d,f,b[d],o),d="checked",g!=null&&g!=e[d]&&kr(e,d,g,b[d],o))}return e}function ho(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){Z.__e(o,n)}}function Vs(e,t,n){var r,o;if(Z.unmount&&Z.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ho(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Z.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Vs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function id(e,t,n){return this.constructor(e,n)}function Fn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],co(t,e=(!r&&n||t).__k=tt(me,null,[e]),o||Tr,Tr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Pn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Us(i,e,s)}function js(e,t){Fn(e,t,js)}function ad(e,t,n){var r,o,i,s,a=St({},e.props);for(i in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)i=="key"?r=t[i]:i=="ref"?o=t[i]:a[i]=t[i]===void 0&&s!=null?s[i]:t[i];return arguments.length>2&&(a.children=arguments.length>3?Pn.call(arguments,2):n),Un(e.type,a,r||e.key,o||e.ref,null)}function bt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,lo(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+Rs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Pn=xr.slice,Z={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(a){e=a}throw e}},Ts=0,lt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=St({},this.state),typeof e=="function"&&(e=e(St({},n),this.props)),e&&St(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),lo(this))},lt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},lt.prototype.render=me,Ut=[],Cs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ks=function(e,t){return e.__v.__b-t.__v.__b},Cr.__r=0,ro=Math.random().toString(8),Nr="__d"+ro,Dn="__a"+ro,Os=/(PointerCapture)$|Capture$/i,oo=0,so=Ls(!1),io=Ls(!0),Rs=0;var ld=0;function c(e,t,n,r,o,i){t||(t={});var s,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?s=t[a]:l[a]=t[a];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ld,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)l[a]===void 0&&(l[a]=s[a]);return Z.vnode&&Z.vnode(d),d}var Mt,ge,mo,zs,un=0,Ys=[],Ce=Z,Hs=Ce.__b,$s=Ce.__r,Bs=Ce.diffed,Gs=Ce.__c,Ws=Ce.unmount,Ks=Ce.__;function qt(e,t){Ce.__h&&Ce.__h(ge,e,un||t),un=0;var n=ge.__H||(ge.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function F(e){return un=1,hn(Xs,e)}function hn(e,t,n){var r=qt(Mt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xs(void 0,t),function(a){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,a);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=ge,!ge.__f)){var o=function(a,l,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,l,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var _=p.__[0];p.__=p.__N,p.__N=void 0,_!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,l,d)||u};ge.__f=!0;var i=ge.shouldComponentUpdate,s=ge.componentWillUpdate;ge.componentWillUpdate=function(a,l,d){if(this.__e){var h=i;i=void 0,o(a,l,d),i=h}s&&s.call(this,a,l,d)},ge.shouldComponentUpdate=o}return r.__N||r.__}function Y(e,t){var n=qt(Mt++,3);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__H.__h.push(n))}function pt(e,t){var n=qt(Mt++,4);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__h.push(n))}function X(e){return un=5,ie(function(){return{current:e}},[])}function po(e,t,n){un=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 ie(e,t){var n=qt(Mt++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function de(e,t){return un=8,ie(function(){return e},t)}function vt(e){var t=ge.context[e.__c],n=qt(Mt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(ge)),t.props.value):e.__}function fo(e,t){Ce.useDebugValue&&Ce.useDebugValue(t?t(e):e)}function cd(e){var t=qt(Mt++,10),n=F();return t.__=e,ge.componentDidCatch||(ge.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=qt(Mt++,11);if(!e.__){for(var t=ge.__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 dd(){for(var e;e=Ys.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Or),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],Ce.__e(n,e.__v)}}}Ce.__b=function(e){ge=null,Hs&&Hs(e)},Ce.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ks&&Ks(e,t)},Ce.__r=function(e){$s&&$s(e),Mt=0;var t=(ge=e.__c).__H;t&&(mo===ge?(t.__h=[],ge.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Or),t.__h.some(_o),t.__h=[],Mt=0)),mo=ge},Ce.diffed=function(e){Bs&&Bs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ys.push(t)!==1&&zs===Ce.requestAnimationFrame||((zs=Ce.requestAnimationFrame)||ud)(dd)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=ge=null},Ce.__c=function(e,t){t.some(function(n){try{n.__h.some(Or),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],Ce.__e(r,n.__v)}}),Gs&&Gs(e,t)},Ce.unmount=function(e){Ws&&Ws(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Or(r)}catch(o){t=o}}),n.__H=void 0,t&&Ce.__e(t,n.__v))};var qs=typeof requestAnimationFrame=="function";function ud(e){var t,n=function(){clearTimeout(r),qs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);qs&&(t=requestAnimationFrame(n))}function Or(e){var t=ge,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),ge=t}function _o(e){var t=ge;e.__c=e.__(),ge=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Xs(e,t){return typeof t=="function"?t(e):t}function Js(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=F({t:{__:n,u:t}}),o=r[0].t,i=r[1];return pt(function(){o.__=n,o.u=t,bo(o)&&i({t:o})},[e,n,t]),Y(function(){return bo(o)&&i({t:o}),e(function(){bo(o)&&i({t:o})})},[e]),n}function bo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function vo(e){e()}function wo(e){return e}function No(){return[!1,vo]}var To=pt;function Rr(e,t){this.props=e,this.context=t}function Xt(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,tt(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Rr.prototype=new lt).isPureReactComponent=!0,Rr.prototype.shouldComponentUpdate=function(e,t){return yo(this.props,e)||yo(this.state,t)};var Zs=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Zs&&Zs(e)};var hd=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=Js({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=hd,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Qs=function(e,t){return e==null?null:It(It(e).map(t))},st={map:Qs,forEach:Qs,count:function(e){return e?It(e).length:0},only:function(e){var t=It(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:It},md=Z.__e;Z.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t)}md(e,t,n,r)};var ei=Z.unmount;function ti(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=Js({},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 ti(r,t,n)})),e}function ni(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ni(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 ri(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 mn(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),ei&&ei(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=ri(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(l):l())};n.__R=s;var a=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ni(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]=ti(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 oi=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 pd(e){return this.getChildContext=function(){return e.context},e.children}function fd(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Fn(tt(pd,{context:t.context},e.__v),t.v)}function si(e,t){var n=tt(fd,{__v:e,h:t});return n.containerInfo=t,n}(mn.prototype=new lt).__a=function(e){var t=this,n=ri(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),oi(t,e,r)):o()};n?n(i):i()}},mn.prototype.render=function(e){this.i=null,this.l=new Map;var t=It(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},mn.prototype.componentDidUpdate=mn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){oi(e,n,t)})};var ii=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,gd=/^(?: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]/,_d=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ed=/[A-Z0-9]/g,yd=typeof document<"u",Sd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Fn(e,t),typeof n=="function"&&n(),e?e.__c:null}function ai(e,t,n){return js(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 li=Z.event;Z.event=function(e){return li&&(e=li(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Co,bd={configurable:!0,get:function(){return this.class}},ci=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||yd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||Sd(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":_d.test(s)&&(s=l):l=s="oninput":i&&gd.test(s)?s=s.replace(Ed,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&o[s=l]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=It(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=It(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",bd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=ii,ci&&ci(e)};var di=Z.__r;Z.__r=function(e){di&&di(e),Co=e.__c};var ui=Z.diffed;Z.diffed=function(e){ui&&ui(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 hi={ReactCurrentDispatcher:{current:{readContext:function(e){return Co.__n[e.__c].props.value},useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:pt,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No}}},vd="18.3.1";function mi(e){return tt.bind(null,e)}function it(e){return!!e&&e.$$typeof===ii}function pi(e){return it(e)&&e.type===me}function fi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Ft(e){return it(e)?ad.apply(null,arguments):e}function ko(e){return!!e.__k&&(Fn(null,e),!0)}function gi(e){return e&&(e.base||e.nodeType===1&&e)||null}var _i=function(e,t){return e(t)},Ei=function(e,t){var n=Z.debounceRendering;Z.debounceRendering=function(o){return o()};var r=e(t);return Z.debounceRendering=n,r},yi=it,Vn={useState:F,useId:go,useReducer:hn,useEffect:Y,useLayoutEffect:pt,useInsertionEffect:To,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:vo,useRef:X,useImperativeHandle:po,useMemo:ie,useCallback:de,useContext:vt,useDebugValue:fo,version:"18.3.1",Children:st,render:xo,hydrate:ai,unmountComponentAtNode:ko,createPortal:si,createElement:tt,createContext:bt,createFactory:mi,cloneElement:Ft,createRef:As,Fragment:me,isValidElement:it,isElement:yi,isFragment:pi,isMemo:fi,findDOMNode:gi,Component:lt,PureComponent:Rr,memo:Xt,forwardRef:ee,flushSync:Ei,unstable_batchedUpdates:_i,StrictMode:me,Suspense:Xe,SuspenseList:mn,lazy:nt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:st,Component:lt,Fragment:me,PureComponent:Rr,StrictMode:me,Suspense:Xe,SuspenseList:mn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi,cloneElement:Ft,createContext:bt,createElement:tt,createFactory:mi,createPortal:si,createRef:As,default:Vn,findDOMNode:gi,flushSync:Ei,forwardRef:ee,hydrate:ai,isElement:yi,isFragment:pi,isMemo:fi,isValidElement:it,lazy:nt,memo:Xt,render:xo,startTransition:vo,unmountComponentAtNode:ko,unstable_batchedUpdates:_i,useCallback:de,useContext:vt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useErrorBoundary:cd,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:pt,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No,version:vd},Symbol.toStringTag,{value:"Module"}));function wd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function Si(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=Si(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():Si(e[o],null)}}}}function Vt(...e){return de(Ro(...e),e)}function Nd(e){const t=Td(e),n=ee((r,o)=>{const{children:i,...s}=r,a=st.toArray(i),l=a.find(Cd);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Td(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(it(o)){const s=Od(o),a=kd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var xd=Symbol("radix.slottable");function Cd(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xd}function kd(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 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)}var Rd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=Rd.reduce((e,t)=>{const n=Nd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Jt=globalThis?.document?pt:()=>{};function Ad(e,t){return hn((n,r)=>t[n][r]??n,e)}var fn=e=>{const{present:t,children:n}=e,r=Id(t),o=typeof n=="function"?n({present:r.isPresent}):st.only(n),i=Vt(r.ref,Md(o));return typeof n=="function"||r.isPresent?Ft(o,{ref:i}):null};fn.displayName="Presence";function Id(e){const[t,n]=F(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,l]=Ad(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Y(()=>{const d=Ar(r.current);i.current=a==="mounted"?d:"none"},[a]),Jt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Ar(d);e?l("MOUNT"):p==="none"||d?.display==="none"?l("UNMOUNT"):l(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Jt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=_=>{const f=Ar(r.current).includes(CSS.escape(_.animationName));if(_.target===t&&f&&(l("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=_=>{_.target===t&&(i.current=Ar(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:de(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Ar(e){return e?.animationName||"none"}function Md(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 bi(e,t=[]){let n=[];function r(i,s){const a=bt(s),l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=vt(_);if(f)return f;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Pd(o,...t)]}function Pd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function jt(e){const t=X(e);return Y(()=>{t.current=e}),ie(()=>(...n)=>t.current?.(...n),[])}var Dd=bt(void 0);function Ld(e){const t=vt(Dd);return e||t||"ltr"}function Ud(e,[t,n]){return Math.min(n,Math.max(t,e))}function zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Fd(e,t){return hn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[vi]=bi(Ao),[Vd,ct]=vi(Ao),wi=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,l]=F(null),[d,h]=F(null),[u,p]=F(null),[_,f]=F(null),[g,b]=F(null),[m,E]=F(0),[y,k]=F(0),[x,T]=F(!1),[C,S]=F(!1),v=Vt(t,D=>l(D)),N=Ld(o);return c(Vd,{scope:n,type:r,dir:N,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:_,onScrollbarXChange:f,scrollbarXEnabled:x,onScrollbarXEnabledChange:T,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:C,onScrollbarYEnabledChange:S,onCornerWidthChange:E,onCornerHeightChange:k,children:c(pn.div,{dir:N,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});wi.displayName=Ao;var Ni="ScrollAreaViewport",Ti=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ct(Ni,n),a=X(null),l=Vt(t,a,s.onViewportChange);return c(me,{children:[c("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),c(pn.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ti.displayName=Ni;var wt="ScrollAreaScrollbar",Io=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return Y(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?c(jd,{...r,ref:t,forceMount:n}):o.type==="scroll"?c(zd,{...r,ref:t,forceMount:n}):o.type==="auto"?c(xi,{...r,ref:t,forceMount:n}):o.type==="always"?c(Mo,{...r,ref:t}):null});Io.displayName=wt;var jd=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),[i,s]=F(!1);return Y(()=>{const a=o.scrollArea;let l=0;if(a){const d=()=>{window.clearTimeout(l),s(!0)},h=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),c(fn,{present:n||i,children:c(xi,{"data-state":i?"visible":"hidden",...r,ref:t})})}),zd=ee((e,t)=>{const{forceMount:n,...r}=e,o=ct(wt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Dr(()=>l("SCROLL_END"),100),[a,l]=Fd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return Y(()=>{if(a==="idle"){const d=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,l]),Y(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const p=()=>{const _=d[h];u!==_&&(l("SCROLL"),s()),u=_};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[o.viewport,i,l,s]),c(fn,{present:n||a!=="hidden",children:c(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:zt(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:zt(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),xi=ee((e,t)=>{const n=ct(wt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=F(!1),a=e.orientation==="horizontal",l=Dr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return gn(n.viewport,l),gn(n.content,l),c(fn,{present:r||i,children:c(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=ct(wt,e.__scopeScrollArea),i=X(null),s=X(0),[a,l]=F({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ai(a.viewport,a.content),h={...r,sizes:a,onSizesChange:l,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,_){return Wd(p,s.current,a,_)}return n==="horizontal"?c(Yd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,_=Ii(p,a,o.dir);i.current.style.transform=`translate3d(${_}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?c(Hd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,_=Ii(p,a);i.current.style.transform=`translate3d(0, ${_}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Yd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarXChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Mr(s.paddingLeft),paddingEnd:Mr(s.paddingRight)}})}})}),Hd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ct(wt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarYChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Mr(s.paddingTop),paddingEnd:Mr(s.paddingBottom)}})}})}),[$d,Ci]=vi(wt),ki=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:d,onWheelScroll:h,onResize:u,...p}=e,_=ct(wt,n),[f,g]=F(null),b=Vt(t,v=>g(v)),m=X(null),E=X(""),y=_.viewport,k=r.content-r.viewport,x=jt(h),T=jt(l),C=Dr(u,10);function S(v){if(m.current){const N=v.clientX-m.current.left,D=v.clientY-m.current.top;d({x:N,y:D})}}return Y(()=>{const v=N=>{const D=N.target;f?.contains(D)&&x(N,k)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[y,f,k,x]),Y(T,[r,T]),gn(f,C),gn(_.content,C),c($d,{scope:n,scrollbar:f,hasThumb:o,onThumbChange:jt(i),onThumbPointerUp:jt(s),onThumbPositionChange:T,onThumbPointerDown:jt(a),children:c(pn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:zt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),m.current=f.getBoundingClientRect(),E.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",_.viewport&&(_.viewport.style.scrollBehavior="auto"),S(v))}),onPointerMove:zt(e.onPointerMove,S),onPointerUp:zt(e.onPointerUp,v=>{const N=v.target;N.hasPointerCapture(v.pointerId)&&N.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=E.current,_.viewport&&(_.viewport.style.scrollBehavior=""),m.current=null})})})}),Ir="ScrollAreaThumb",Oi=ee((e,t)=>{const{forceMount:n,...r}=e,o=Ci(Ir,e.__scopeScrollArea);return c(fn,{present:n||o.hasThumb,children:c(Bd,{ref:t,...r})})}),Bd=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ct(Ir,n),s=Ci(Ir,n),{onThumbPositionChange:a}=s,l=Vt(t,u=>s.onThumbChange(u)),d=X(void 0),h=Dr(()=>{d.current&&(d.current(),d.current=void 0)},100);return Y(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const _=Kd(u,a);d.current=_,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),c(pn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:zt(e.onPointerDownCapture,u=>{const p=u.target.getBoundingClientRect(),_=u.clientX-p.left,f=u.clientY-p.top;s.onThumbPointerDown({x:_,y:f})}),onPointerUp:zt(e.onPointerUp,s.onThumbPointerUp)})});Oi.displayName=Ir;var Po="ScrollAreaCorner",Ri=ee((e,t)=>{const n=ct(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c(Gd,{...e,ref:t}):null});Ri.displayName=Po;var Gd=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ct(Po,n),[i,s]=F(0),[a,l]=F(0),d=!!(i&&a);return gn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),l(h)}),gn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?c(pn.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Mr(e){return e?parseInt(e,10):0}function Ai(e,t){const n=e/t;return isNaN(n)?0:n}function Pr(e){const t=Ai(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Wd(e,t,n,r="ltr"){const o=Pr(n),i=o/2,s=t||i,a=o-s,l=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return Mi([l,d],u)(e)}function Ii(e,t,n="ltr"){const r=Pr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],d=Ud(e,l);return Mi([0,s],[0,a])(d)}function Mi(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 Pi(e,t){return e>0&&e<t}var Kd=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function Dr(e,t){const n=jt(e),r=X(0);return Y(()=>()=>window.clearTimeout(r.current),[]),de(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function gn(e,t){const n=jt(t);Jt(()=>{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 Di=wi,qd=Ti,Xd=Ri;function Jd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var _n={},jn={},Li={},zn={},Yn={},Hn={},Ui;function Do(){if(Ui)return Hn;Ui=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.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 Hn.EventEmitter=e,Hn}var En={},Fi;function $n(){return Fi||(Fi=1,Object.defineProperty(En,"__esModule",{value:!0}),En.DisconnectionReason=En.ConnectionStatus=void 0,En.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},En.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),En}var Vi;function Lo(){if(Vi)return Yn;Vi=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.BaseConnection=void 0;const e=Do(),t=$n();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 Yn.BaseConnection=n,Yn}var ji={},zi;function at(){return zi||(zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=x,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(S,v=e.SynapseErrorCode.UNKNOWN,N={}){super(S);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=v,this.timestamp=new Date,this.cause=N.cause,this.context=N.context,this.hint=N.hint,this.reason=N.reason,this.displayMessage=N.displayMessage||N?.hint||S,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(S,v,N,D){const B=n.makeMessage(v,N,S);super(B,e.SynapseErrorCode.API,{cause:N,context:{status:v,hasBody:!!N},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:S||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=N,this.headers=D}static makeMessage(S,v,N){const D=v instanceof Error?v.message:N;return S&&D?`HTTP ${S}: ${D}`:S?`${S} status code (no body)`:D||"(no status code or body)"}static generate(S,v,N,D){if(!S)return new r({message:N});const B=v?.error,G=B&&typeof B=="object"&&!Array.isArray(B)?B:void 0;switch(S){case 400:return new i(N||"Bad Request",S,G,D);case 401:return new s(N||"Unauthorized",S,G,D);case 403:return new a(N||"Permission Denied",S,G,D);case 404:return new l(N||"Not Found",S,G,D);case 405:return new d(N||"Method Not Allowed",S,G,D);case 429:return new h(N||"Rate Limit Exceeded",S,G,D);case 500:return new u(N||"Internal Server Error",S,G,D);default:return new n(N||"API Error",S,G,D)}}}e.APIError=n;class r extends n{constructor({message:C}={}){super(C||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:C}={}){super(C||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class l extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="NotFoundError"}}e.NotFoundError=l;class d extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONNECTION,S),this.name="ConnectionError"}}e.ConnectionError=p;class _ extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.RECORDING,S),this.name="RecordingError"}}e.RecordingError=_;class f extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.AUTH,S),this.name="AuthenticationError"}}e.AuthenticationError=f;class g extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.FILE,S),this.name="FileError"}}e.FileError=g;class b extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.SESSION,S),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.MESSAGE,S),this.name="MessageError"}}e.MessageError=m;class E extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.STORE,S),this.name="StoreError"}}e.StoreError=E;class y extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONFIGURATION,S),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.VALIDATION,S),this.name="ValidationError"}}e.ValidationError=k;function x(T,C,S,v={}){if(T instanceof C)return T;const N={...v,context:{...T instanceof t?T.context:void 0,...v.context},hint:v.hint??(T instanceof t?T.hint:void 0),reason:v.reason??(T instanceof t?T.reason:void 0),cause:v.cause??T};if(T instanceof t)return new C(T.message,N);const D=T instanceof Error&&T.message?T.message:S;return new C(D,N)}})(ji)),ji}var Yi;function Hi(){if(Yi)return zn;Yi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.WebSocketConnection=void 0;const e=Lo(),t=$n(),n=at();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const l=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(l)}}handleError(s){}handleClose(s){const a=s.wasClean,l=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(l===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):l===1001||l===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):l===4001||l===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):l===4401||l===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(l===4401?"Session token expired":"Session credentials rejected")):l===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):l===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:l,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const l=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(l),l}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return zn.WebSocketConnection=r,zn}var Bn={},$i={},Bi;function Gi(){return Bi||(Bi=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})($i)),$i}var Wi;function Ki(){if(Wi)return Bn;Wi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.SSEConnection=void 0;const e=Lo(),t=$n(),n=Gi(),r=at();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const l=new AbortController;this.activeStreamController=l,this.streamChat(a,l)}postChat(a,l,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(l),signal:d.signal})}async streamChat(a,l){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,l);if(h.status===401&&this.config.auth.onUnauthorized){const f=await this.config.auth.onUnauthorized();if(l.signal.aborted)return;f&&(h=await this.postChat(d,a,l))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),p=new TextDecoder;let _="";for(;;){const{done:f,value:g}=await u.read();if(f)break;_+=p.decode(g,{stream:!0}),_=this.extractJsonObjects(_)}_.trim().length>0&&this.extractJsonObjects(_)}catch(h){if(l.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===l&&(this.activeStreamController=null)}}extractJsonObjects(a){let l=0;for(;l<a.length;){const d=a.indexOf("{",l);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const p=JSON.parse(u);this.handleMessage(p)}catch(p){const _=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(_)}l=h+1}return""}findObjectEnd(a,l){let d=0,h=!1,u=!1;for(let p=l;p<a.length;p++){const _=a[p];if(h){u?u=!1:_==="\\"?u=!0:_==='"'&&(h=!1);continue}if(_==='"')h=!0;else if(_==="{")d++;else if(_==="}"&&(d--,d===0))return p}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Bn.SSEConnection=o,Bn}var qi;function Xi(){return qi||(qi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Hi(),n=Ki(),r=at();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})(Li)),Li}var Gn={},Ji;function Uo(){if(Ji)return Gn;Ji=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix-ws.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Gn.getConfig=r,Gn}var Wn={},Kn={},Zi;function Lr(){if(Zi)return Kn;Zi=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.HttpClient=void 0;const e=at();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const l=this.buildUrl(r,o?.params),d=await fetch(l,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(l){if(s=l,a===i||!(l instanceof TypeError&&l.message==="Failed to fetch"||l instanceof DOMException&&l.name==="AbortError"||l instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Kn.HttpClient=t,Kn}var qn={},Xn={},Qi;function Jn(){if(Qi)return Xn;Qi=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.BaseResource=void 0;let e=class{constructor(t){R(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return Xn.BaseResource=e,Xn}var ea;function ta(){if(ea)return qn;ea=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Session=void 0;const e=Jn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:l}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...l&&{nps_base5:l}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return qn.Session=t,qn}var Zn={},na;function Fo(){if(na)return Zn;na=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.Config=void 0;const e=Jn();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 Zn.Config=t,Zn}var ra={},oa;function sa(){return oa||(oa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Lr(),n=Uo(),r=Fo(),o=new Map,i=(l,d)=>`${l.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(l){const d=l.serverUrl||(0,n.getConfig)(l.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,l.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":l.agentId,...l.channel&&{"x-channel":l.channel}}}),_=new r.Config(p).retrieve(l.agentId);return _.catch(()=>{o.get(h)===_&&o.delete(h)}),o.set(h,_),_}function a(l){const d=o.get(l);return d&&o.delete(l),d}})(ra)),ra}var Qn={},ia;function Vo(){if(ia)return Qn;ia=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.Auth=void 0;const e=Jn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Qn.Auth=t,Qn}var er={},yn={},aa;function jo(){return aa||(aa=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.ErrorType=yn.SYNAPSE_RECOVERY_REASON=void 0,yn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},yn.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),yn}var tr={},la;function zo(){if(la)return tr;la=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.ErrorUtils=void 0;const e=at();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return tr.ErrorUtils=t,tr}var ca={},da;function ua(){return da||(da=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=l;const t=Lr(),n=Uo(),r=zo(),o=Vo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),p=i.get(u);if(p)return p;const _=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),f=new o.Auth(_).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return f.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===f&&i.delete(u)}),i.set(u,f),f}function l(d){const h=i.get(d);return h&&i.delete(d),h}})(ca)),ca}var ha;function Zd(){if(ha)return er;ha=1,Object.defineProperty(er,"__esModule",{value:!0}),er.TokenManager=void 0;const e=at(),t=jo(),n=zo(),r=ua();let o=class{constructor(i,s,a,l){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=l.partnerAuthToken,this.refreshToken=l.refreshToken,this.onTokenExchange=l.onTokenExchange,this._level=l.level,this._userId=l.userId,l.sessToken&&(this.sessToken=l.sessToken,this.httpClient.setAuthorization(l.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(l.serverUrl,a,l.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,l){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,l,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return er.TokenManager=o,er}var nr={},ma;function Qd(){var n;if(ma)return nr;ma=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceResource=void 0;const e=Jn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return nr.VoiceResource=t,nr}var pa;function fa(){if(pa)return Wn;pa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ResourceManager=void 0;const e=Lr(),t=ta(),n=at(),r=Fo(),o=sa(),i=Vo(),s=Zd(),a=Qd();class l{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:p,intent:_,user_location:f,referer:g,...b}=u||{},m=this.tokenManager.userId||h,E={...m&&{user_id:m},...p&&{user_context:p},...(_||Object.keys(b).length>0)&&{session_context:{..._&&{intent:_},...f&&{user_location:f},...b}},...g&&{referer:g}},y=await this.session.create(E);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:_,feedbackReason:f,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:p,feedbacks:_,feedbackReason:f,npsBase5:g})}async callTool(h,u,p,_){return await this.session.callTool(h,u,p,_)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Wn.ResourceManager=l,Wn}var rr={},ga={},_a;function Yo(){return _a||(_a=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)}})(ga)),ga}var Ea={},ya;function eu(){return ya||(ya=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=at();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 l=s[a].url,d=await fetch(l,{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})(Ea)),Ea}var ft={},Sa;function Ur(){if(Sa)return ft;Sa=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=Yo();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 or={},ba;function tu(){if(ba)return or;ba=1,Object.defineProperty(or,"__esModule",{value:!0}),or.AudioManager=void 0;const e=at();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return or.AudioManager=t,or}var va;function wa(){if(va)return rr;va=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.MessageManager=void 0;const e=Yo(),t=eu(),n=Ur(),r=tu(),o=at();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:l,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(l&&l.length>0){const p=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:l,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:l,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:_}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...l&&{audio:l},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},..._&&{initial_prompts:_}};return}const f=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:p})}else s?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},..._&&{initial_prompts:_},...p&&{tool_result:p}}}:l&&l?.audio&&l?.format?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:l?.audio,format:l?.format,...h&&{tool_declined:h},...p&&{tool_result:p}}}:p&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:p}});if(!g){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}f.sendMessage(g)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(l=>{this.sendSocketMessage({urls:l})}).catch(l=>{const d=this.toFileError(l,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,l)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const l={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,l)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,l)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const l={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,l);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const l=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),l={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(l)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const l=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(l),l}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,l=>{const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(l){const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,l,d){return(0,o.normalizeError)(s,o.FileError,a,{context:l,hint:d})}toRecordingError(s,a,l,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:l,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return rr.MessageManager=i,rr}var Na={},Ta;function nu(){return Ta||(Ta=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})(Na)),Na}var sr={},ir={},xa;function ru(){if(xa)return ir;xa=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),l=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(l)};l()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return ir.VoiceAudioAnalyser=t,ir}var Sn={},Ca;function ka(){return Ca||(Ca=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.VOICE_AGENT_EVENTS=Sn.VOICE_AGENT_STATE=void 0,Sn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Sn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Sn}var Oa;function ou(){if(Oa)return sr;Oa=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.VoiceAgent=void 0;const e=Do(),t=ru(),n=at(),r=ka(),o=3e3,i=8,s=3600*1e3,a=600;function l(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const _=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(_),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),_=new RTCPeerConnection({iceServers:p,iceTransportPolicy:"all"});this.pc=_,this.dataChannel=_.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(E,u)),_.ontrack=E=>this.handleRemoteTrack(E),_.onconnectionstatechange=()=>{_.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(_.connectionState==="failed"||_.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},_.oniceconnectionstatechange=()=>{(_.iceConnectionState==="connected"||_.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):_.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const f=await _.createOffer();await _.setLocalDescription(f);const g=this.config.iceGatheringTimeoutMs??o;await l(_,g);const b=E=>({sdp:_.localDescription.sdp,type:_.localDescription.type,pc_id:this.pcId,request_data:{session_id:E.sessionId,token:E.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(b(h))}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(b(y))}else throw E}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,_.signalingState==="closed")return;await _.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(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const f=await this.getCredentials();p=await this.resourceManager.getVoiceIceServers(f.sessionId)}else throw _}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,_=>{_?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return sr.VoiceAgent=d,sr}var Ra;function su(){if(Ra)return jn;Ra=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.SynapseSDK=void 0;const e=Xi(),t=$n(),n=Uo(),r=fa(),o=wa(),i=Ur(),s=Do(),a=at(),l=jo(),d=nu(),h=Yo(),u=ou();class p{constructor(f){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={...f,environment:f.environment||"production"},this.connectionType=f.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const f=await this.resourceManager.refreshBearer();if(!f)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(g){this.emitError(this.toConnectionError(g,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return f}async startSession(f){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,f=void 0),await this.resourceManager.ensureCredentials();const g=f?.session_id?f:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:f,files:g,audio:b,tool_declined:m,tool_id:E,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:f,files:g,audio:b,...m&&{tool_declined:m},...E&&{tool_id:E},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(T){this.emitError(T)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:f,feedback:g,feedbackReason:b});break}}async sendSessionFeedback(f,g){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!f?.length&&!g){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:f,npsBase5:g});break}}on(f,g){this.sdkEventEmitter.on(f,g)}off(f,g){this.sdkEventEmitter.off(f,g)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(f){return await this.resourceManager.getSessionMessages(f)}async callTool(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,f,g,b);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let E={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,E);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:f,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:f,onError:g})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const f=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(f),f}}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(f){if(f instanceof a.APIError){const g=f.reason??(f.status===401||f.status===403?l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:f.error?.msg||f.message,error:f.error,code:f.code,...g&&{reason:g},status:f.status,context:f.context}}return f instanceof a.SynapseError?{message:f.displayMessage||f.message,code:f.code,...f.reason&&{reason:f.reason},context:f.context}:f instanceof Error?{message:f.message}:{message:"An unexpected error occurred"}}emitError(f){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(f))}toSessionError(f,g,b,m){return(0,a.normalizeError)(f,a.SessionError,g,{context:b,hint:m})}async initializeConnection(f){if(this.closeConnection(),!f.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=f;const g=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?g.WEBSOCKET_URL:g.BASE_API_URL,E=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:E||m,auth:{sessionId:f.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(g=>{this.onIncomingSocketMessage(g)}),this.connection.onError(g=>{this.onRealtimeConnectionError(g)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const f=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==f||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(g.code);if(b){await this.handleRecovery(b,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(f){if(f instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(f.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:f.message,code:f.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,f);const g=f instanceof a.APIError?f:this.toConnectionError(f,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const f=this.resourceManager.getSessToken();if(!f){const g=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(g),g}this.messageManager.sendSocketAuthMessage(f)}onIncomingSocketMessage(f){switch(f.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(f);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(f);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(f);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(f);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:f.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const f=this.resourceManager.getLevel();return f?f==="user":!!this.config.authToken}statusOf(f){if(f instanceof a.APIError)return f.status;if(f instanceof a.SynapseError&&typeof f.context?.status=="number")return f.context.status}emitRecoveryError(f,g,b){this.emitError(new a.SessionError(g,{reason:f,cause:b,context:{stage:"connectionRecovery",reason:f}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(f,g){if(f===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(f){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(f){const g=this.statusOf(f);if(g!==403&&g!==401){this.emitError(this.toSessionError(f,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",f)}}async recoverMissingSession(){const f=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!f){this.closeConnection(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(f);await this.connectTo(g);return}catch(g){const b=this.statusOf(g);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);return}try{await this.connectTo(await this.createNewSession())}catch(m){const E=this.statusOf(m);if(E===401||E===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(f){await this.initializeConnection(f),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(f,g,b,m){return(0,a.normalizeError)(f,a.ConnectionError,g,{context:b,hint:m})}scheduleReconnect(f){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(f);return}const g=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(f)}}},g)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return jn.SynapseSDK=p,jn}var Aa={},Ia;function iu(){return Ia||(Ia=1,Object.defineProperty(Aa,"__esModule",{value:!0})),Aa}var Fr={},Ma;function au(){return Ma||(Ma=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.USER_FEEDBACK=void 0,Fr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Fr}var Pa={},Da;function lu(){return Da||(Da=1,Object.defineProperty(Pa,"__esModule",{value:!0})),Pa}var ar={},La;function cu(){if(La)return ar;La=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.ToolCall=void 0;const e=Jn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return ar.ToolCall=t,ar}var Je={},Ua;function du(){if(Ua)return Je;Ua=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.SYNAPSE_EICITATION_STATUS=Je.SYNAPSE_CTA_ACTIONS=Je.SYNAPSE_TOOL_FORMATS=Je.SYNAPSE_TOOL_CALLBACK_NAME=Je.SYNAPSE_COMPONENTS=Je.SYNAPSE_TOOL_NAME=void 0;var e;(function(s){s.MOBILE_VERIFICATION="mobile_verification",s.AVAILABILITY_DATES="availability_dates",s.AVAILABILITY_SLOTS="availability_slots",s.DOCTOR_AVAILABILITY="doctor_availability",s.DOCTOR_DETAILS="doctor_details",s.GET_LOCATION="get_location"})(e||(Je.SYNAPSE_TOOL_NAME=e={}));var t;(function(s){s.MOBILE="mobile_number",s.OTP="otp",s.EMAIL="email_address",s.PILL="pills",s.MULTI="multi",s.DOCTOR_CARD="doctor_card",s.CARD="card",s.MEDIA_CARD="media_card"})(t||(Je.SYNAPSE_COMPONENTS=t={}));var n;(function(s){s.DOCTOR_AVAILABILITY="get_doctor_availability",s.AVAILABILITY_DATES="get_available_dates",s.AVAILABILITY_SLOTS="get_available_slots",s.MOBILE_VERIFICATION="verify_mobile_number",s.DOCTOR_DETAILS="get_doctor_details"})(n||(Je.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Je.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Je.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Je.SYNAPSE_EICITATION_STATUS=i={})),Je}var Fa={},Va;function uu(){return Va||(Va=1,Object.defineProperty(Fa,"__esModule",{value:!0})),Fa}var ja={},za;function hu(){return za||(za=1,Object.defineProperty(ja,"__esModule",{value:!0})),ja}var lr={},Ya;function mu(){if(Ya)return lr;Ya=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(lr.SYNAPSE_CONVERSATION=e={})),lr}var bn={},Ha;function pu(){return Ha||(Ha=1,(function(e){var t=bn&&bn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=bn&&bn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(ka(),e)})(bn)),bn}var $a;function fu(){return $a||($a=1,(function(e){var t=_n&&_n.__createBinding||(Object.create?(function(T,C,S,v){v===void 0&&(v=S);var N=Object.getOwnPropertyDescriptor(C,S);(!N||("get"in N?!C.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return C[S]}}),Object.defineProperty(T,v,N)}):(function(T,C,S,v){v===void 0&&(v=S),T[v]=C[S]})),n=_n&&_n.__exportStar||function(T,C){for(var S in T)S!=="default"&&!Object.prototype.hasOwnProperty.call(C,S)&&t(C,T,S)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=su();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=Hi();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Ki();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Xi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n($n(),e);var l=fa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return l.ResourceManager}}),n(iu(),e);var d=ta();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(au(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=ua();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(lu(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var _=sa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return _.prefetchAgentConfig}});var f=cu();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return f.ToolCall}}),n(du(),e);var g=wa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(Ur(),e),n(uu(),e);var b=Lr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=at();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 E=jo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return E.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return E.SYNAPSE_RECOVERY_REASON}});var y=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(hu(),e);var k=Gi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var x=Ur();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(mu(),e),n(pu(),e)})(_n)),_n}var I=fu();function Ba(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=Ba(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ga(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ba(e))&&(r&&(r+=" "),r+=t);return r}const gu=(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},_u=(e,t)=>({classGroupId:e,validator:t}),Wa=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Vr="-",Ka=[],Eu="arbitrary..",yu=e=>{const t=bu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Su(o);const i=o.split(Vr),s=i[0]===""&&i.length>1?1:0;return qa(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?gu(a,s):s:a||Ka}return n[o]||Ka}}},qa=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const l=qa(e,t+1,o);if(l)return l}const i=n.validators;if(i===null)return;const s=t===0?e.join(Vr):e.slice(t).join(Vr),a=i.length;for(let l=0;l<a;l++){const d=i[l];if(d.validator(s))return d.classGroupId}},Su=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?Eu+r:void 0})(),bu=e=>{const{theme:t,classGroups:n}=e;return vu(n,t)},vu=(e,t)=>{const n=Wa();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];wu(s,t,n,r)}},wu=(e,t,n,r)=>{if(typeof e=="string"){Nu(e,t,n);return}if(typeof e=="function"){Tu(e,t,n,r);return}xu(e,t,n,r)},Nu=(e,t,n)=>{const r=e===""?t:Xa(t,e);r.classGroupId=n},Tu=(e,t,n,r)=>{if(Cu(e)){Ho(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(_u(n,e))},xu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,l]=o[s];Ho(l,Xa(t,a),n,r)}},Xa=(e,t)=>{let n=e;const r=t.split(Vr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Wa(),n.nextPart.set(s,a)),n=a}return n},Cu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,ku=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="!",Ja=":",Ou=[],Za=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Ru=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,d;const h=o.length;for(let g=0;g<h;g++){const b=o[g];if(s===0&&a===0){if(b===Ja){i.push(o.slice(l,g)),l=g+1;continue}if(b==="/"){d=g;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(l);let p=u,_=!1;u.endsWith($o)?(p=u.slice(0,-1),_=!0):u.startsWith($o)&&(p=u.slice(1),_=!0);const f=d&&d>l?d-l:void 0;return Za(i,_,p,f)};if(t){const o=t+Ja,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Za(Ou,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Au=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",l=t.has(s);a||l?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},Iu=e=>({cache:ku(e.cacheSize),parseClassName:Ru(e),sortModifiers:Au(e),...yu(e)}),Mu=/\s+/,Pu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Mu);let l="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:_,baseClassName:f,maybePostfixModifierPosition:g}=n(h);if(u){l=h+(l.length>0?" "+l:l);continue}let b=!!g,m=r(b?f.substring(0,g):f);if(!m){if(!b){l=h+(l.length>0?" "+l:l);continue}if(m=r(f),!m){l=h+(l.length>0?" "+l:l);continue}b=!1}const E=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=_?E+$o:E,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,b);for(let T=0;T<x.length;++T){const C=x[T];s.push(y+C)}l=h+(l.length>0?" "+l:l)}return l},Du=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Qa(n))&&(o&&(o+=" "),o+=r);return o},Qa=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Qa(e[r]))&&(n&&(n+=" "),n+=t);return n},Lu=(e,...t)=>{let n,r,o,i;const s=l=>{const d=t.reduce((h,u)=>u(h),e());return n=Iu(d),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const d=r(l);if(d)return d;const h=Pu(l,n);return o(l,h),h};return i=s,(...l)=>i(Du(...l))},Uu=[],je=e=>{const t=n=>n[e]||Uu;return t.isThemeGetter=!0,t},el=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tl=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Fu=/^\d+\/\d+$/,Vu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ju=/\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$/,zu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vn=e=>Fu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Yt=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Pt=e=>Vu.test(e),$u=()=>!0,Bu=e=>ju.test(e)&&!zu.test(e),nl=()=>!1,Gu=e=>Yu.test(e),Wu=e=>Hu.test(e),Ku=e=>!H(e)&&!$(e),qu=e=>wn(e,al,nl),H=e=>el.test(e),Zt=e=>wn(e,ll,Bu),Go=e=>wn(e,eh,ne),rl=e=>wn(e,sl,nl),Xu=e=>wn(e,il,Wu),jr=e=>wn(e,cl,Gu),$=e=>tl.test(e),cr=e=>Nn(e,ll),Ju=e=>Nn(e,th),ol=e=>Nn(e,sl),Zu=e=>Nn(e,al),Qu=e=>Nn(e,il),zr=e=>Nn(e,cl,!0),wn=(e,t,n)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Nn=(e,t,n=!1)=>{const r=tl.exec(e);return r?r[1]?t(r[1]):n:!1},sl=e=>e==="position"||e==="percentage",il=e=>e==="image"||e==="url",al=e=>e==="length"||e==="size"||e==="bg-size",ll=e=>e==="length",eh=e=>e==="number",th=e=>e==="family-name",cl=e=>e==="shadow",nh=()=>{const e=je("color"),t=je("font"),n=je("text"),r=je("font-weight"),o=je("tracking"),i=je("leading"),s=je("breakpoint"),a=je("container"),l=je("spacing"),d=je("radius"),h=je("shadow"),u=je("inset-shadow"),p=je("text-shadow"),_=je("drop-shadow"),f=je("blur"),g=je("perspective"),b=je("aspect"),m=je("ease"),E=je("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],T=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],S=()=>[$,H,l],v=()=>[vn,"full","auto",...S()],N=()=>[Yt,"none","subgrid",$,H],D=()=>["auto",{span:["full",Yt,$,H]},Yt,$,H],B=()=>[Yt,"auto",$,H],G=()=>["auto","min","max","fr",$,H],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...S()],Ee=()=>[vn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],V=()=>[e,$,H],le=()=>[...k(),ol,rl,{position:[$,H]}],Re=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",Zu,qu,{size:[$,H]}],Q=()=>[Bo,cr,Zt],A=()=>["","none","full",d,$,H],W=()=>["",ne,cr,Zt],re=()=>["solid","dashed","dotted","double"],ve=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],K=()=>[ne,Bo,ol,rl],Ae=()=>["","none",f,$,H],He=()=>["none",ne,$,H],ae=()=>["none",ne,$,H],Pe=()=>[ne,$,H],De=()=>[vn,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pt],breakpoint:[Pt],color:[$u],container:[Pt],"drop-shadow":[Pt],ease:["in","out","in-out"],font:[Ku],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pt],shadow:[Pt],spacing:["px",ne],text:[Pt],"text-shadow":[Pt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",vn,H,$,b]}],container:["container"],columns:[{columns:[ne,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:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Yt,"auto",$,H]}],basis:[{basis:[vn,"full","auto",a,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,vn,"auto","initial","none",H]}],grow:[{grow:["",ne,$,H]}],shrink:[{shrink:["",ne,$,H]}],order:[{order:[Yt,"first","last","none",$,H]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:Ee()}],w:[{w:[a,"screen",...Ee()]}],"min-w":[{"min-w":[a,"screen","none",...Ee()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...Ee()]}],h:[{h:["screen","lh",...Ee()]}],"min-h":[{"min-h":["screen","lh","none",...Ee()]}],"max-h":[{"max-h":["screen","lh",...Ee()]}],"font-size":[{text:["base",n,cr,Zt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,$,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,H]}],"font-family":[{font:[Ju,H,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]}],"line-clamp":[{"line-clamp":[ne,"none",$,Go]}],leading:[{leading:[i,...S()]}],"list-image":[{"list-image":["none",$,H]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,H]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",$,Zt]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[ne,"auto",$,H]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,H]}],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]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Re()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Yt,$,H],radial:["",$,H],conic:[Yt,$,H]},Qu,Xu]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:Q()}],"gradient-via-pos":[{via:Q()}],"gradient-to-pos":[{to:Q()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:A()}],"rounded-s":[{"rounded-s":A()}],"rounded-e":[{"rounded-e":A()}],"rounded-t":[{"rounded-t":A()}],"rounded-r":[{"rounded-r":A()}],"rounded-b":[{"rounded-b":A()}],"rounded-l":[{"rounded-l":A()}],"rounded-ss":[{"rounded-ss":A()}],"rounded-se":[{"rounded-se":A()}],"rounded-ee":[{"rounded-ee":A()}],"rounded-es":[{"rounded-es":A()}],"rounded-tl":[{"rounded-tl":A()}],"rounded-tr":[{"rounded-tr":A()}],"rounded-br":[{"rounded-br":A()}],"rounded-bl":[{"rounded-bl":A()}],"border-w":[{border:W()}],"border-w-x":[{"border-x":W()}],"border-w-y":[{"border-y":W()}],"border-w-s":[{"border-s":W()}],"border-w-e":[{"border-e":W()}],"border-w-t":[{"border-t":W()}],"border-w-r":[{"border-r":W()}],"border-w-b":[{"border-b":W()}],"border-w-l":[{"border-l":W()}],"divide-x":[{"divide-x":W()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":W()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,$,H]}],"outline-w":[{outline:["",ne,cr,Zt]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",h,zr,jr]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",u,zr,jr]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[ne,Zt]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",p,zr,jr]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[ne,$,H]}],"mix-blend":[{"mix-blend":[...ve(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ve()}],"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":K()}],"mask-image-linear-to-pos":[{"mask-linear-to":K()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":K()}],"mask-image-t-to-pos":[{"mask-t-to":K()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":K()}],"mask-image-r-to-pos":[{"mask-r-to":K()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":K()}],"mask-image-b-to-pos":[{"mask-b-to":K()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":K()}],"mask-image-l-to-pos":[{"mask-l-to":K()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":K()}],"mask-image-x-to-pos":[{"mask-x-to":K()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":K()}],"mask-image-y-to-pos":[{"mask-y-to":K()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,H]}],"mask-image-radial-from-pos":[{"mask-radial-from":K()}],"mask-image-radial-to-pos":[{"mask-radial-to":K()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"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":K()}],"mask-image-conic-to-pos":[{"mask-conic-to":K()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Re()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,H]}],filter:[{filter:["","none",$,H]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,$,H]}],contrast:[{contrast:[ne,$,H]}],"drop-shadow":[{"drop-shadow":["","none",_,zr,jr]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",ne,$,H]}],"hue-rotate":[{"hue-rotate":[ne,$,H]}],invert:[{invert:["",ne,$,H]}],saturate:[{saturate:[ne,$,H]}],sepia:[{sepia:["",ne,$,H]}],"backdrop-filter":[{"backdrop-filter":["","none",$,H]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,$,H]}],"backdrop-contrast":[{"backdrop-contrast":[ne,$,H]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,$,H]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,$,H]}],"backdrop-invert":[{"backdrop-invert":["",ne,$,H]}],"backdrop-opacity":[{"backdrop-opacity":[ne,$,H]}],"backdrop-saturate":[{"backdrop-saturate":[ne,$,H]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,$,H]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,H]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",$,H]}],ease:[{ease:["linear","initial",m,$,H]}],delay:[{delay:[ne,$,H]}],animate:[{animate:["none",E,$,H]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,H]}],"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: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,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,H]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[ne,cr,Zt,Go]}],stroke:[{stroke:["none",...V()]}],"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"]}},rh=Lu(nh);function L(...e){return rh(Ga(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 oh=e=>{switch(e){case I.SYNAPSE_COMPONENTS.DOCTOR_CARD:case I.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},sh=e=>new Promise(t=>setTimeout(t,e)),dl=ee(({className:e,children:t,...n},r)=>c(Di,{ref:r,className:L("relative overflow-hidden",e),...n,children:[c(qd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),c(ul,{}),c(Xd,{})]}));dl.displayName=Di.displayName;const ul=ee(({className:e,orientation:t="vertical",...n},r)=>c(Io,{ref:r,orientation:t,className:L("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c(Oi,{className:"relative flex-1 rounded-full bg-border"})}));ul.displayName=Io.displayName;var ih=Symbol.for("react.lazy"),Yr=Oo[" use ".trim().toString()];function ah(e){return typeof e=="object"&&e!==null&&"then"in e}function hl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===ih&&"_payload"in e&&ah(e._payload)}function ml(e){const t=ch(e),n=ee((r,o)=>{let{children:i,...s}=r;hl(i)&&typeof Yr=="function"&&(i=Yr(i._payload));const a=st.toArray(i),l=a.find(uh);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var lh=ml("Slot");function ch(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(hl(o)&&typeof Yr=="function"&&(o=Yr(o._payload)),it(o)){const s=mh(o),a=hh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var dh=Symbol("radix.slottable");function uh(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dh}function hh(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 mh(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 pl=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,fl=Ga,ph=(e,t)=>n=>{var r;if(t?.variants==null)return fl(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=pl(h)||pl(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,..._}=h;return Object.entries(_).every(f=>{let[g,b]=f;return Array.isArray(b)?b.includes({...i,...a}[g]):{...i,...a}[g]===b})?[...d,u,p]:d},[]);return fl(e,s,l,n?.class,n?.className)},fh=ph("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"}}),Se=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>c(r?lh:"button",{className:L(fh({variant:t,size:n,className:e})),ref:i,...o}));Se.displayName="Button";const gh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_h=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),gl=e=>{const t=_h(e);return t.charAt(0).toUpperCase()+t.slice(1)},_l=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Eh=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var yh={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 Sh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>tt("svg",{ref:l,...yh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:_l("lucide",o),...!i&&!Eh(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>tt(d,h)),...Array.isArray(i)?i:[i]])),Ye=(e,t)=>{const n=ee(({className:r,...o},i)=>tt(Sh,{ref:i,iconNode:t,className:_l(`lucide-${gh(gl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=gl(e),n},bh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=Ye("chevron-down",bh),vh=[["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"}]],wh=Ye("ellipsis-vertical",vh),Nh=[["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"}]],El=Ye("file-text",Nh),Th=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],yl=Ye("info",Th),xh=[["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"}]],Ch=Ye("maximize-2",xh),kh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Oh=Ye("menu",kh),Rh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],dr=Ye("message-square-plus",Rh),Ah=[["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",Ah),Ih=[["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"}]],Mh=Ye("minimize-2",Ih),Ph=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Sl=Ye("plus",Ph),Dh=[["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"}]],Lh=Ye("rotate-ccw",Dh),Uh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],bl=Ye("square",Uh),Fh=[["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",Fh),Vh=[["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"}]],wl=Ye("thumbs-down",Vh),jh=[["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"}]],zh=Ye("triangle-alert",jh),Yh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Tn=Ye("x",Yh),Hh=[["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"}]],$h=Ye("zoom-in",Hh),Nl=e=>{let t;const n=new Set,r=(a,l)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=l??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},Bh=(e=>e?Nl(e):Nl),Gh=e=>e;function Wh(e,t=Gh){const n=Vn.useSyncExternalStore(e.subscribe,Vn.useCallback(()=>t(e.getState()),[e,t]),Vn.useCallback(()=>t(e.getInitialState()),[e,t]));return Vn.useDebugValue(n),n}const Kh=e=>{const t=Bh(e),n=r=>Wh(t,r);return Object.assign(n,t),n},qh=(e=>Kh);function Xh(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)}}}},Jh=(e,t)=>(n,r,o)=>{let i={storage:Xh(()=>localStorage),partialize:g=>g,version:0,merge:(g,b)=>({...b,...g}),...t},s=!1;const a=new Set,l=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,b)=>(u(g,b),h());const p=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>p;let _;const f=()=>{var g,b;if(!d)return;s=!1,a.forEach(E=>{var y;return E((y=r())!=null?y:p)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(g=r())!=null?g:p))||void 0;return qo(d.getItem.bind(d))(i.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==i.version){if(i.migrate){const y=i.migrate(E.state,E.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,E.state];return[!1,void 0]}).then(E=>{var y;const[k,x]=E;if(_=i.merge(x,(y=r())!=null?y:p),n(_,!0),k)return h()}).then(()=>{m?.(_,void 0),_=r(),s=!0,l.forEach(E=>E(_))}).catch(E=>{m?.(void 0,E)})};return o.persist={setOptions:g=>{i={...i,...g},g.storage&&(d=g.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>f(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(l.add(g),()=>{l.delete(g)})},i.skipHydration||f(),_||p},Zh=Jh,Ne={USER:"user",ASSISTANT:"assistant"};var be=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(be||{}),_e=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(_e||{});let dt="";const ur=e=>`med-assist-store-${e}`,Qh=e=>{xn(),dt=ur(e)},em=200;let gt=null,hr=null;function xn(){if(hr&&(clearTimeout(hr),hr=null),!!gt){try{sessionStorage.setItem(gt.key,JSON.stringify(gt.value))}catch{}gt=null}}typeof window<"u"&&(window.addEventListener("pagehide",xn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&xn()}));const tm={getItem:()=>{if(!dt)return null;if(gt?.key===dt)return gt.value;try{const e=sessionStorage.getItem(dt);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{dt&&(gt&>.key!==dt&&xn(),gt={key:dt,value:t},hr||(hr=setTimeout(xn,em)))},removeItem:()=>{gt?.key===dt&&(gt=null),dt&&sessionStorage.removeItem(dt)}},Tl={sessionId:"",isStreaming:!1,recordingStatus:be.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:_e.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},xl={...Tl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=qh()(Zh((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:_e.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:be.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(Tl),await sessionStorage.removeItem(dt||ur(t().agentId))},clearUser:()=>{e(xl),sessionStorage.removeItem(dt||ur(t().agentId))}}),{name:"med-assist-store",storage:tm,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})})),nm=e=>{const t=ur(e);xn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(xl),n&&j.setState(n)},Xo=bt(null),rm=({children:e})=>{const[t,n]=F(null);return c(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},om=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},sm=()=>{const e=vt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},im=()=>{const[e,t]=F(I.VOICE_AGENT_STATE.IDLE),[n,r]=F(!1),o=om(),i=j(h=>h.setError);Y(()=>{if(!o)return;const h=o.voice,u=_=>{t(_)},p=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(I.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(I.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=de(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=de(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),l=de(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=de(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:l,toggleMute:d}},en=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));en.displayName="Card";const Cl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex flex-col space-y-1.5 p-6",e),...t}));Cl.displayName="CardHeader";const kl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("font-semibold leading-none tracking-tight",e),...t}));kl.displayName="CardTitle";const am=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("text-sm text-muted-foreground",e),...t}));am.displayName="CardDescription";const Ol=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("p-6 pt-0",e),...t}));Ol.displayName="CardContent";const Rl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex items-center p-6 pt-0",e),...t}));Rl.displayName="CardFooter";const Jo=5,Al=3,Il=10*1024*1024,Hr={width:384,height:600},$r=20,lm=400,cm=320,dm=560,um=150;function hm({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=de(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Hr.width-$r,y:window.innerHeight-Hr.height-$r},[]),[i,s]=F(()=>e??o()),[a,l]=F(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);Y(()=>{t||(u.current=!1)},[t]),pt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),Y(()=>{if(!t||typeof window>"u")return;let g=null;const b=()=>{s(E=>{const y=Math.max(0,window.innerWidth-Hr.width-$r),k=Math.max(0,window.innerHeight-Hr.height-$r),x=Math.max(0,Math.min(E.x,y)),T=Math.max(0,Math.min(E.y,k));return x===E.x&&T===E.y?E:{x,y:T}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(b,um)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const p=de(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){l(!1);return}g.preventDefault(),l(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),_=de(g=>{if(!t||!a)return;const b=g.clientX-d.current.x,m=g.clientY-d.current.y,E=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(b,E)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[a,t]),f=de(()=>{!t||!a||(l(!1),r?.())},[a,r]);return Y(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",p),()=>{g.removeEventListener("mousedown",p)}},[t,p]),Y(()=>{if(a)return document.addEventListener("mousemove",_),document.addEventListener("mouseup",f),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",f),document.body.style.cursor="",document.body.style.userSelect=""}},[a,_,f]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Zo="#6B5CE0",mm="#F0F0F0",Br={background:mm,backgroundImage:void 0,primary:Zo,textColor:"black"},pm="rgba(0, 0, 0, 0.4)",fm="24px";function gm(e){if(e==="dark")return"white";if(e==="light")return"black"}function _m(e){const t=e?.primary??e?.primaryColor??Br.primary,n=e?.textColor??gm(e?.mode);return{background:e?.background??Br.background,backgroundImage:e?.backgroundImage??Br.backgroundImage,primary:t,primaryColor:t,textColor:n??Br.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Em(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const l=(o+i)/2;if(o!==i){const h=o-i;switch(a=l>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(l*100);return`${s} ${a}% ${d}%`}function ym(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,l=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(l=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),l=Math.round(l*100);const h=Math.round(d*100);return`${a} ${l}% ${h}%`}function Sm(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 Em(t);if(t.startsWith("rgb"))return ym(t);if(t.startsWith("hsl"))return Sm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Ml(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Ml(e)>.5?"0 0% 9%":"0 0% 98%"}function bm(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 vm(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 Pl(e,t){const n=t.primary??Zo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(_,f)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(_,f)};let l;try{l=Qo(n)}catch{l=Qo(Zo)}a("--primary",l),a("--primary-foreground",es(l)),a("--ring",l),a("--border-primary",l);const d=vm(l);for(const[_,f]of Object.entries(d))a(`--primary-${_}`,f);const h=es(l);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const _=i?"#191919":"#F0F0F0";try{a("--background",Qo(_))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${l} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",bm(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${l})`),a("--header-stroke",`hsl(${l} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${l} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${l} / 0.3)`)),s&&!o){const _=Ml(h)>.5;a("--header-tagline",_?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",l):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const _ of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${_}`,`var(--${p}-${_})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",l),a("--accent-foreground",es(l)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",fm),a("--theme-background-overlay",pm),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function tn({className:e,style:t}){return c("div",{className:L("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function ts(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Dl(){return c("div",{className:"px-3 pb-2 pt-1",children:[c(ts,{}),c("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[c("div",{className:"px-2 pt-2 pb-1",children:c(tn,{className:"h-5 w-3/5 rounded-md"})}),c("div",{className:"flex items-center justify-between px-1 py-1",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c("div",{className:"flex items-center gap-2",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c(tn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function wm(){const e=[{role:Ne.ASSISTANT,size:"h-16 w-[70%]"},{role:Ne.USER,size:"h-9 w-[45%]"},{role:Ne.ASSISTANT,size:"h-24 w-[75%]"},{role:Ne.USER,size:"h-9 w-[35%]"},{role:Ne.ASSISTANT,size:"h-16 w-[65%]"}];return c("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[c(ts,{}),e.map((t,n)=>c("div",{className:L("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:c(tn,{className:L("rounded-lg",t.size)})},n))]})}function Nm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return c("div",{"aria-hidden":"true",children:[c(ts,{}),Array.from({length:e},(n,r)=>c("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[c(tn,{className:L("h-5 rounded-md",t[r%t.length])}),c(tn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function Tm(e,t=[]){let n=[];function r(i,s){const a=bt(s);a.displayName=i+"Context";const l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=vt(_);if(f)return f;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>bt(s));return function(s){const a=s?.[e]||i;return ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,xm(o,...t)]}function xm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Cm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=Cm.reduce((e,t)=>{const n=ml(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Ll={exports:{}},rs={};const km=Jd(Oo);var Ul;function Om(){if(Ul)return rs;Ul=1;var e=km;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 _=p(),f=r({inst:{value:_,getSnapshot:p}}),g=f[0].inst,b=f[1];return i(function(){g.value=_,g.getSnapshot=p,l(g)&&b({inst:g})},[u,_,p]),o(function(){return l(g)&&b({inst:g}),u(function(){l(g)&&b({inst:g})})},[u]),s(_),_}function l(u){var p=u.getSnapshot;u=u.value;try{var _=p();return!n(u,_)}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 Fl;function Rm(){return Fl||(Fl=1,Ll.exports=Om()),Ll.exports}var Am=Rm();function Im(){return Am.useSyncExternalStore(Mm,()=>!0,()=>!1)}function Mm(){return()=>{}}var os="Avatar",[Pm]=Tm(os),[Dm,Vl]=Pm(os),jl=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=F("idle");return c(Dm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:c(ns.span,{...r,ref:t})})});jl.displayName=os;var zl="AvatarImage",Yl=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Vl(zl,n),a=Lm(r,i),l=jt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Jt(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?c(ns.img,{...i,ref:t,src:r}):null});Yl.displayName=zl;var Hl="AvatarFallback",$l=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Vl(Hl,n),[s,a]=F(r===void 0);return Y(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),s&&i.imageLoadingStatus!=="loaded"?c(ns.span,{...o,ref:t}):null});$l.displayName=Hl;function Bl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Lm(e,{referrerPolicy:t,crossOrigin:n}){const r=Im(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=F(()=>Bl(i,e));return Jt(()=>{a(Bl(i,e))},[i,e]),Jt(()=>{const l=u=>()=>{a(u)};if(!i)return;const d=l("loaded"),h=l("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Gl=jl,Wl=Yl,Kl=$l;const ss=ee(({className:e,...t},n)=>c(Gl,{ref:n,className:L("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Gl.displayName;const ql=ee(({className:e,...t},n)=>c(Wl,{ref:n,className:L("aspect-square h-full w-full",e),...t}));ql.displayName=Wl.displayName;const is=ee(({className:e,...t},n)=>c(Kl,{ref:n,className:L("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Kl.displayName;const Xl=bt(!1);function Um({enabled:e,children:t}){return c(Xl.Provider,{value:e,children:t})}function Fm(){return vt(Xl)}const Jl="(max-width: 768px), (pointer: coarse)",Zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Vm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Jl)?.matches??!1,t=Zl.test(navigator?.userAgent??"");return e||t}function Ql(){const[e,t]=F(Vm);return Y(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Jl),r=Zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function jm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:l=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Ql(),p=Fm(),_=j(N=>N.displayMode)==="side_panel",f=p&&!u&&!_,g=j(N=>N.displayMode)==="full",b=j(N=>N.initialDisplayMode)==="full",m=!g&&l?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",E=j(N=>N.connectionStatus),y=j(N=>N.level)==="user",[k,x]=F(!1),T=X(null),C=ie(()=>a===I.VOICE_AGENT_STATE.CONNECTED||a===I.VOICE_AGENT_STATE.CONNECTING||a===I.VOICE_AGENT_STATE.LISTENING||a===I.VOICE_AGENT_STATE.SPEAKING||a===I.VOICE_AGENT_STATE.THINKING,[a]),S=de(()=>{k||(x(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,x(!1)},6e3),s())},[k,s]);Y(()=>{E===_e.CONNECTED&&(x(!1),T.current&&clearTimeout(T.current))},[E]);const v=(()=>{switch(E){case _e.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case _e.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case _e.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return c("div",{className:"px-6 py-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative flex-shrink-0",children:[c(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:c(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?c("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):c("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),c("div",{className:L("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,E===_e.CONNECTING&&"animate-pulse")})]}),c("div",{className:"flex flex-col",children:[r?c("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):c("p",{className:L("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",m),children:n||"Health Assist"}),c("div",{className:"flex items-center gap-1.5",children:c("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),c("div",{className:L("flex items-center",!f&&"gap-1"),children:[!C&&!y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:S,disabled:k,className:L("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",m),children:c(dr,{className:"w-5 h-5"})}),h&&y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:L("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(wh,{className:"w-5 h-5"})}),f&&c(Se,{onClick:d,type:"button",variant:"ghost",size:"icon",title:g?"Exit fullscreen":"Enter fullscreen",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:g?c(Mh,{className:"w-8 h-8"}):c(Ch,{className:"w-8 h-8"})}),(t||!b)&&c(Se,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(Tn,{className:"w-8 h-8"})})]})]})})}const as=ee(({className:e,...t},n)=>c("textarea",{className:L("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 ec({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=F(!1),[s,a]=F(""),l=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";Y(()=>{if(l){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,l]),Y(()=>{i(!1)},[e]);const h=()=>l?"text-green-600":"text-text-secondary",u=p=>{if(p===0)return"0 B";const _=1024,f=["B","KB","MB","GB"],g=Math.floor(Math.log(p)/Math.log(_));return`${(p/Math.pow(_,g)).toFixed(1)} ${f[g]}`.toLowerCase()};return!l||o?c("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[c("div",{className:`flex-shrink-0 ${h()}`,children:c(El,{className:"h-5 w-5"})}),c("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&c("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&c("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:c(Tn,{className:"h-3 w-3"})})]}):c("div",{className:`relative group flex-shrink-0 ${r}`,children:[c("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&c("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:c(Tn,{className:"h-3 w-3"})})]})}function ls({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return c("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&c("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),tc=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),zm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},nc=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),Ym=nt(()=>tc().then(e=>({default:e.ElicitationInput})));function Hm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:l,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:_,allowed:f,showStartNewChatButton:g,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:E,isAuthComponent:y,activeElicitationState:k,isFullScreen:x,showAttention:T}){const C=X(null),S=X(null),v=T?c("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,N=e.trim().length>0||a,D=!f||f.includes(I.SYNAPSE_CONVERSATION.AUDIO),B=!f||f.includes(I.SYNAPSE_CONVERSATION.VOICE),G=N||!D,he=N,pe=!f||f.includes(I.SYNAPSE_CONVERSATION.FILE),se=(d||p!==be.IDLE)&&!s,Ee=L("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":se?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),V=A=>{const W=Array.from(A.target.files||[]);W.length>0&&r(W)},le=()=>{d||(C.current&&(C.current.value=""),C.current?.click())},Re=A=>{A.key==="Enter"&&!A.shiftKey&&he&&!d&&(A.preventDefault(),n())},te=A=>{A.style.height="auto",A.style.overflow="hidden";const W=A.scrollHeight,re=x?20:28,ve=120,K=Math.max(re,Math.min(W,ve));A.style.height=K+"px",W>ve?A.style.overflow="auto":A.style.overflow="hidden"},Q=A=>{te(A.currentTarget)};return Y(()=>{S.current&&te(S.current)},[e]),Y(()=>{d||S.current?.focus()},[d]),g&&b?c("div",{className:"px-4 py-2 flex justify-unset",children:c("button",{type:"button",onClick:b,className:L("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[c("span",{children:"Start new chat"}),c(dr,{className:"w-5 h-5","aria-hidden":!0})]})}):c(me,{children:y?c(Xe,{fallback:c(Dl,{}),children:c(Ym,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:_,isMobile:u,onSend:n})}):x?c("div",{className:"mx-3 mb-3","data-name":"reply-box",children:c("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:L("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),c("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[c("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(Sl,{className:"w-6 h-6",strokeWidth:1.5})})}),c("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(bl,{className:"w-4 h-4"})}):D&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0 p-2",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-6 h-6",strokeWidth:1.5})}),G&&!s?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):D&&B&&!s&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:E,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):c("div",{className:"px-3 pt-1",children:[c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("div",{className:"px-1 pt-1 pb-0",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:A=>t(A.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:L("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center shrink-0",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(Sl,{className:"w-5 h-5",strokeWidth:1.5})})}),c("div",{className:"flex items-center gap-2 shrink-0",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(bl,{className:"w-4 h-4"})}):G?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):D&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),D&&B&&!s&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:E,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const $m=Xt(Hm),rc=bt(null),oc=rc.Provider;function Bm(){const e=vt(rc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function Gm({message:e,onDismiss:t}){return c(me,{children:[c("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),c("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:c("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[c("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),c("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:c(Tn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Wm(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=de(()=>{t(null)},[t]);return Y(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?c(Gm,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?c("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:c("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Km="Before we begin",qm=e=>`A quick note on how ${e} works and handles your information.`,Xm=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 Jm(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 sc=(e,t)=>{if(t){const n=Jm(t,e);if(n.length)return n}return Xm(e)},Zm="I agree and consent",Qm="By continuing, you consent to the above.",ep="Continue";function ic({botName:e,consentContent:t,isFullScreen:n}){return c(me,{children:[c("div",{className:"flex flex-col gap-1",children:[c("h2",{className:L("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Km}),c("p",{className:L("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:qm(e)})]}),c("div",{className:L("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:sc(e,t).map((r,o)=>c("p",{className:L("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function tp({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return c(ds,{isOpen:e,onClose:t,children:c("div",{className:L("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?c(ic,{botName:n,consentContent:o,isFullScreen:s}):c("div",{className:"flex flex-col gap-2",children:[c("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),sc(n,o).map((a,l)=>c("p",{className:L("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},l))]}),c(Se,{onClick:t,className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function np({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=F(!1);return e?c(ds,{isOpen:e,children:c("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:L("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[c(ic,{botName:t,consentContent:n,isFullScreen:o}),c("div",{className:"flex flex-col gap-1.5",children:[c("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[c("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),c("div",{"aria-hidden":"true",className:L("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&c("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:L("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Zm})]}),c("p",{className:L("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:Qm})]}),c(Se,{disabled:!i,onClick:()=>i&&r(),className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:ep})]})}):null}const rp=nt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),op=nt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),sp=nt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),ip=nt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),ap=nt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),lp=[{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"}],cp=[{Icon:rp,label:"Bad",score:1},{Icon:op,label:"Poor",score:2},{Icon:sp,label:"Okay",score:3},{Icon:ip,label:"Good",score:4},{Icon:ap,label:"Great!",score:5}];function dp(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function up({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,l]=F(null),[d,h]=F(new Set),[u,p]=F(!1),_=s&&a!==null?dp(a,t):t.form?.default?.length?t.form.default:lp,f=E=>{h(y=>{const k=new Set(y);return k.has(E)?k.delete(E):k.add(E),k})},g=E=>{l(E),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?c(ds,{isOpen:e,onClose:o,children:c("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[c("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),c("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[c("div",{className:"flex flex-col gap-1",children:[t.title&&c("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&c("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&c("div",{className:"flex items-center justify-between gap-1",children:cp.map(({Icon:E,label:y,score:k})=>{const x=a===k,T=a!==null&&!x;return c("button",{onClick:()=>g(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[c("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${T?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:c(Xe,{fallback:c("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:c(E,{})})}),c("span",{className:`text-[10px] leading-none transition-colors ${x?"text-primary/50 font-medium":T?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&_.length>0&&c("div",{className:"flex flex-col gap-2",children:_.map(E=>c("div",{onClick:()=>f(E.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(E.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:E.label},E.value))}),c(Se,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),c("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>p(E=>!E),children:[c("div",{className:"relative w-3 h-3 shrink-0",children:c("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&c("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),c("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function ac({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:l,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:_,activeElicitation:f,voiceAgentState:g,theme:b,feedbackModal:m,consentModal:E}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:T,tagline:C,iconUrl:S,onStartNewSession:v,showStartNewChatButton:N,onToggleDisplayMode:D,onOpenSessionDrawer:B}=Bm(),[G,he]=F(!1),[pe,se]=F(!1),[Ee,V]=F(!1),le=X(null),Re=j(z=>z.level),te=l,Q=te==="full",A=te==="side_panel",W=X(null),[re,ve]=F("");Y(()=>{W.current!==null&&W.current!==te&&ve(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),W.current=te},[te]);const K=ie(()=>_m(b),[b]),Ae=j(z=>z.setIsMobile),He=!!_,ae=de(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);pt(()=>{if(!le.current)return;const z=te==="full"?{...K,headerTinted:!1}:K;Pl(le.current,z),te==="full"&&!K.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),Pl(le.current,K))},[K,te]),Y(()=>{const z=()=>{const Ie=window?.innerWidth??0,we=navigator?.userAgent?.toLowerCase()??"",Le=Ie<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(we);he(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),pt(()=>{if(!e||!G||!le.current)return;const z=le.current;let Ie=null,we=null,Le=null,qe=window.visualViewport?.offsetTop??0,Ue=0;const _t=2,ut=80;if(window.visualViewport){const ze=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,Oe=window.visualViewport.offsetTop;Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Oe}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`,we&&clearTimeout(we),we=setTimeout(()=>{z.style.transition=""},100)})}},rt=()=>{ze()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,Oe=Date.now();Math.abs(Ge-qe)<_t||Oe-Ue<ut||(Ue=Oe,qe=Ge,Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",rt),window.visualViewport.addEventListener("scroll",Be),ze(),()=>{Ie&&cancelAnimationFrame(Ie),we&&clearTimeout(we),Le&&clearTimeout(Le),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 ze=()=>{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",ze),ze(),()=>{window.removeEventListener("resize",ze),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),Y(()=>{if(e&&!(A&&d==="push")){const z=le.current,Ie=window.scrollY,we=document.body.style.cssText,Le=document.documentElement.style.overflow,qe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ie}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",qe>0&&!G&&(document.body.style.paddingRight=`${qe}px`);let Ue=0;const _t=ze=>{Ue=ze.touches[0].clientY},ut=ze=>{if(ze.touches.length!==1)return;const rt=Ue-ze.touches[0].clientY;Ue=ze.touches[0].clientY;let Be=ze.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:Oe,scrollHeight:Bt,clientHeight:Et}=Be,an=Oe<=0&&rt<0,ln=Oe+Et>=Bt-1&&rt>0;if(!an&&!ln)return;break}Be=Be.parentElement}ze.preventDefault()};return z&&(z.addEventListener("touchstart",_t,{passive:!0}),z.addEventListener("touchmove",ut,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",_t),z.removeEventListener("touchmove",ut)),document.body.style.cssText=we,document.documentElement.style.overflow=Le,window.scrollTo(0,Ie)}}},[e,G,A,d]),Y(()=>{if(!(!A||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,A,d,h,u,p]);const{position:Pe,elementRef:De}=hm({enabled:e&&!G&&!Q&&!A});Y(()=>{le.current&&(De.current=le.current)},[De]);const Tt=L("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!Q&&!A?"transition-all duration-300":"",G?"w-screen h-[100svh]":Q?"w-screen h-screen":A?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),$t=L("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",K.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":Q?"rounded-none border-0 flex-row":A?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return c("div",{ref:le,"data-mode":te,className:Tt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...Q&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...Q&&!e&&{display:"none"},...A&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...A&&!e&&{display:"none"},...!G&&!Q&&!A&&{left:`${Pe.x}px`,top:`${Pe.y}px`,bottom:"auto",right:"auto"},...G&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:K.backgroundImage?"transparent":"hsl(var(--background))"}},children:[c("style",{children:`
|
|
1
|
+
var Qc=Object.defineProperty;var ed=(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)=>ed(e,typeof t!="symbol"?t+"":t,n);var Pn,J,Ts,Ut,xs,Cs,ks,ro,Nr,Dn,Os,oo,so,io,Rs,Tr={},xr=[],td=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ln=Array.isArray;function bt(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?Pn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return Un(e,s,r,o,null)}function Un(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++Ts,__i:-1,__u:0};return o==null&&J.vnode!=null&&J.vnode(i),i}function As(){return{current:null}}function me(e){return e.children}function ct(e,t){this.props=e,this.context=t}function dn(e,t){if(t==null)return e.__?dn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?dn(e):null}function nd(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=bt({},t);i.__v=t.__v+1,J.vnode&&J.vnode(i),co(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??dn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Us(r,i,o),t.__e=t.__=null,i.__e!=n&&Is(i)}}function Is(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}),Is(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Ut.push(e)&&!Cr.__r++||xs!=J.debounceRendering)&&((xs=J.debounceRendering)||Cs)(Cr)}function Cr(){try{for(var e,t=1;Ut.length;)Ut.length>t&&Ut.sort(ks),e=Ut.shift(),t=Ut.length,nd(e)}finally{Ut.length=Cr.__r=0}}function Ms(e,t,n,r,o,i,s,a,l,d,h){var u,p,_,f,g,b,m,E=r&&r.__k||xr,y=t.length;for(l=rd(n,t,E,l,y),u=0;u<y;u++)(_=n.__k[u])!=null&&(p=_.__i!=-1&&E[_.__i]||Tr,_.__i=u,b=co(e,_,p,o,i,s,a,l,d,h),f=_.__e,_.ref&&p.ref!=_.ref&&(p.ref&&ho(p.ref,null,_),h.push(_.ref,_.__c||f,_)),g==null&&f!=null&&(g=f),(m=!!(4&_.__u))||p.__k===_.__k?(l=Ps(_,l,e,m),m&&p.__e&&(p.__e=null)):typeof _.type=="function"&&b!==void 0?l=b:f&&(l=f.nextSibling),_.__u&=-7);return n.__e=g,l}function rd(e,t,n,r,o){var i,s,a,l,d,h=n.length,u=h,p=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=Un(null,s,null,null,null):Ln(s)?s=e.__k[i]=Un(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Un(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,l=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=od(s,n,l,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?p--:d==l+1?p++:(d>l?p--:p++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=dn(a)),Vs(a,a));return r}function Ps(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=Ps(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function It(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ln(e)?e.some(function(n){It(n,t)}):t.push(e)),t}function od(e,t,n,r){var o,i,s,a=e.key,l=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&l==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&l==d.type)return s}return-1}function Ds(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||td.test(t)?n:n+"px"}function kr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ds(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ds(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Os,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Dn]=r[Dn]:(n[Dn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ls(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Nr]==null)t[Nr]=oo++;else if(t[Nr]<n[Dn])return;return n(J.event?J.event(t):t)}}}function co(e,t,n,r,o,i,s,a,l,d){var h,u,p,_,f,g,b,m,E,y,k,x,T,C,S,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=J.__b)&&h(t);e:if(typeof v=="function")try{if(m=t.props,E=v.prototype&&v.prototype.render,y=(h=v.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(E?t.__c=u=new v(m,k):(t.__c=u=new ct(m,k),u.constructor=v,u.render=id),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),E&&u.__s==null&&(u.__s=u.state),E&&v.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=bt({},u.__s)),bt(u.__s,v.getDerivedStateFromProps(m,u.__s))),_=u.props,f=u.state,u.__v=t,p)E&&v.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),E&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(E&&v.getDerivedStateFromProps==null&&m!==_&&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(N){N&&(N.__=t)}),xr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),E&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(_,f,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=J.__r,T=0,E)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),xr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++T<25);u.state=u.__s,u.getChildContext!=null&&(r=bt(bt({},r),u.getChildContext())),E&&!p&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(_,f)),C=h!=null&&h.type===me&&h.key==null?Fs(h.props.children):h,a=Ms(e,Ln(C)?C:[C],t,n,r,o,i,s,a,l,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(N){if(t.__v=null,l||i!=null)if(N.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(S=i.length;S--;)ao(i[S]);uo(t)}else t.__e=n.__e,t.__k=n.__k,N.then||uo(t);J.__e(N,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=sd(n.__e,t,n,r,o,i,s,l,d);return(h=J.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 Us(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);J.__c&&J.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){J.__e(i,o.__v)}})}function Fs(e){return typeof e!="object"||e==null||e.__b>0?e:Ln(e)?e.map(Fs):e.constructor!==void 0?null:bt({},e)}function sd(e,t,n,r,o,i,s,a,l){var d,h,u,p,_,f,g,b=n.props||Tr,m=t.props,E=t.type;if(E=="svg"?o="http://www.w3.org/2000/svg":E=="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((_=i[d])&&"setAttribute"in _==!!E&&(E?_.localName==E:_.nodeType==3)){e=_,i[d]=null;break}}if(e==null){if(E==null)return document.createTextNode(m);e=document.createElementNS(o,E,m.is&&m),a&&(J.__m&&J.__m(t,i),a=!1),i=null}if(E==null)b===m||a&&e.data==m||(e.data=m);else{if(i=E=="textarea"&&m.defaultValue!=null?null:i&&Pn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(_=e.attributes[d]).name]=_.value;for(d in b)_=b[d],d=="dangerouslySetInnerHTML"?u=_:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||kr(e,d,null,_,o);for(d in m)_=m[d],d=="children"?p=_:d=="dangerouslySetInnerHTML"?h=_:d=="value"?f=_:d=="checked"?g=_:a&&typeof _!="function"||b[d]===_||kr(e,d,_,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),Ms(t.type=="template"?e.content:e,Ln(p)?p:[p],t,n,r,E=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&dn(n,0),a,l),i!=null)for(d=i.length;d--;)ao(i[d]);a&&E!="textarea"||(d="value",E=="progress"&&f==null?e.removeAttribute("value"):f!=null&&(f!==e[d]||E=="progress"&&!f||E=="option"&&f!=b[d])&&kr(e,d,f,b[d],o),d="checked",g!=null&&g!=e[d]&&kr(e,d,g,b[d],o))}return e}function ho(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){J.__e(o,n)}}function Vs(e,t,n){var r,o;if(J.unmount&&J.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){J.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Vs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function id(e,t,n){return this.constructor(e,n)}function Fn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),J.__&&J.__(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||Tr,Tr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Pn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Us(i,e,s)}function js(e,t){Fn(e,t,js)}function ad(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?Pn.call(arguments,2):n),Un(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,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"+Rs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Pn=xr.slice,J={__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}},Ts=0,ct.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),lo(this))},ct.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},ct.prototype.render=me,Ut=[],Cs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ks=function(e,t){return e.__v.__b-t.__v.__b},Cr.__r=0,ro=Math.random().toString(8),Nr="__d"+ro,Dn="__a"+ro,Os=/(PointerCapture)$|Capture$/i,oo=0,so=Ls(!1),io=Ls(!0),Rs=0;var ld=0;function c(e,t,n,r,o,i){t||(t={});var s,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?s=t[a]:l[a]=t[a];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ld,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)l[a]===void 0&&(l[a]=s[a]);return J.vnode&&J.vnode(d),d}var Mt,ge,mo,zs,un=0,Ys=[],Ce=J,Hs=Ce.__b,$s=Ce.__r,Bs=Ce.diffed,Gs=Ce.__c,Ws=Ce.unmount,Ks=Ce.__;function qt(e,t){Ce.__h&&Ce.__h(ge,e,un||t),un=0;var n=ge.__H||(ge.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function F(e){return un=1,hn(Xs,e)}function hn(e,t,n){var r=qt(Mt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xs(void 0,t),function(a){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,a);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=ge,!ge.__f)){var o=function(a,l,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,l,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var _=p.__[0];p.__=p.__N,p.__N=void 0,_!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,l,d)||u};ge.__f=!0;var i=ge.shouldComponentUpdate,s=ge.componentWillUpdate;ge.componentWillUpdate=function(a,l,d){if(this.__e){var h=i;i=void 0,o(a,l,d),i=h}s&&s.call(this,a,l,d)},ge.shouldComponentUpdate=o}return r.__N||r.__}function Y(e,t){var n=qt(Mt++,3);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__H.__h.push(n))}function ft(e,t){var n=qt(Mt++,4);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__h.push(n))}function X(e){return un=5,ie(function(){return{current:e}},[])}function po(e,t,n){un=6,ft(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 ie(e,t){var n=qt(Mt++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function de(e,t){return un=8,ie(function(){return e},t)}function wt(e){var t=ge.context[e.__c],n=qt(Mt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(ge)),t.props.value):e.__}function fo(e,t){Ce.useDebugValue&&Ce.useDebugValue(t?t(e):e)}function cd(e){var t=qt(Mt++,10),n=F();return t.__=e,ge.componentDidCatch||(ge.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=qt(Mt++,11);if(!e.__){for(var t=ge.__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 dd(){for(var e;e=Ys.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Or),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],Ce.__e(n,e.__v)}}}Ce.__b=function(e){ge=null,Hs&&Hs(e)},Ce.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ks&&Ks(e,t)},Ce.__r=function(e){$s&&$s(e),Mt=0;var t=(ge=e.__c).__H;t&&(mo===ge?(t.__h=[],ge.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Or),t.__h.some(_o),t.__h=[],Mt=0)),mo=ge},Ce.diffed=function(e){Bs&&Bs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ys.push(t)!==1&&zs===Ce.requestAnimationFrame||((zs=Ce.requestAnimationFrame)||ud)(dd)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=ge=null},Ce.__c=function(e,t){t.some(function(n){try{n.__h.some(Or),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],Ce.__e(r,n.__v)}}),Gs&&Gs(e,t)},Ce.unmount=function(e){Ws&&Ws(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Or(r)}catch(o){t=o}}),n.__H=void 0,t&&Ce.__e(t,n.__v))};var qs=typeof requestAnimationFrame=="function";function ud(e){var t,n=function(){clearTimeout(r),qs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);qs&&(t=requestAnimationFrame(n))}function Or(e){var t=ge,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),ge=t}function _o(e){var t=ge;e.__c=e.__(),ge=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Xs(e,t){return typeof t=="function"?t(e):t}function Zs(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=F({t:{__:n,u:t}}),o=r[0].t,i=r[1];return ft(function(){o.__=n,o.u=t,bo(o)&&i({t:o})},[e,n,t]),Y(function(){return bo(o)&&i({t:o}),e(function(){bo(o)&&i({t:o})})},[e]),n}function bo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function vo(e){e()}function wo(e){return e}function No(){return[!1,vo]}var To=ft;function Rr(e,t){this.props=e,this.context=t}function Xt(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,tt(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Rr.prototype=new ct).isPureReactComponent=!0,Rr.prototype.shouldComponentUpdate=function(e,t){return yo(this.props,e)||yo(this.state,t)};var Js=J.__b;J.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Js&&Js(e)};var hd=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=Zs({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=hd,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Qs=function(e,t){return e==null?null:It(It(e).map(t))},st={map:Qs,forEach:Qs,count:function(e){return e?It(e).length:0},only:function(e){var t=It(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:It},md=J.__e;J.__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)}md(e,t,n,r)};var ei=J.unmount;function ti(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=Zs({},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 ti(r,t,n)})),e}function ni(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ni(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 ri(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 mn(){this.i=null,this.l=null}J.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),ei&&ei(e)},(Xe.prototype=new ct).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ri(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(l):l())};n.__R=s;var a=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ni(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]=ti(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 oi=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 pd(e){return this.getChildContext=function(){return e.context},e.children}function fd(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Fn(tt(pd,{context:t.context},e.__v),t.v)}function si(e,t){var n=tt(fd,{__v:e,h:t});return n.containerInfo=t,n}(mn.prototype=new ct).__a=function(e){var t=this,n=ri(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),oi(t,e,r)):o()};n?n(i):i()}},mn.prototype.render=function(e){this.i=null,this.l=new Map;var t=It(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},mn.prototype.componentDidUpdate=mn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){oi(e,n,t)})};var ii=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,gd=/^(?: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]/,_d=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ed=/[A-Z0-9]/g,yd=typeof document<"u",Sd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Fn(e,t),typeof n=="function"&&n(),e?e.__c:null}function ai(e,t,n){return js(e,t),typeof n=="function"&&n(),e?e.__c:null}ct.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(ct.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var li=J.event;J.event=function(e){return li&&(e=li(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Co,bd={configurable:!0,get:function(){return this.class}},ci=J.vnode;J.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||yd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||Sd(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":_d.test(s)&&(s=l):l=s="oninput":i&&gd.test(s)?s=s.replace(Ed,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&o[s=l]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=It(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=It(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",bd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=ii,ci&&ci(e)};var di=J.__r;J.__r=function(e){di&&di(e),Co=e.__c};var ui=J.diffed;J.diffed=function(e){ui&&ui(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 hi={ReactCurrentDispatcher:{current:{readContext:function(e){return Co.__n[e.__c].props.value},useCallback:de,useContext:wt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:ft,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No}}},vd="18.3.1";function mi(e){return tt.bind(null,e)}function it(e){return!!e&&e.$$typeof===ii}function pi(e){return it(e)&&e.type===me}function fi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Ft(e){return it(e)?ad.apply(null,arguments):e}function ko(e){return!!e.__k&&(Fn(null,e),!0)}function gi(e){return e&&(e.base||e.nodeType===1&&e)||null}var _i=function(e,t){return e(t)},Ei=function(e,t){var n=J.debounceRendering;J.debounceRendering=function(o){return o()};var r=e(t);return J.debounceRendering=n,r},yi=it,Vn={useState:F,useId:go,useReducer:hn,useEffect:Y,useLayoutEffect:ft,useInsertionEffect:To,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:vo,useRef:X,useImperativeHandle:po,useMemo:ie,useCallback:de,useContext:wt,useDebugValue:fo,version:"18.3.1",Children:st,render:xo,hydrate:ai,unmountComponentAtNode:ko,createPortal:si,createElement:tt,createContext:vt,createFactory:mi,cloneElement:Ft,createRef:As,Fragment:me,isValidElement:it,isElement:yi,isFragment:pi,isMemo:fi,findDOMNode:gi,Component:ct,PureComponent:Rr,memo:Xt,forwardRef:ee,flushSync:Ei,unstable_batchedUpdates:_i,StrictMode:me,Suspense:Xe,SuspenseList:mn,lazy:nt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:st,Component:ct,Fragment:me,PureComponent:Rr,StrictMode:me,Suspense:Xe,SuspenseList:mn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi,cloneElement:Ft,createContext:vt,createElement:tt,createFactory:mi,createPortal:si,createRef:As,default:Vn,findDOMNode:gi,flushSync:Ei,forwardRef:ee,hydrate:ai,isElement:yi,isFragment:pi,isMemo:fi,isValidElement:it,lazy:nt,memo:Xt,render:xo,startTransition:vo,unmountComponentAtNode:ko,unstable_batchedUpdates:_i,useCallback:de,useContext:wt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useErrorBoundary:cd,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:ft,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No,version:vd},Symbol.toStringTag,{value:"Module"}));function wd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function Si(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=Si(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():Si(e[o],null)}}}}function Vt(...e){return de(Ro(...e),e)}function Nd(e){const t=Td(e),n=ee((r,o)=>{const{children:i,...s}=r,a=st.toArray(i),l=a.find(Cd);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Td(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(it(o)){const s=Od(o),a=kd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var xd=Symbol("radix.slottable");function Cd(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xd}function kd(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 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)}var Rd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=Rd.reduce((e,t)=>{const n=Nd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Zt=globalThis?.document?ft:()=>{};function Ad(e,t){return hn((n,r)=>t[n][r]??n,e)}var fn=e=>{const{present:t,children:n}=e,r=Id(t),o=typeof n=="function"?n({present:r.isPresent}):st.only(n),i=Vt(r.ref,Md(o));return typeof n=="function"||r.isPresent?Ft(o,{ref:i}):null};fn.displayName="Presence";function Id(e){const[t,n]=F(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,l]=Ad(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Y(()=>{const d=Ar(r.current);i.current=a==="mounted"?d:"none"},[a]),Zt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Ar(d);e?l("MOUNT"):p==="none"||d?.display==="none"?l("UNMOUNT"):l(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Zt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=_=>{const f=Ar(r.current).includes(CSS.escape(_.animationName));if(_.target===t&&f&&(l("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=_=>{_.target===t&&(i.current=Ar(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:de(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Ar(e){return e?.animationName||"none"}function Md(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 bi(e,t=[]){let n=[];function r(i,s){const a=vt(s),l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=wt(_);if(f)return f;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 ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Pd(o,...t)]}function Pd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function jt(e){const t=X(e);return Y(()=>{t.current=e}),ie(()=>(...n)=>t.current?.(...n),[])}var Dd=vt(void 0);function Ld(e){const t=wt(Dd);return e||t||"ltr"}function Ud(e,[t,n]){return Math.min(n,Math.max(t,e))}function zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Fd(e,t){return hn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[vi]=bi(Ao),[Vd,dt]=vi(Ao),wi=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,l]=F(null),[d,h]=F(null),[u,p]=F(null),[_,f]=F(null),[g,b]=F(null),[m,E]=F(0),[y,k]=F(0),[x,T]=F(!1),[C,S]=F(!1),v=Vt(t,P=>l(P)),N=Ld(o);return c(Vd,{scope:n,type:r,dir:N,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:_,onScrollbarXChange:f,scrollbarXEnabled:x,onScrollbarXEnabledChange:T,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:C,onScrollbarYEnabledChange:S,onCornerWidthChange:E,onCornerHeightChange:k,children:c(pn.div,{dir:N,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});wi.displayName=Ao;var Ni="ScrollAreaViewport",Ti=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=dt(Ni,n),a=X(null),l=Vt(t,a,s.onViewportChange);return c(me,{children:[c("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),c(pn.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ti.displayName=Ni;var Nt="ScrollAreaScrollbar",Io=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return Y(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?c(jd,{...r,ref:t,forceMount:n}):o.type==="scroll"?c(zd,{...r,ref:t,forceMount:n}):o.type==="auto"?c(xi,{...r,ref:t,forceMount:n}):o.type==="always"?c(Mo,{...r,ref:t}):null});Io.displayName=Nt;var jd=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),[i,s]=F(!1);return Y(()=>{const a=o.scrollArea;let l=0;if(a){const d=()=>{window.clearTimeout(l),s(!0)},h=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),c(fn,{present:n||i,children:c(xi,{"data-state":i?"visible":"hidden",...r,ref:t})})}),zd=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Dr(()=>l("SCROLL_END"),100),[a,l]=Fd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return Y(()=>{if(a==="idle"){const d=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,l]),Y(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const p=()=>{const _=d[h];u!==_&&(l("SCROLL"),s()),u=_};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[o.viewport,i,l,s]),c(fn,{present:n||a!=="hidden",children:c(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:zt(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:zt(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),xi=ee((e,t)=>{const n=dt(Nt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=F(!1),a=e.orientation==="horizontal",l=Dr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return gn(n.viewport,l),gn(n.content,l),c(fn,{present:r||i,children:c(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=dt(Nt,e.__scopeScrollArea),i=X(null),s=X(0),[a,l]=F({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ai(a.viewport,a.content),h={...r,sizes:a,onSizesChange:l,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,_){return Wd(p,s.current,a,_)}return n==="horizontal"?c(Yd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,_=Ii(p,a,o.dir);i.current.style.transform=`translate3d(${_}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?c(Hd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,_=Ii(p,a);i.current.style.transform=`translate3d(0, ${_}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Yd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=dt(Nt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarXChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Mr(s.paddingLeft),paddingEnd:Mr(s.paddingRight)}})}})}),Hd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=dt(Nt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarYChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Mr(s.paddingTop),paddingEnd:Mr(s.paddingBottom)}})}})}),[$d,Ci]=vi(Nt),ki=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:d,onWheelScroll:h,onResize:u,...p}=e,_=dt(Nt,n),[f,g]=F(null),b=Vt(t,v=>g(v)),m=X(null),E=X(""),y=_.viewport,k=r.content-r.viewport,x=jt(h),T=jt(l),C=Dr(u,10);function S(v){if(m.current){const N=v.clientX-m.current.left,P=v.clientY-m.current.top;d({x:N,y:P})}}return Y(()=>{const v=N=>{const P=N.target;f?.contains(P)&&x(N,k)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[y,f,k,x]),Y(T,[r,T]),gn(f,C),gn(_.content,C),c($d,{scope:n,scrollbar:f,hasThumb:o,onThumbChange:jt(i),onThumbPointerUp:jt(s),onThumbPositionChange:T,onThumbPointerDown:jt(a),children:c(pn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:zt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),m.current=f.getBoundingClientRect(),E.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",_.viewport&&(_.viewport.style.scrollBehavior="auto"),S(v))}),onPointerMove:zt(e.onPointerMove,S),onPointerUp:zt(e.onPointerUp,v=>{const N=v.target;N.hasPointerCapture(v.pointerId)&&N.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=E.current,_.viewport&&(_.viewport.style.scrollBehavior=""),m.current=null})})})}),Ir="ScrollAreaThumb",Oi=ee((e,t)=>{const{forceMount:n,...r}=e,o=Ci(Ir,e.__scopeScrollArea);return c(fn,{present:n||o.hasThumb,children:c(Bd,{ref:t,...r})})}),Bd=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=dt(Ir,n),s=Ci(Ir,n),{onThumbPositionChange:a}=s,l=Vt(t,u=>s.onThumbChange(u)),d=X(void 0),h=Dr(()=>{d.current&&(d.current(),d.current=void 0)},100);return Y(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const _=Kd(u,a);d.current=_,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),c(pn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:zt(e.onPointerDownCapture,u=>{const p=u.target.getBoundingClientRect(),_=u.clientX-p.left,f=u.clientY-p.top;s.onThumbPointerDown({x:_,y:f})}),onPointerUp:zt(e.onPointerUp,s.onThumbPointerUp)})});Oi.displayName=Ir;var Po="ScrollAreaCorner",Ri=ee((e,t)=>{const n=dt(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c(Gd,{...e,ref:t}):null});Ri.displayName=Po;var Gd=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=dt(Po,n),[i,s]=F(0),[a,l]=F(0),d=!!(i&&a);return gn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),l(h)}),gn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?c(pn.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Mr(e){return e?parseInt(e,10):0}function Ai(e,t){const n=e/t;return isNaN(n)?0:n}function Pr(e){const t=Ai(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Wd(e,t,n,r="ltr"){const o=Pr(n),i=o/2,s=t||i,a=o-s,l=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return Mi([l,d],u)(e)}function Ii(e,t,n="ltr"){const r=Pr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],d=Ud(e,l);return Mi([0,s],[0,a])(d)}function Mi(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 Pi(e,t){return e>0&&e<t}var Kd=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function Dr(e,t){const n=jt(e),r=X(0);return Y(()=>()=>window.clearTimeout(r.current),[]),de(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function gn(e,t){const n=jt(t);Zt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Di=wi,qd=Ti,Xd=Ri;function Zd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var _n={},jn={},Li={},zn={},Yn={},Hn={},Ui;function Do(){if(Ui)return Hn;Ui=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.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 Hn.EventEmitter=e,Hn}var En={},Fi;function $n(){return Fi||(Fi=1,Object.defineProperty(En,"__esModule",{value:!0}),En.DisconnectionReason=En.ConnectionStatus=void 0,En.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},En.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),En}var Vi;function Lo(){if(Vi)return Yn;Vi=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.BaseConnection=void 0;const e=Do(),t=$n();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 Yn.BaseConnection=n,Yn}var ji={},zi;function at(){return zi||(zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=x,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(S,v=e.SynapseErrorCode.UNKNOWN,N={}){super(S);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=v,this.timestamp=new Date,this.cause=N.cause,this.context=N.context,this.hint=N.hint,this.reason=N.reason,this.displayMessage=N.displayMessage||N?.hint||S,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(S,v,N,P){const B=n.makeMessage(v,N,S);super(B,e.SynapseErrorCode.API,{cause:N,context:{status:v,hasBody:!!N},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:S||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=N,this.headers=P}static makeMessage(S,v,N){const P=v instanceof Error?v.message:N;return S&&P?`HTTP ${S}: ${P}`:S?`${S} status code (no body)`:P||"(no status code or body)"}static generate(S,v,N,P){if(!S)return new r({message:N});const B=v?.error,G=B&&typeof B=="object"&&!Array.isArray(B)?B:void 0;switch(S){case 400:return new i(N||"Bad Request",S,G,P);case 401:return new s(N||"Unauthorized",S,G,P);case 403:return new a(N||"Permission Denied",S,G,P);case 404:return new l(N||"Not Found",S,G,P);case 405:return new d(N||"Method Not Allowed",S,G,P);case 429:return new h(N||"Rate Limit Exceeded",S,G,P);case 500:return new u(N||"Internal Server Error",S,G,P);default:return new n(N||"API Error",S,G,P)}}}e.APIError=n;class r extends n{constructor({message:C}={}){super(C||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:C}={}){super(C||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class l extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="NotFoundError"}}e.NotFoundError=l;class d extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONNECTION,S),this.name="ConnectionError"}}e.ConnectionError=p;class _ extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.RECORDING,S),this.name="RecordingError"}}e.RecordingError=_;class f extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.AUTH,S),this.name="AuthenticationError"}}e.AuthenticationError=f;class g extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.FILE,S),this.name="FileError"}}e.FileError=g;class b extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.SESSION,S),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.MESSAGE,S),this.name="MessageError"}}e.MessageError=m;class E extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.STORE,S),this.name="StoreError"}}e.StoreError=E;class y extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONFIGURATION,S),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.VALIDATION,S),this.name="ValidationError"}}e.ValidationError=k;function x(T,C,S,v={}){if(T instanceof C)return T;const N={...v,context:{...T instanceof t?T.context:void 0,...v.context},hint:v.hint??(T instanceof t?T.hint:void 0),reason:v.reason??(T instanceof t?T.reason:void 0),cause:v.cause??T};if(T instanceof t)return new C(T.message,N);const P=T instanceof Error&&T.message?T.message:S;return new C(P,N)}})(ji)),ji}var Yi;function Hi(){if(Yi)return zn;Yi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.WebSocketConnection=void 0;const e=Lo(),t=$n(),n=at();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const l=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(l)}}handleError(s){}handleClose(s){const a=s.wasClean,l=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(l===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):l===1001||l===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):l===4001||l===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):l===4401||l===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(l===4401?"Session token expired":"Session credentials rejected")):l===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):l===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:l,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const l=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(l),l}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return zn.WebSocketConnection=r,zn}var Bn={},$i={},Bi;function Gi(){return Bi||(Bi=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})($i)),$i}var Wi;function Ki(){if(Wi)return Bn;Wi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.SSEConnection=void 0;const e=Lo(),t=$n(),n=Gi(),r=at();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const l=new AbortController;this.activeStreamController=l,this.streamChat(a,l)}postChat(a,l,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(l),signal:d.signal})}async streamChat(a,l){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,l);if(h.status===401&&this.config.auth.onUnauthorized){const f=await this.config.auth.onUnauthorized();if(l.signal.aborted)return;f&&(h=await this.postChat(d,a,l))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),p=new TextDecoder;let _="";for(;;){const{done:f,value:g}=await u.read();if(f)break;_+=p.decode(g,{stream:!0}),_=this.extractJsonObjects(_)}_.trim().length>0&&this.extractJsonObjects(_)}catch(h){if(l.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===l&&(this.activeStreamController=null)}}extractJsonObjects(a){let l=0;for(;l<a.length;){const d=a.indexOf("{",l);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const p=JSON.parse(u);this.handleMessage(p)}catch(p){const _=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(_)}l=h+1}return""}findObjectEnd(a,l){let d=0,h=!1,u=!1;for(let p=l;p<a.length;p++){const _=a[p];if(h){u?u=!1:_==="\\"?u=!0:_==='"'&&(h=!1);continue}if(_==='"')h=!0;else if(_==="{")d++;else if(_==="}"&&(d--,d===0))return p}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Bn.SSEConnection=o,Bn}var qi;function Xi(){return qi||(qi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Hi(),n=Ki(),r=at();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})(Li)),Li}var Gn={},Zi;function Uo(){if(Zi)return Gn;Zi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix-ws.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Gn.getConfig=r,Gn}var Wn={},Kn={},Ji;function Lr(){if(Ji)return Kn;Ji=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.HttpClient=void 0;const e=at();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const l=this.buildUrl(r,o?.params),d=await fetch(l,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(l){if(s=l,a===i||!(l instanceof TypeError&&l.message==="Failed to fetch"||l instanceof DOMException&&l.name==="AbortError"||l instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Kn.HttpClient=t,Kn}var qn={},Xn={},Qi;function Zn(){if(Qi)return Xn;Qi=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.BaseResource=void 0;let e=class{constructor(t){R(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return Xn.BaseResource=e,Xn}var ea;function ta(){if(ea)return qn;ea=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Session=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:l}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...l&&{nps_base5:l}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return qn.Session=t,qn}var Jn={},na;function Fo(){if(na)return Jn;na=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.Config=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return Jn.Config=t,Jn}var ra={},oa;function sa(){return oa||(oa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Lr(),n=Uo(),r=Fo(),o=new Map,i=(l,d)=>`${l.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(l){const d=l.serverUrl||(0,n.getConfig)(l.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,l.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":l.agentId,...l.channel&&{"x-channel":l.channel}}}),_=new r.Config(p).retrieve(l.agentId);return _.catch(()=>{o.get(h)===_&&o.delete(h)}),o.set(h,_),_}function a(l){const d=o.get(l);return d&&o.delete(l),d}})(ra)),ra}var Qn={},ia;function Vo(){if(ia)return Qn;ia=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.Auth=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Qn.Auth=t,Qn}var er={},yn={},aa;function jo(){return aa||(aa=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.ErrorType=yn.SYNAPSE_RECOVERY_REASON=void 0,yn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},yn.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),yn}var tr={},la;function zo(){if(la)return tr;la=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.ErrorUtils=void 0;const e=at();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return tr.ErrorUtils=t,tr}var ca={},da;function ua(){return da||(da=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=l;const t=Lr(),n=Uo(),r=zo(),o=Vo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),p=i.get(u);if(p)return p;const _=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),f=new o.Auth(_).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return f.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===f&&i.delete(u)}),i.set(u,f),f}function l(d){const h=i.get(d);return h&&i.delete(d),h}})(ca)),ca}var ha;function Jd(){if(ha)return er;ha=1,Object.defineProperty(er,"__esModule",{value:!0}),er.TokenManager=void 0;const e=at(),t=jo(),n=zo(),r=ua();let o=class{constructor(i,s,a,l){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=l.partnerAuthToken,this.refreshToken=l.refreshToken,this.onTokenExchange=l.onTokenExchange,this._level=l.level,this._userId=l.userId,l.sessToken&&(this.sessToken=l.sessToken,this.httpClient.setAuthorization(l.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(l.serverUrl,a,l.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,l){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,l,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return er.TokenManager=o,er}var nr={},ma;function Qd(){var n;if(ma)return nr;ma=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceResource=void 0;const e=Zn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return nr.VoiceResource=t,nr}var pa;function fa(){if(pa)return Wn;pa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ResourceManager=void 0;const e=Lr(),t=ta(),n=at(),r=Fo(),o=sa(),i=Vo(),s=Jd(),a=Qd();class l{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:p,intent:_,user_location:f,referer:g,...b}=u||{},m=this.tokenManager.userId||h,E={...m&&{user_id:m},...p&&{user_context:p},...(_||Object.keys(b).length>0)&&{session_context:{..._&&{intent:_},...f&&{user_location:f},...b}},...g&&{referer:g}},y=await this.session.create(E);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:_,feedbackReason:f,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:p,feedbacks:_,feedbackReason:f,npsBase5:g})}async callTool(h,u,p,_){return await this.session.callTool(h,u,p,_)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Wn.ResourceManager=l,Wn}var rr={},ga={},_a;function Yo(){return _a||(_a=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)}})(ga)),ga}var Ea={},ya;function eu(){return ya||(ya=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=at();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[]);R(this,"pendingSizes",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type),this.pendingSizes=s.map(a=>a.size)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[],sizes:this.pendingSizes||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.map((a,l)=>({entry:a,file:this.pendingFiles[l]})).filter(({entry:a,file:l})=>l&&a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const{entry:l,file:d}=s[a],h=await fetch(l.url,this.buildUploadRequest(l,d));if(!h.ok)throw new t.FileError(`Failed to upload ${d.name} to URL ${a+1}: ${h.status} ${h.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(l.id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}buildUploadRequest(o,i){if(o.fields){const s=new FormData;for(const[a,l]of Object.entries(o.fields))s.append(a,l);return s.append("file",i),{method:"POST",body:s}}return{method:"PUT",body:i,headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"}}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[],this.pendingSizes=[]}}e.Filemanager=n})(Ea)),Ea}var gt={},Sa;function Ur(){if(Sa)return gt;Sa=1,Object.defineProperty(gt,"__esModule",{value:!0}),gt.SYNAPSE_REALTIME_RESERVED_EVENTS=gt.SYNAPSE_REALTIME_ERROR_CODES=gt.SYNAPSE_REALTIME_EVENTS=gt.SYNAPSE_MESSAGE_TYPES=void 0;const e=Yo();return gt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,gt.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"},gt.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"},gt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},gt}var or={},ba;function tu(){if(ba)return or;ba=1,Object.defineProperty(or,"__esModule",{value:!0}),or.AudioManager=void 0;const e=at();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return or.AudioManager=t,or}var va;function wa(){if(va)return rr;va=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.MessageManager=void 0;const e=Yo(),t=eu(),n=Ur(),r=tu(),o=at();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:l,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,file_sizes:this.fileManager.getPendingFileState().sizes,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(l&&l.length>0){const p=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:l,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:l,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:_}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...l&&{audio:l},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},..._&&{initial_prompts:_}};return}const f=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:p})}else s?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},..._&&{initial_prompts:_},...p&&{tool_result:p}}}:l&&l?.audio&&l?.format?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:l?.audio,format:l?.format,...h&&{tool_declined:h},...p&&{tool_result:p}}}:p&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:p}});if(!g){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}f.sendMessage(g)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(l=>{this.sendSocketMessage({urls:l})}).catch(l=>{const d=this.toFileError(l,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,l)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const l={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,l)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,l)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const l={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,l);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const l=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),l={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(l)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const l=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(l),l}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,l=>{const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(l){const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,l,d){return(0,o.normalizeError)(s,o.FileError,a,{context:l,hint:d})}toRecordingError(s,a,l,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:l,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return rr.MessageManager=i,rr}var Na={},Ta;function nu(){return Ta||(Ta=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})(Na)),Na}var sr={},ir={},xa;function ru(){if(xa)return ir;xa=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),l=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(l)};l()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return ir.VoiceAudioAnalyser=t,ir}var Sn={},Ca;function ka(){return Ca||(Ca=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.VOICE_AGENT_EVENTS=Sn.VOICE_AGENT_STATE=void 0,Sn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Sn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Sn}var Oa;function ou(){if(Oa)return sr;Oa=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.VoiceAgent=void 0;const e=Do(),t=ru(),n=at(),r=ka(),o=3e3,i=8,s=3600*1e3,a=600;function l(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const _=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(_),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),_=new RTCPeerConnection({iceServers:p,iceTransportPolicy:"all"});this.pc=_,this.dataChannel=_.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(E,u)),_.ontrack=E=>this.handleRemoteTrack(E),_.onconnectionstatechange=()=>{_.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(_.connectionState==="failed"||_.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},_.oniceconnectionstatechange=()=>{(_.iceConnectionState==="connected"||_.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):_.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const f=await _.createOffer();await _.setLocalDescription(f);const g=this.config.iceGatheringTimeoutMs??o;await l(_,g);const b=E=>({sdp:_.localDescription.sdp,type:_.localDescription.type,pc_id:this.pcId,request_data:{session_id:E.sessionId,token:E.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(b(h))}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(b(y))}else throw E}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,_.signalingState==="closed")return;await _.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(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const f=await this.getCredentials();p=await this.resourceManager.getVoiceIceServers(f.sessionId)}else throw _}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,_=>{_?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return sr.VoiceAgent=d,sr}var Ra;function su(){if(Ra)return jn;Ra=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.SynapseSDK=void 0;const e=Xi(),t=$n(),n=Uo(),r=fa(),o=wa(),i=Ur(),s=Do(),a=at(),l=jo(),d=nu(),h=Yo(),u=ou();class p{constructor(f){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={...f,environment:f.environment||"production"},this.connectionType=f.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const f=await this.resourceManager.refreshBearer();if(!f)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(g){this.emitError(this.toConnectionError(g,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return f}async startSession(f){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,f=void 0),await this.resourceManager.ensureCredentials();const g=f?.session_id?f:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:f,files:g,audio:b,tool_declined:m,tool_id:E,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:f,files:g,audio:b,...m&&{tool_declined:m},...E&&{tool_id:E},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(T){this.emitError(T)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:f,feedback:g,feedbackReason:b});break}}async sendSessionFeedback(f,g){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!f?.length&&!g){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:f,npsBase5:g});break}}on(f,g){this.sdkEventEmitter.on(f,g)}off(f,g){this.sdkEventEmitter.off(f,g)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(f){return await this.resourceManager.getSessionMessages(f)}async callTool(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,f,g,b);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let E={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,E);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:f,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:f,onError:g})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const f=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(f),f}}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(f){if(f instanceof a.APIError){const g=f.reason??(f.status===401||f.status===403?l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:f.error?.msg||f.message,error:f.error,code:f.code,...g&&{reason:g},status:f.status,context:f.context}}return f instanceof a.SynapseError?{message:f.displayMessage||f.message,code:f.code,...f.reason&&{reason:f.reason},context:f.context}:f instanceof Error?{message:f.message}:{message:"An unexpected error occurred"}}emitError(f){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(f))}toSessionError(f,g,b,m){return(0,a.normalizeError)(f,a.SessionError,g,{context:b,hint:m})}async initializeConnection(f){if(this.closeConnection(),!f.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=f;const g=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?g.WEBSOCKET_URL:g.BASE_API_URL,E=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:E||m,auth:{sessionId:f.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(g=>{this.onIncomingSocketMessage(g)}),this.connection.onError(g=>{this.onRealtimeConnectionError(g)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const f=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==f||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(g.code);if(b){await this.handleRecovery(b,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(f){if(f instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(f.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:f.message,code:f.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,f);const g=f instanceof a.APIError?f:this.toConnectionError(f,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const f=this.resourceManager.getSessToken();if(!f){const g=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(g),g}this.messageManager.sendSocketAuthMessage(f)}onIncomingSocketMessage(f){switch(f.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(f);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(f);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(f);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(f);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:f.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const f=this.resourceManager.getLevel();return f?f==="user":!!this.config.authToken}statusOf(f){if(f instanceof a.APIError)return f.status;if(f instanceof a.SynapseError&&typeof f.context?.status=="number")return f.context.status}emitRecoveryError(f,g,b){this.emitError(new a.SessionError(g,{reason:f,cause:b,context:{stage:"connectionRecovery",reason:f}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(f,g){if(f===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(f){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(f){const g=this.statusOf(f);if(g!==403&&g!==401){this.emitError(this.toSessionError(f,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",f)}}async recoverMissingSession(){const f=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!f){this.closeConnection(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(f);await this.connectTo(g);return}catch(g){const b=this.statusOf(g);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);return}try{await this.connectTo(await this.createNewSession())}catch(m){const E=this.statusOf(m);if(E===401||E===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(f){await this.initializeConnection(f),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(f,g,b,m){return(0,a.normalizeError)(f,a.ConnectionError,g,{context:b,hint:m})}scheduleReconnect(f){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(f);return}const g=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(f)}}},g)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return jn.SynapseSDK=p,jn}var Aa={},Ia;function iu(){return Ia||(Ia=1,Object.defineProperty(Aa,"__esModule",{value:!0})),Aa}var Fr={},Ma;function au(){return Ma||(Ma=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.USER_FEEDBACK=void 0,Fr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Fr}var Pa={},Da;function lu(){return Da||(Da=1,Object.defineProperty(Pa,"__esModule",{value:!0})),Pa}var ar={},La;function cu(){if(La)return ar;La=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.ToolCall=void 0;const e=Zn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return ar.ToolCall=t,ar}var Ze={},Ua;function du(){if(Ua)return Ze;Ua=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 Fa={},Va;function uu(){return Va||(Va=1,Object.defineProperty(Fa,"__esModule",{value:!0})),Fa}var ja={},za;function hu(){return za||(za=1,Object.defineProperty(ja,"__esModule",{value:!0})),ja}var lr={},Ya;function mu(){if(Ya)return lr;Ya=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(lr.SYNAPSE_CONVERSATION=e={})),lr}var bn={},Ha;function pu(){return Ha||(Ha=1,(function(e){var t=bn&&bn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=bn&&bn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(ka(),e)})(bn)),bn}var $a;function fu(){return $a||($a=1,(function(e){var t=_n&&_n.__createBinding||(Object.create?(function(T,C,S,v){v===void 0&&(v=S);var N=Object.getOwnPropertyDescriptor(C,S);(!N||("get"in N?!C.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return C[S]}}),Object.defineProperty(T,v,N)}):(function(T,C,S,v){v===void 0&&(v=S),T[v]=C[S]})),n=_n&&_n.__exportStar||function(T,C){for(var S in T)S!=="default"&&!Object.prototype.hasOwnProperty.call(C,S)&&t(C,T,S)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=su();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=Hi();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Ki();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Xi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n($n(),e);var l=fa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return l.ResourceManager}}),n(iu(),e);var d=ta();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(au(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=ua();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(lu(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var _=sa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return _.prefetchAgentConfig}});var f=cu();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return f.ToolCall}}),n(du(),e);var g=wa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(Ur(),e),n(uu(),e);var b=Lr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=at();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 E=jo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return E.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return E.SYNAPSE_RECOVERY_REASON}});var y=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(hu(),e);var k=Gi();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var x=Ur();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(mu(),e),n(pu(),e)})(_n)),_n}var M=fu();function Ba(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=Ba(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ga(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ba(e))&&(r&&(r+=" "),r+=t);return r}const gu=(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},_u=(e,t)=>({classGroupId:e,validator:t}),Wa=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Vr="-",Ka=[],Eu="arbitrary..",yu=e=>{const t=bu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Su(o);const i=o.split(Vr),s=i[0]===""&&i.length>1?1:0;return qa(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?gu(a,s):s:a||Ka}return n[o]||Ka}}},qa=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const l=qa(e,t+1,o);if(l)return l}const i=n.validators;if(i===null)return;const s=t===0?e.join(Vr):e.slice(t).join(Vr),a=i.length;for(let l=0;l<a;l++){const d=i[l];if(d.validator(s))return d.classGroupId}},Su=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?Eu+r:void 0})(),bu=e=>{const{theme:t,classGroups:n}=e;return vu(n,t)},vu=(e,t)=>{const n=Wa();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];wu(s,t,n,r)}},wu=(e,t,n,r)=>{if(typeof e=="string"){Nu(e,t,n);return}if(typeof e=="function"){Tu(e,t,n,r);return}xu(e,t,n,r)},Nu=(e,t,n)=>{const r=e===""?t:Xa(t,e);r.classGroupId=n},Tu=(e,t,n,r)=>{if(Cu(e)){Ho(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(_u(n,e))},xu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,l]=o[s];Ho(l,Xa(t,a),n,r)}},Xa=(e,t)=>{let n=e;const r=t.split(Vr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Wa(),n.nextPart.set(s,a)),n=a}return n},Cu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,ku=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="!",Za=":",Ou=[],Ja=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Ru=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,d;const h=o.length;for(let g=0;g<h;g++){const b=o[g];if(s===0&&a===0){if(b===Za){i.push(o.slice(l,g)),l=g+1;continue}if(b==="/"){d=g;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(l);let p=u,_=!1;u.endsWith($o)?(p=u.slice(0,-1),_=!0):u.startsWith($o)&&(p=u.slice(1),_=!0);const f=d&&d>l?d-l:void 0;return Ja(i,_,p,f)};if(t){const o=t+Za,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Ja(Ou,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Au=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",l=t.has(s);a||l?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},Iu=e=>({cache:ku(e.cacheSize),parseClassName:Ru(e),sortModifiers:Au(e),...yu(e)}),Mu=/\s+/,Pu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Mu);let l="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:_,baseClassName:f,maybePostfixModifierPosition:g}=n(h);if(u){l=h+(l.length>0?" "+l:l);continue}let b=!!g,m=r(b?f.substring(0,g):f);if(!m){if(!b){l=h+(l.length>0?" "+l:l);continue}if(m=r(f),!m){l=h+(l.length>0?" "+l:l);continue}b=!1}const E=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=_?E+$o:E,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,b);for(let T=0;T<x.length;++T){const C=x[T];s.push(y+C)}l=h+(l.length>0?" "+l:l)}return l},Du=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Qa(n))&&(o&&(o+=" "),o+=r);return o},Qa=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Qa(e[r]))&&(n&&(n+=" "),n+=t);return n},Lu=(e,...t)=>{let n,r,o,i;const s=l=>{const d=t.reduce((h,u)=>u(h),e());return n=Iu(d),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const d=r(l);if(d)return d;const h=Pu(l,n);return o(l,h),h};return i=s,(...l)=>i(Du(...l))},Uu=[],je=e=>{const t=n=>n[e]||Uu;return t.isThemeGetter=!0,t},el=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tl=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Fu=/^\d+\/\d+$/,Vu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ju=/\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$/,zu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vn=e=>Fu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Yt=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Pt=e=>Vu.test(e),$u=()=>!0,Bu=e=>ju.test(e)&&!zu.test(e),nl=()=>!1,Gu=e=>Yu.test(e),Wu=e=>Hu.test(e),Ku=e=>!H(e)&&!$(e),qu=e=>wn(e,al,nl),H=e=>el.test(e),Jt=e=>wn(e,ll,Bu),Go=e=>wn(e,eh,ne),rl=e=>wn(e,sl,nl),Xu=e=>wn(e,il,Wu),jr=e=>wn(e,cl,Gu),$=e=>tl.test(e),cr=e=>Nn(e,ll),Zu=e=>Nn(e,th),ol=e=>Nn(e,sl),Ju=e=>Nn(e,al),Qu=e=>Nn(e,il),zr=e=>Nn(e,cl,!0),wn=(e,t,n)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Nn=(e,t,n=!1)=>{const r=tl.exec(e);return r?r[1]?t(r[1]):n:!1},sl=e=>e==="position"||e==="percentage",il=e=>e==="image"||e==="url",al=e=>e==="length"||e==="size"||e==="bg-size",ll=e=>e==="length",eh=e=>e==="number",th=e=>e==="family-name",cl=e=>e==="shadow",nh=()=>{const e=je("color"),t=je("font"),n=je("text"),r=je("font-weight"),o=je("tracking"),i=je("leading"),s=je("breakpoint"),a=je("container"),l=je("spacing"),d=je("radius"),h=je("shadow"),u=je("inset-shadow"),p=je("text-shadow"),_=je("drop-shadow"),f=je("blur"),g=je("perspective"),b=je("aspect"),m=je("ease"),E=je("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],T=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],S=()=>[$,H,l],v=()=>[vn,"full","auto",...S()],N=()=>[Yt,"none","subgrid",$,H],P=()=>["auto",{span:["full",Yt,$,H]},Yt,$,H],B=()=>[Yt,"auto",$,H],G=()=>["auto","min","max","fr",$,H],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...S()],Ee=()=>[vn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],V=()=>[e,$,H],le=()=>[...k(),ol,rl,{position:[$,H]}],Re=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",Ju,qu,{size:[$,H]}],Q=()=>[Bo,cr,Jt],I=()=>["","none","full",d,$,H],W=()=>["",ne,cr,Jt],re=()=>["solid","dashed","dotted","double"],ve=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],K=()=>[ne,Bo,ol,rl],Ae=()=>["","none",f,$,H],He=()=>["none",ne,$,H],ae=()=>["none",ne,$,H],Pe=()=>[ne,$,H],De=()=>[vn,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pt],breakpoint:[Pt],color:[$u],container:[Pt],"drop-shadow":[Pt],ease:["in","out","in-out"],font:[Ku],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pt],shadow:[Pt],spacing:["px",ne],text:[Pt],"text-shadow":[Pt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",vn,H,$,b]}],container:["container"],columns:[{columns:[ne,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:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Yt,"auto",$,H]}],basis:[{basis:[vn,"full","auto",a,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,vn,"auto","initial","none",H]}],grow:[{grow:["",ne,$,H]}],shrink:[{shrink:["",ne,$,H]}],order:[{order:[Yt,"first","last","none",$,H]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:Ee()}],w:[{w:[a,"screen",...Ee()]}],"min-w":[{"min-w":[a,"screen","none",...Ee()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...Ee()]}],h:[{h:["screen","lh",...Ee()]}],"min-h":[{"min-h":["screen","lh","none",...Ee()]}],"max-h":[{"max-h":["screen","lh",...Ee()]}],"font-size":[{text:["base",n,cr,Jt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,$,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,H]}],"font-family":[{font:[Zu,H,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]}],"line-clamp":[{"line-clamp":[ne,"none",$,Go]}],leading:[{leading:[i,...S()]}],"list-image":[{"list-image":["none",$,H]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,H]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",$,Jt]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[ne,"auto",$,H]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,H]}],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]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Re()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Yt,$,H],radial:["",$,H],conic:[Yt,$,H]},Qu,Xu]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:Q()}],"gradient-via-pos":[{via:Q()}],"gradient-to-pos":[{to:Q()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:W()}],"border-w-x":[{"border-x":W()}],"border-w-y":[{"border-y":W()}],"border-w-s":[{"border-s":W()}],"border-w-e":[{"border-e":W()}],"border-w-t":[{"border-t":W()}],"border-w-r":[{"border-r":W()}],"border-w-b":[{"border-b":W()}],"border-w-l":[{"border-l":W()}],"divide-x":[{"divide-x":W()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":W()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,$,H]}],"outline-w":[{outline:["",ne,cr,Jt]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",h,zr,jr]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",u,zr,jr]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[ne,Jt]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",p,zr,jr]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[ne,$,H]}],"mix-blend":[{"mix-blend":[...ve(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ve()}],"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":K()}],"mask-image-linear-to-pos":[{"mask-linear-to":K()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":K()}],"mask-image-t-to-pos":[{"mask-t-to":K()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":K()}],"mask-image-r-to-pos":[{"mask-r-to":K()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":K()}],"mask-image-b-to-pos":[{"mask-b-to":K()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":K()}],"mask-image-l-to-pos":[{"mask-l-to":K()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":K()}],"mask-image-x-to-pos":[{"mask-x-to":K()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":K()}],"mask-image-y-to-pos":[{"mask-y-to":K()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,H]}],"mask-image-radial-from-pos":[{"mask-radial-from":K()}],"mask-image-radial-to-pos":[{"mask-radial-to":K()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"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":K()}],"mask-image-conic-to-pos":[{"mask-conic-to":K()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Re()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,H]}],filter:[{filter:["","none",$,H]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,$,H]}],contrast:[{contrast:[ne,$,H]}],"drop-shadow":[{"drop-shadow":["","none",_,zr,jr]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",ne,$,H]}],"hue-rotate":[{"hue-rotate":[ne,$,H]}],invert:[{invert:["",ne,$,H]}],saturate:[{saturate:[ne,$,H]}],sepia:[{sepia:["",ne,$,H]}],"backdrop-filter":[{"backdrop-filter":["","none",$,H]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,$,H]}],"backdrop-contrast":[{"backdrop-contrast":[ne,$,H]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,$,H]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,$,H]}],"backdrop-invert":[{"backdrop-invert":["",ne,$,H]}],"backdrop-opacity":[{"backdrop-opacity":[ne,$,H]}],"backdrop-saturate":[{"backdrop-saturate":[ne,$,H]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,$,H]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,H]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",$,H]}],ease:[{ease:["linear","initial",m,$,H]}],delay:[{delay:[ne,$,H]}],animate:[{animate:["none",E,$,H]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,H]}],"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: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,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",$,H]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[ne,cr,Jt,Go]}],stroke:[{stroke:["none",...V()]}],"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"]}},rh=Lu(nh);function L(...e){return rh(Ga(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 oh=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},sh=e=>new Promise(t=>setTimeout(t,e)),dl=ee(({className:e,children:t,...n},r)=>c(Di,{ref:r,className:L("relative overflow-hidden",e),...n,children:[c(qd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),c(ul,{}),c(Xd,{})]}));dl.displayName=Di.displayName;const ul=ee(({className:e,orientation:t="vertical",...n},r)=>c(Io,{ref:r,orientation:t,className:L("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c(Oi,{className:"relative flex-1 rounded-full bg-border"})}));ul.displayName=Io.displayName;var ih=Symbol.for("react.lazy"),Yr=Oo[" use ".trim().toString()];function ah(e){return typeof e=="object"&&e!==null&&"then"in e}function hl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===ih&&"_payload"in e&&ah(e._payload)}function ml(e){const t=ch(e),n=ee((r,o)=>{let{children:i,...s}=r;hl(i)&&typeof Yr=="function"&&(i=Yr(i._payload));const a=st.toArray(i),l=a.find(uh);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var lh=ml("Slot");function ch(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(hl(o)&&typeof Yr=="function"&&(o=Yr(o._payload)),it(o)){const s=mh(o),a=hh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var dh=Symbol("radix.slottable");function uh(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dh}function hh(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 mh(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 pl=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,fl=Ga,ph=(e,t)=>n=>{var r;if(t?.variants==null)return fl(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=pl(h)||pl(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,..._}=h;return Object.entries(_).every(f=>{let[g,b]=f;return Array.isArray(b)?b.includes({...i,...a}[g]):{...i,...a}[g]===b})?[...d,u,p]:d},[]);return fl(e,s,l,n?.class,n?.className)},fh=ph("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"}}),Se=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>c(r?lh:"button",{className:L(fh({variant:t,size:n,className:e})),ref:i,...o}));Se.displayName="Button";const gh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_h=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),gl=e=>{const t=_h(e);return t.charAt(0).toUpperCase()+t.slice(1)},_l=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Eh=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var yh={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 Sh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>tt("svg",{ref:l,...yh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:_l("lucide",o),...!i&&!Eh(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>tt(d,h)),...Array.isArray(i)?i:[i]])),Ye=(e,t)=>{const n=ee(({className:r,...o},i)=>tt(Sh,{ref:i,iconNode:t,className:_l(`lucide-${gh(gl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=gl(e),n},bh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=Ye("chevron-down",bh),vh=[["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"}]],wh=Ye("ellipsis-vertical",vh),Nh=[["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"}]],El=Ye("file-text",Nh),Th=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],yl=Ye("info",Th),xh=[["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"}]],Ch=Ye("maximize-2",xh),kh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Oh=Ye("menu",kh),Rh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],dr=Ye("message-square-plus",Rh),Ah=[["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",Ah),Ih=[["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"}]],Mh=Ye("minimize-2",Ih),Ph=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Sl=Ye("plus",Ph),Dh=[["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"}]],Lh=Ye("rotate-ccw",Dh),Uh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],bl=Ye("square",Uh),Fh=[["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",Fh),Vh=[["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"}]],wl=Ye("thumbs-down",Vh),jh=[["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"}]],zh=Ye("triangle-alert",jh),Yh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Tn=Ye("x",Yh),Hh=[["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"}]],$h=Ye("zoom-in",Hh),Nl=e=>{let t;const n=new Set,r=(a,l)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=l??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},Bh=(e=>e?Nl(e):Nl),Gh=e=>e;function Wh(e,t=Gh){const n=Vn.useSyncExternalStore(e.subscribe,Vn.useCallback(()=>t(e.getState()),[e,t]),Vn.useCallback(()=>t(e.getInitialState()),[e,t]));return Vn.useDebugValue(n),n}const Kh=e=>{const t=Bh(e),n=r=>Wh(t,r);return Object.assign(n,t),n},qh=(e=>Kh);function Xh(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)}}}},Zh=(e,t)=>(n,r,o)=>{let i={storage:Xh(()=>localStorage),partialize:g=>g,version:0,merge:(g,b)=>({...b,...g}),...t},s=!1;const a=new Set,l=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,b)=>(u(g,b),h());const p=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>p;let _;const f=()=>{var g,b;if(!d)return;s=!1,a.forEach(E=>{var y;return E((y=r())!=null?y:p)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(g=r())!=null?g:p))||void 0;return qo(d.getItem.bind(d))(i.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==i.version){if(i.migrate){const y=i.migrate(E.state,E.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,E.state];return[!1,void 0]}).then(E=>{var y;const[k,x]=E;if(_=i.merge(x,(y=r())!=null?y:p),n(_,!0),k)return h()}).then(()=>{m?.(_,void 0),_=r(),s=!0,l.forEach(E=>E(_))}).catch(E=>{m?.(void 0,E)})};return o.persist={setOptions:g=>{i={...i,...g},g.storage&&(d=g.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>f(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(l.add(g),()=>{l.delete(g)})},i.skipHydration||f(),_||p},Jh=Zh,Ne={USER:"user",ASSISTANT:"assistant"};var be=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(be||{}),_e=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(_e||{});let ut="";const ur=e=>`med-assist-store-${e}`,Qh=e=>{xn(),ut=ur(e)},em=200;let _t=null,hr=null;function xn(){if(hr&&(clearTimeout(hr),hr=null),!!_t){try{sessionStorage.setItem(_t.key,JSON.stringify(_t.value))}catch{}_t=null}}typeof window<"u"&&(window.addEventListener("pagehide",xn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&xn()}));const tm={getItem:()=>{if(!ut)return null;if(_t?.key===ut)return _t.value;try{const e=sessionStorage.getItem(ut);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{ut&&(_t&&_t.key!==ut&&xn(),_t={key:ut,value:t},hr||(hr=setTimeout(xn,em)))},removeItem:()=>{_t?.key===ut&&(_t=null),ut&&sessionStorage.removeItem(ut)}},Tl={sessionId:"",isStreaming:!1,recordingStatus:be.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:_e.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},xl={...Tl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=qh()(Jh((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:_e.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:be.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(Tl),await sessionStorage.removeItem(ut||ur(t().agentId))},clearUser:()=>{e(xl),sessionStorage.removeItem(ut||ur(t().agentId))}}),{name:"med-assist-store",storage:tm,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})})),nm=e=>{const t=ur(e);xn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(xl),n&&j.setState(n)},Xo=vt(null),rm=({children:e})=>{const[t,n]=F(null);return c(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},om=()=>{const e=wt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},sm=()=>{const e=wt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},im=()=>{const[e,t]=F(M.VOICE_AGENT_STATE.IDLE),[n,r]=F(!1),o=om(),i=j(h=>h.setError);Y(()=>{if(!o)return;const h=o.voice,u=_=>{t(_)},p=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(M.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(M.VOICE_AGENT_EVENTS.ERROR,p),()=>{h.off(M.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(M.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=de(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=de(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),l=de(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=de(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:l,toggleMute:d}},en=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));en.displayName="Card";const Cl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex flex-col space-y-1.5 p-6",e),...t}));Cl.displayName="CardHeader";const kl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("font-semibold leading-none tracking-tight",e),...t}));kl.displayName="CardTitle";const am=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("text-sm text-muted-foreground",e),...t}));am.displayName="CardDescription";const Ol=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("p-6 pt-0",e),...t}));Ol.displayName="CardContent";const Rl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex items-center p-6 pt-0",e),...t}));Rl.displayName="CardFooter";const Zo=5,Al=3,Il=10*1024*1024,Hr={width:384,height:600},$r=20,lm=400,cm=320,dm=560,um=150;function hm({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=de(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Hr.width-$r,y:window.innerHeight-Hr.height-$r},[]),[i,s]=F(()=>e??o()),[a,l]=F(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);Y(()=>{t||(u.current=!1)},[t]),ft(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),Y(()=>{if(!t||typeof window>"u")return;let g=null;const b=()=>{s(E=>{const y=Math.max(0,window.innerWidth-Hr.width-$r),k=Math.max(0,window.innerHeight-Hr.height-$r),x=Math.max(0,Math.min(E.x,y)),T=Math.max(0,Math.min(E.y,k));return x===E.x&&T===E.y?E:{x,y:T}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(b,um)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const p=de(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){l(!1);return}g.preventDefault(),l(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),_=de(g=>{if(!t||!a)return;const b=g.clientX-d.current.x,m=g.clientY-d.current.y,E=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(b,E)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[a,t]),f=de(()=>{!t||!a||(l(!1),r?.())},[a,r]);return Y(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",p),()=>{g.removeEventListener("mousedown",p)}},[t,p]),Y(()=>{if(a)return document.addEventListener("mousemove",_),document.addEventListener("mouseup",f),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",f),document.body.style.cursor="",document.body.style.userSelect=""}},[a,_,f]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Jo="#6B5CE0",mm="#F0F0F0",Br={background:mm,backgroundImage:void 0,primary:Jo,textColor:"black"},pm="rgba(0, 0, 0, 0.4)",fm="24px";function gm(e){if(e==="dark")return"white";if(e==="light")return"black"}function _m(e){const t=e?.primary??e?.primaryColor??Br.primary,n=e?.textColor??gm(e?.mode);return{background:e?.background??Br.background,backgroundImage:e?.backgroundImage??Br.backgroundImage,primary:t,primaryColor:t,textColor:n??Br.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Em(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const l=(o+i)/2;if(o!==i){const h=o-i;switch(a=l>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(l*100);return`${s} ${a}% ${d}%`}function ym(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,l=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(l=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),l=Math.round(l*100);const h=Math.round(d*100);return`${a} ${l}% ${h}%`}function Sm(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 Em(t);if(t.startsWith("rgb"))return ym(t);if(t.startsWith("hsl"))return Sm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Ml(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Ml(e)>.5?"0 0% 9%":"0 0% 98%"}function bm(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 vm(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 Pl(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=(_,f)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(_,f)};let l;try{l=Qo(n)}catch{l=Qo(Jo)}a("--primary",l),a("--primary-foreground",es(l)),a("--ring",l),a("--border-primary",l);const d=vm(l);for(const[_,f]of Object.entries(d))a(`--primary-${_}`,f);const h=es(l);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const _=i?"#191919":"#F0F0F0";try{a("--background",Qo(_))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${l} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",bm(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${l})`),a("--header-stroke",`hsl(${l} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${l} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${l} / 0.3)`)),s&&!o){const _=Ml(h)>.5;a("--header-tagline",_?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",l):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const _ of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${_}`,`var(--${p}-${_})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",l),a("--accent-foreground",es(l)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",fm),a("--theme-background-overlay",pm),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function tn({className:e,style:t}){return c("div",{className:L("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function ts(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Dl(){return c("div",{className:"px-3 pb-2 pt-1",children:[c(ts,{}),c("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[c("div",{className:"px-2 pt-2 pb-1",children:c(tn,{className:"h-5 w-3/5 rounded-md"})}),c("div",{className:"flex items-center justify-between px-1 py-1",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c("div",{className:"flex items-center gap-2",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c(tn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function wm(){const e=[{role:Ne.ASSISTANT,size:"h-16 w-[70%]"},{role:Ne.USER,size:"h-9 w-[45%]"},{role:Ne.ASSISTANT,size:"h-24 w-[75%]"},{role:Ne.USER,size:"h-9 w-[35%]"},{role:Ne.ASSISTANT,size:"h-16 w-[65%]"}];return c("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[c(ts,{}),e.map((t,n)=>c("div",{className:L("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:c(tn,{className:L("rounded-lg",t.size)})},n))]})}function Nm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return c("div",{"aria-hidden":"true",children:[c(ts,{}),Array.from({length:e},(n,r)=>c("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[c(tn,{className:L("h-5 rounded-md",t[r%t.length])}),c(tn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function Tm(e,t=[]){let n=[];function r(i,s){const a=vt(s);a.displayName=i+"Context";const l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=wt(_);if(f)return f;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 ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,xm(o,...t)]}function xm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Cm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=Cm.reduce((e,t)=>{const n=ml(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Ll={exports:{}},rs={};const km=Zd(Oo);var Ul;function Om(){if(Ul)return rs;Ul=1;var e=km;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 _=p(),f=r({inst:{value:_,getSnapshot:p}}),g=f[0].inst,b=f[1];return i(function(){g.value=_,g.getSnapshot=p,l(g)&&b({inst:g})},[u,_,p]),o(function(){return l(g)&&b({inst:g}),u(function(){l(g)&&b({inst:g})})},[u]),s(_),_}function l(u){var p=u.getSnapshot;u=u.value;try{var _=p();return!n(u,_)}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 Fl;function Rm(){return Fl||(Fl=1,Ll.exports=Om()),Ll.exports}var Am=Rm();function Im(){return Am.useSyncExternalStore(Mm,()=>!0,()=>!1)}function Mm(){return()=>{}}var os="Avatar",[Pm]=Tm(os),[Dm,Vl]=Pm(os),jl=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=F("idle");return c(Dm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:c(ns.span,{...r,ref:t})})});jl.displayName=os;var zl="AvatarImage",Yl=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Vl(zl,n),a=Lm(r,i),l=jt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Zt(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?c(ns.img,{...i,ref:t,src:r}):null});Yl.displayName=zl;var Hl="AvatarFallback",$l=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Vl(Hl,n),[s,a]=F(r===void 0);return Y(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),s&&i.imageLoadingStatus!=="loaded"?c(ns.span,{...o,ref:t}):null});$l.displayName=Hl;function Bl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Lm(e,{referrerPolicy:t,crossOrigin:n}){const r=Im(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=F(()=>Bl(i,e));return Zt(()=>{a(Bl(i,e))},[i,e]),Zt(()=>{const l=u=>()=>{a(u)};if(!i)return;const d=l("loaded"),h=l("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Gl=jl,Wl=Yl,Kl=$l;const ss=ee(({className:e,...t},n)=>c(Gl,{ref:n,className:L("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Gl.displayName;const ql=ee(({className:e,...t},n)=>c(Wl,{ref:n,className:L("aspect-square h-full w-full",e),...t}));ql.displayName=Wl.displayName;const is=ee(({className:e,...t},n)=>c(Kl,{ref:n,className:L("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Kl.displayName;const Xl=vt(!1);function Um({enabled:e,children:t}){return c(Xl.Provider,{value:e,children:t})}function Fm(){return wt(Xl)}const Zl="(max-width: 768px), (pointer: coarse)",Jl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Vm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Zl)?.matches??!1,t=Jl.test(navigator?.userAgent??"");return e||t}function Ql(){const[e,t]=F(Vm);return Y(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Zl),r=Jl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function jm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:l=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Ql(),p=Fm(),_=j(N=>N.displayMode)==="side_panel",f=p&&!u&&!_,g=j(N=>N.displayMode)==="full",b=j(N=>N.initialDisplayMode)==="full",m=!g&&l?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",E=j(N=>N.connectionStatus),y=j(N=>N.level)==="user",[k,x]=F(!1),T=X(null),C=ie(()=>a===M.VOICE_AGENT_STATE.CONNECTED||a===M.VOICE_AGENT_STATE.CONNECTING||a===M.VOICE_AGENT_STATE.LISTENING||a===M.VOICE_AGENT_STATE.SPEAKING||a===M.VOICE_AGENT_STATE.THINKING,[a]),S=de(()=>{k||(x(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,x(!1)},6e3),s())},[k,s]);Y(()=>{E===_e.CONNECTED&&(x(!1),T.current&&clearTimeout(T.current))},[E]);const v=(()=>{switch(E){case _e.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case _e.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case _e.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return c("div",{className:"px-6 py-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative flex-shrink-0",children:[c(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:c(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?c("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):c("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),c("div",{className:L("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,E===_e.CONNECTING&&"animate-pulse")})]}),c("div",{className:"flex flex-col",children:[r?c("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):c("p",{className:L("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",m),children:n||"Health Assist"}),c("div",{className:"flex items-center gap-1.5",children:c("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),c("div",{className:L("flex items-center",!f&&"gap-1"),children:[!C&&!y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:S,disabled:k,className:L("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",m),children:c(dr,{className:"w-5 h-5"})}),h&&y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:L("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(wh,{className:"w-5 h-5"})}),f&&c(Se,{onClick:d,type:"button",variant:"ghost",size:"icon",title:g?"Exit fullscreen":"Enter fullscreen",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:g?c(Mh,{className:"w-8 h-8"}):c(Ch,{className:"w-8 h-8"})}),(t||!b)&&c(Se,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(Tn,{className:"w-8 h-8"})})]})]})})}const as=ee(({className:e,...t},n)=>c("textarea",{className:L("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 ec({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=F(!1),[s,a]=F(""),l=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";Y(()=>{if(l){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,l]),Y(()=>{i(!1)},[e]);const h=()=>l?"text-green-600":"text-text-secondary",u=p=>{if(p===0)return"0 B";const _=1024,f=["B","KB","MB","GB"],g=Math.floor(Math.log(p)/Math.log(_));return`${(p/Math.pow(_,g)).toFixed(1)} ${f[g]}`.toLowerCase()};return!l||o?c("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[c("div",{className:`flex-shrink-0 ${h()}`,children:c(El,{className:"h-5 w-5"})}),c("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&c("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&c("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:c(Tn,{className:"h-3 w-3"})})]}):c("div",{className:`relative group flex-shrink-0 ${r}`,children:[c("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&c("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&c("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:c(Tn,{className:"h-3 w-3"})})]})}function ls({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return c("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&c("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),tc=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),zm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},nc=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),Ym=nt(()=>tc().then(e=>({default:e.ElicitationInput})));function Hm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:l,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:_,allowed:f,showStartNewChatButton:g,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:E,isAuthComponent:y,activeElicitationState:k,isFullScreen:x,showAttention:T}){const C=X(null),S=X(null),v=T?c("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,N=e.trim().length>0||a,P=!f||f.includes(M.SYNAPSE_CONVERSATION.AUDIO),B=!f||f.includes(M.SYNAPSE_CONVERSATION.VOICE),G=N||!P,he=N,pe=!f||f.includes(M.SYNAPSE_CONVERSATION.FILE),se=(d||p!==be.IDLE)&&!s,Ee=L("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":se?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),V=I=>{const W=Array.from(I.target.files||[]);W.length>0&&r(W)},le=()=>{d||(C.current&&(C.current.value=""),C.current?.click())},Re=I=>{I.key==="Enter"&&!I.shiftKey&&he&&!d&&(I.preventDefault(),n())},te=I=>{I.style.height="auto",I.style.overflow="hidden";const W=I.scrollHeight,re=x?20:28,ve=120,K=Math.max(re,Math.min(W,ve));I.style.height=K+"px",W>ve?I.style.overflow="auto":I.style.overflow="hidden"},Q=I=>{te(I.currentTarget)};return Y(()=>{S.current&&te(S.current)},[e]),Y(()=>{d||S.current?.focus()},[d]),g&&b?c("div",{className:"px-4 py-2 flex justify-unset",children:c("button",{type:"button",onClick:b,className:L("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[c("span",{children:"Start new chat"}),c(dr,{className:"w-5 h-5","aria-hidden":!0})]})}):c(me,{children:y?c(Xe,{fallback:c(Dl,{}),children:c(Ym,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:_,isMobile:u,onSend:n})}):x?c("div",{className:"mx-3 mb-3","data-name":"reply-box",children:c("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:I=>t(I.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:L("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),c("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[c("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(Sl,{className:"w-6 h-6",strokeWidth:1.5})})}),c("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(bl,{className:"w-4 h-4"})}):P&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0 p-2",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-6 h-6",strokeWidth:1.5})}),G&&!s?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):P&&B&&!s&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:E,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):c("div",{className:"px-3 pt-1",children:[c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("div",{className:"px-1 pt-1 pb-0",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:I=>t(I.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:L("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center shrink-0",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c(Sl,{className:"w-5 h-5",strokeWidth:1.5})})}),c("div",{className:"flex items-center gap-2 shrink-0",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(bl,{className:"w-4 h-4"})}):G?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):P&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),P&&B&&!s&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:E,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const $m=Xt(Hm),rc=vt(null),oc=rc.Provider;function Bm(){const e=wt(rc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function Gm({message:e,onDismiss:t}){return c(me,{children:[c("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),c("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:c("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[c("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),c("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:c(Tn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Wm(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=de(()=>{t(null)},[t]);return Y(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?c(Gm,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?c("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:c("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Km="Before we begin",qm=e=>`A quick note on how ${e} works and handles your information.`,Xm=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 Zm(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 sc=(e,t)=>{if(t){const n=Zm(t,e);if(n.length)return n}return Xm(e)},Jm="I agree and consent",Qm="By continuing, you consent to the above.",ep="Continue";function ic({botName:e,consentContent:t,isFullScreen:n}){return c(me,{children:[c("div",{className:"flex flex-col gap-1",children:[c("h2",{className:L("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Km}),c("p",{className:L("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:qm(e)})]}),c("div",{className:L("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:sc(e,t).map((r,o)=>c("p",{className:L("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function tp({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return c(ds,{isOpen:e,onClose:t,children:c("div",{className:L("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?c(ic,{botName:n,consentContent:o,isFullScreen:s}):c("div",{className:"flex flex-col gap-2",children:[c("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),sc(n,o).map((a,l)=>c("p",{className:L("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},l))]}),c(Se,{onClick:t,className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function np({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=F(!1);return e?c(ds,{isOpen:e,children:c("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:L("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[c(ic,{botName:t,consentContent:n,isFullScreen:o}),c("div",{className:"flex flex-col gap-1.5",children:[c("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[c("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),c("div",{"aria-hidden":"true",className:L("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&c("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:L("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Jm})]}),c("p",{className:L("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:Qm})]}),c(Se,{disabled:!i,onClick:()=>i&&r(),className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:ep})]})}):null}const rp=nt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),op=nt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),sp=nt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),ip=nt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),ap=nt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),lp=[{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"}],cp=[{Icon:rp,label:"Bad",score:1},{Icon:op,label:"Poor",score:2},{Icon:sp,label:"Okay",score:3},{Icon:ip,label:"Good",score:4},{Icon:ap,label:"Great!",score:5}];function dp(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function up({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,l]=F(null),[d,h]=F(new Set),[u,p]=F(!1),_=s&&a!==null?dp(a,t):t.form?.default?.length?t.form.default:lp,f=E=>{h(y=>{const k=new Set(y);return k.has(E)?k.delete(E):k.add(E),k})},g=E=>{l(E),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?c(ds,{isOpen:e,onClose:o,children:c("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[c("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),c("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[c("div",{className:"flex flex-col gap-1",children:[t.title&&c("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&c("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&c("div",{className:"flex items-center justify-between gap-1",children:cp.map(({Icon:E,label:y,score:k})=>{const x=a===k,T=a!==null&&!x;return c("button",{onClick:()=>g(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[c("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${T?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:c(Xe,{fallback:c("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:c(E,{})})}),c("span",{className:`text-[10px] leading-none transition-colors ${x?"text-primary/50 font-medium":T?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&_.length>0&&c("div",{className:"flex flex-col gap-2",children:_.map(E=>c("div",{onClick:()=>f(E.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(E.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:E.label},E.value))}),c(Se,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),c("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>p(E=>!E),children:[c("div",{className:"relative w-3 h-3 shrink-0",children:c("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&c("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),c("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function ac({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:l,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:_,activeElicitation:f,voiceAgentState:g,theme:b,feedbackModal:m,consentModal:E}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:T,tagline:C,iconUrl:S,onStartNewSession:v,showStartNewChatButton:N,onToggleDisplayMode:P,onOpenSessionDrawer:B}=Bm(),[G,he]=F(!1),[pe,se]=F(!1),[Ee,V]=F(!1),le=X(null),Re=j(z=>z.level),te=l,Q=te==="full",I=te==="side_panel",W=X(null),[re,ve]=F("");Y(()=>{W.current!==null&&W.current!==te&&ve(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),W.current=te},[te]);const K=ie(()=>_m(b),[b]),Ae=j(z=>z.setIsMobile),He=!!_,ae=de(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);ft(()=>{if(!le.current)return;const z=te==="full"?{...K,headerTinted:!1}:K;Pl(le.current,z),te==="full"&&!K.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),Pl(le.current,K))},[K,te]),Y(()=>{const z=()=>{const Ie=window?.innerWidth??0,we=navigator?.userAgent?.toLowerCase()??"",Le=Ie<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(we);he(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),ft(()=>{if(!e||!G||!le.current)return;const z=le.current;let Ie=null,we=null,Le=null,qe=window.visualViewport?.offsetTop??0,Ue=0;const Et=2,ht=80;if(window.visualViewport){const ze=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,Oe=window.visualViewport.offsetTop;Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Oe}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`,we&&clearTimeout(we),we=setTimeout(()=>{z.style.transition=""},100)})}},rt=()=>{ze()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,Oe=Date.now();Math.abs(Ge-qe)<Et||Oe-Ue<ht||(Ue=Oe,qe=Ge,Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",rt),window.visualViewport.addEventListener("scroll",Be),ze(),()=>{Ie&&cancelAnimationFrame(Ie),we&&clearTimeout(we),Le&&clearTimeout(Le),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 ze=()=>{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",ze),ze(),()=>{window.removeEventListener("resize",ze),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),Y(()=>{if(e&&!(I&&d==="push")){const z=le.current,Ie=window.scrollY,we=document.body.style.cssText,Le=document.documentElement.style.overflow,qe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ie}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",qe>0&&!G&&(document.body.style.paddingRight=`${qe}px`);let Ue=0;const Et=ze=>{Ue=ze.touches[0].clientY},ht=ze=>{if(ze.touches.length!==1)return;const rt=Ue-ze.touches[0].clientY;Ue=ze.touches[0].clientY;let Be=ze.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:Oe,scrollHeight:Bt,clientHeight:yt}=Be,an=Oe<=0&&rt<0,ln=Oe+yt>=Bt-1&&rt>0;if(!an&&!ln)return;break}Be=Be.parentElement}ze.preventDefault()};return z&&(z.addEventListener("touchstart",Et,{passive:!0}),z.addEventListener("touchmove",ht,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",Et),z.removeEventListener("touchmove",ht)),document.body.style.cssText=we,document.documentElement.style.overflow=Le,window.scrollTo(0,Ie)}}},[e,G,I,d]),Y(()=>{if(!(!I||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,I,d,h,u,p]);const{position:Pe,elementRef:De}=hm({enabled:e&&!G&&!Q&&!I});Y(()=>{le.current&&(De.current=le.current)},[De]);const xt=L("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!Q&&!I?"transition-all duration-300":"",G?"w-screen h-[100svh]":Q?"w-screen h-screen":I?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),$t=L("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",K.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":Q?"rounded-none border-0 flex-row":I?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return c("div",{ref:le,"data-mode":te,className:xt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...Q&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...Q&&!e&&{display:"none"},...I&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...I&&!e&&{display:"none"},...!G&&!Q&&!I&&{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:K.backgroundImage?"transparent":"hsl(var(--background))"}},children:[c("style",{children:`
|
|
2
2
|
/* Isolate widget from host website styles */
|
|
3
3
|
.synapse-chat-widget-container,
|
|
4
4
|
.synapse-chat-widget-container *,
|
|
@@ -35,25 +35,25 @@ var Qc=Object.defineProperty;var ed=(e,t,n)=>t in e?Qc(e,t,{enumerable:!0,config
|
|
|
35
35
|
.synapse-chat-widget-container [data-radix-scroll-area-viewport] {
|
|
36
36
|
overscroll-behavior: contain;
|
|
37
37
|
}
|
|
38
|
-
`}),c(en,{className:$t,"data-text-color":K.textColor,style:G?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[c("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:re}),!K.backgroundImage&&c("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${K.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:K.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),c(tp,{isOpen:Ee,onClose:()=>V(!1),botName:x,explicitDisclaimer:b?.explicitDisclaimer,consentContent:b?.consentContent,isFullScreen:Q}),E?.isOpen&&c(np,{isOpen:!0,botName:x,consentContent:b?.consentContent,onAccept:E.onAccept,isFullScreen:Q}),m?.isOpen&&c(up,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),Q&&n,Re==="user"&&!Q&&r,c("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[c("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...Q?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!Q&&!A&&{cursor:e?"grab":"default"}},children:c(jm,{onClose:y,showCloseButton:k,title:x,titleImg:T,tagline:C,iconUrl:S,startNewConversation:v,voiceAgentState:g,headerTinted:Q?!1:K.headerTinted,onToggleDisplayMode:D,onOpenSessionDrawer:Q?void 0:B})}),(()=>{const z=Q&&!!o,Ie=s&&g===I.VOICE_AGENT_STATE.IDLE?c(Xe,{fallback:c(Dl,{}),children:c($m,{value:s.value,onChange:s.onChange,onSend:He?ae: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:K,onStartNewChat:v,showStartNewChatButton:N,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:_,activeElicitationState:f,isFullScreen:Q&&!z,showAttention:s.showAttention})}):null,we={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Le=c(me,{children:[i&&a==="development"&&c("div",{className:"px-6 flex justify-center items-center",children:c("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),Q?c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:c("span",{className:"text-[10px] leading-[14px]",style:we,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):b?.explicitDisclaimer?c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c("div",{className:"flex justify-center items-center gap-1",children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:["AI can make mistakes. ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c(me,{children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c(yl,{className:"w-3 h-3"})]})]}),qe=o&&Q?o({composer:z?Ie:null,composerFooter:z?Le:null}):null;return c(me,{children:[c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[qe??t,c(Wm,{})]}),s&&!z&&c("div",{className:L("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[c("div",{className:L(Q&&"max-w-2xl mx-auto w-full"),children:Ie}),Le]})]})})()]})]})]})}function hp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function mp(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 pp(e){const t=new Date(e.c_at),n=mp(t),r=hp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function fp(){return c("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function gp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=pp(e);return c("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[c("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),c("div",{className:"flex items-center gap-2 w-full min-w-0",children:[c("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&c(fp,{})]})]})}function lc({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?c(Nm,{}):e.length===0?c("div",{className:"flex items-center justify-center h-full px-4 text-center",children:c("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):c(me,{children:e.map(o=>c(gp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function cc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:l,onClose:d}=e;return c(me,{children:[c("div",{className:L("absolute inset-0 z-[60] transition-opacity duration-200",l?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),c("div",{className:L("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",l?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:"flex items-center justify-between",children:[c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:c(Tn,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),c("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return c("div",{id:"synapse-session-sidebar","data-collapsed":s,className:L("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:L("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:c(Oh,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?c("button",{type:"button",onClick:o,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:c(dr,{className:"w-6 h-6"})}):c("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&c("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function _p(){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 Ep=180;function yp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=l=>{const d=l.label||l.value||"";d&&n({message:l.value||d,messageId:Date.now().toString()})};return c("div",{className:"flex-1 flex flex-col overflow-y-auto",children:c("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[c("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=Ep&&c("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:_p()}),e&&c("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&c("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((l,d)=>{const h=l.label||l.value||"";return h?c("button",{type:"button",onClick:()=>a(l),disabled:r,className:L("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&c("div",{children:[o,i]})]})})}const nn={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Cn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function Sp(e,t){return`${e}:${t}`}function dc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function uc(){const[e,t]=F(typeof navigator<"u"?navigator.onLine:!0);return Y(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const hc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),bp=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",vp=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}},wp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},mc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Np=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===I.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),l=n||a,d=n&&r?Cp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:mc(l,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const l=a.date?s.findIndex(d=>d.date===a.date):-1;if(l===-1)s.push({...a});else{const d=s[l];s[l]={...d,...hc(a),slots:a.slots??d.slots}}}return s},Tp=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,l=s.end_date||o.end_date;r[i]={...s,...hc(o),availability:Np({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:l,format:n})}}}return r},pc=e=>!!e&&Array.isArray(e.doctors),xp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!pc(e)||!pc(t))return e;const r=e.format||t.format;return{...t,doctors:Tp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Cp=(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},fc=(e,t)=>`${e}::${t}`,kp=e=>e<1e12?e*1e3:e,Op=(e,t)=>`${e}::${t}::answer`,Rp=e=>!!e?.tool_id&&!!e?.component;function Ap(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(Rp),i=r.timestamp?Qt(kp(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=>fc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[fc(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:Op(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Ip=Math.round(Il/(1024*1024)),gc=(e,t=0)=>e.length+t>Al?{title:`You can only upload up to ${Al} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Il?{title:`Total file size limit of ${Ip} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,_c="initial-bot-message",rn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Mp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,l]=F([]),d=X([]),[h,u]=F(!1),[p,_]=F(!1),f=X(new Map),g=X(0),[b,m]=F(!1),E=X([]),y=X(null),k=X({}),x=X({}),T=X(null),C=sm(),S=X(null),{isOnline:v}=uc(),N=X(!1),D=X([]),B=j(w=>w.agentId),G=j(w=>w.sessionId),he=j(w=>w.isStreaming),pe=j(w=>w.isWaitingForResponse),se=j(w=>w.initialMessage),Ee=j(w=>w.userId),V=j(w=>w.fileUploadPerSession),{setSessionId:le,setRefreshToken:Re,setSessToken:te,setLevel:Q,setError:A,setConnectionStatus:W,setShowRetryButton:re,setStartNewConnection:ve,setIsStreaming:K,setIsWaitingForResponse:Ae,setProgressMessage:He,setRecordingStatus:ae,clearSession:Pe,clearUser:De,addMessageToSession:Tt,getMessagesForSession:$t,setMessagesForSession:z,updateMessageInSession:Ie,setUserId:we,setFileUploadPerSession:Le,setToastMessage:qe,upsertElicitationState:Ue,setElicitationState:_t,setInitialMessage:ut,setSessionInitialMessage:ze}=j.getState();Y(()=>{if(!v)A({title:"No internet connection",description:"Please check your internet connection."}),W(_e.NOT_CONNECTED);else if(!b)W(_e.CONNECTING);else if(Oe())W(_e.CONNECTED),Et();else{const{showRetryButton:w,startNewConnection:O,error:P}=j.getState();(w||O||P)&&!Oe()&&Et(),T.current!==null&&!O&&!On()&&rt(j.getState().sessionId||void 0)}},[v,b]),Y(()=>{G&&(l(w=>{const O=new Set(w.map(M=>M.id)),P=[...w];for(const M of $t(G)||[])O.has(M.id)||(O.add(M.id),P.push(M));return P}),E.current=[])},[G]),Y(()=>{if(m(!1),!B)return;const w=new I.SynapseSDK({agentId:B,...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:Ee,callbacks:{onError:O=>{if(gr(O),typeof navigator<"u"&&!navigator.onLine){W(_e.NOT_CONNECTED),A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),cn()):wr();return}case I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:wr();return;case I.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:A(null),W(_e.NOT_CONNECTED),ve(!0);return;case I.SYNAPSE_RECOVERY_REASON.RETRY_LATER:W(_e.CONNECTING);return}switch(O.code){case I.SynapseErrorCode.API:case I.SynapseErrorCode.SESSION:{const P=O;P.status===404||P?.context?.status===404?ve(!0):(W(_e.NOT_CONNECTED),A({title:"Something went wrong!",description:rn(O)}),re(!0));break}case I.SynapseErrorCode.RECORDING:A({title:"Recording failed",description:rn(O)});break;case I.SynapseErrorCode.CONNECTION:Oe()||(W(_e.NOT_CONNECTED),g.current<2?(g.current=g.current+1,rt(j.getState().sessionId||void 0)):(re(!0),A({title:"Trying to connect...",description:rn(O)})));break;default:A({title:"Something went wrong",description:rn(O)}),re(!0);break}},onTokenExchange:O=>{const P=j.getState().userId;(O?.user_id&&P&&O.user_id!==P||O?.userid_change_detected)&&Pe(),O?.refresh_token&&Re(O.refresh_token),O?.sess_token&&te(O.sess_token),O?.level&&Q(O.level),O?.user_id&&we(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=w,C(w),m(!0),()=>{m(!1),Bt(),y.current=null,C(null),S.current&&(clearTimeout(S.current),S.current=null)}},[B,e,o]),Y(()=>{d.current=a},[a]),Y(()=>{const w=d.current[d.current.length-1];!w?.role||!G||(w?.role===Ne.USER&&!w.isStored?(l(O=>{const P=[...O];return P[P.length-1]={...w,isStored:!0},P}),Tt(G,{...w,isStored:!0})):!he&&!w.isStored&&(l(O=>{const P=[...O];return P[P.length-1]={...w,isStored:!0},P}),Tt(G,{...w,isStored:!0})))},[a,he]),Y(()=>()=>{const w=d.current[d.current.length-1],O=j.getState().sessionId;w&&!w?.isStored&&O&&((j.getState().chats[O]||[]).some(P=>P.id===w.id)||Tt(O,{...w,isStored:!0}))},[]),Y(()=>(S.current&&(clearTimeout(S.current),S.current=null),pe&&!he?S.current=setTimeout(()=>{Ae(!1),S.current=null},3e4):he&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[pe,he,Ae]);const rt=async w=>{T.current=performance.now();try{const O=await y.current?.startSession(w?{session_id:w}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===w),le(O.session_id)),O?.user_id&&we(O.user_id),O?.initial_message){ut(O.initial_message);const P=O.session_id||w;P&&ze(P,O.initial_message)}O?.error?.msg&&qe(O.error.msg)}catch(O){if(O?.reason)return;const P=O;P.status===404||P.context?.status==404?(A(null),W(_e.NOT_CONNECTED),ve(!0)):(A({title:"Connection Lost!",description:rn(O)}),re(!0))}},Be=async w=>{const O=j.getState().chats[w];if(O?.length)return l(O),O;const P=f.current.get(w);if(P)return P;const M=(async()=>{try{const q=await y.current?.getSessionMessages(w);if(!q?.length)return[];const{messages:oe,elicitations:ce}=Ap(q);return Object.keys(ce).length&&_t({...j.getState().elicitationState,...ce}),z(w,oe),l(oe),oe}catch{return[]}finally{f.current.delete(w)}})();f.current.set(w,M),_(!0);try{return await M}finally{_(!1)}},Ge=async({forceNewSession:w=!1,sessionId:O}={})=>{try{if(!y.current){A({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),w){W(_e.CONNECTING),l([]),await Pe(),await y?.current?.endSession(),Et(),await rt(),yr();return}const P=j.getState()?.sessionId,M=O||P||void 0;M!==P&&(Bt(),l([]),M&&await Be(M)),await rt(M),yr()}catch{}finally{u(!1)}},Oe=()=>y.current?.isConnected()??!1,Bt=()=>{y.current?.endSession()},Et=()=>{g.current=0;const{showRetryButton:w,startNewConnection:O,error:P}=j.getState();w&&re(!1),O&&ve(!1),P&&A(null)},an=()=>{Rn(nn.CONNECTION_ESTABLISHED)},ln=()=>{let w;try{w=y.current?.getSessionConfig()?.session_id}catch{w=void 0}return w||j.getState().sessionId||void 0},On=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Rn=(w,O={})=>{const P=ln();!P||k.current[w]===P||(k.current[w]=P,dc(w,{sessionId:P,resumed:x.current[P]??!1,...O}))},Qr=(w,O={})=>{const P=ln();dc(w,{...P&&{sessionId:P},...O})},Lt=(w,O,P={})=>{Qr(nn.SESSION_ERROR,{reason:Sp(w,O),...P})},gr=w=>{if(Oe())return;const O=w?.code,P=[I.SynapseErrorCode.RECORDING,I.SynapseErrorCode.FILE,I.SynapseErrorCode.MESSAGE,I.SynapseErrorCode.VALIDATION,I.SynapseErrorCode.CONFIGURATION,I.SynapseErrorCode.STORE];if(O&&P.includes(O))return;const M=typeof w?.status=="number"?w.status:void 0,q=w?.error,oe=typeof q?.code=="string"?q.code:typeof q?.type=="string"?q.type:void 0,ce={...M!==void 0&&{status:M}};if(w?.reason===I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||w?.reason===I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===I.SynapseErrorCode.AUTH||M===401||M===403){Lt(Cn.AUTH,w?.reason??oe??O??"auth_error",ce);return}const ue=O===I.SynapseErrorCode.API&&M===void 0;if(O===I.SynapseErrorCode.CONNECTION||M===0||ue){Lt(Cn.CONNECTION,w?.reason??oe??(ue?"timeout":O)??"connection_error",ce);return}Lt(Cn.SESSION,w?.reason??oe??O??"session_error",ce)},_r=w=>{switch(w){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Lt(Cn.SESSION,w);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Lt(Cn.CONNECTION,w);return}},Gt=()=>{Rn(nn.FIRST_MESSAGE_SENT)},eo=[nn.CONNECTION_ESTABLISHED,nn.FIRST_MESSAGE_SENT,nn.FIRST_BOT_REPLY],to=()=>{for(const w of eo)delete k.current[w];Oe()&&On()&&an()},Er=w=>{w!==_c&&Rn(nn.FIRST_BOT_REPLY,{messageId:w})},yr=()=>{const w=y.current;if(!w)return;for(const[P,M]of D.current)w.off(P,M);D.current=[];const O=(P,M)=>{w.on(P,M),D.current.push([P,M])};O(I.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,P=>{const M=P;if(M.data?.text&&M.messageId){const q=j.getState();q.isStreaming||(Ae(!1),K(!0),Et()),q.connectionStatus!==_e.CONNECTED&&Oe()&&W(_e.CONNECTED);const oe=M.data.text,ce=M.messageId,ue=N.current;N.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&Er(ce),l(We=>{const Te=We[We.length-1];if(Te&&Te.id===ce&&Te.role===Ne.ASSISTANT){const xe=[...We],Ze=ue&&Te.content.length>0&&!/\s$/.test(Te.content)&&!/^\s/.test(oe)?`
|
|
38
|
+
`}),c(en,{className:$t,"data-text-color":K.textColor,style:G?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[c("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:re}),!K.backgroundImage&&c("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${K.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:K.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),c(tp,{isOpen:Ee,onClose:()=>V(!1),botName:x,explicitDisclaimer:b?.explicitDisclaimer,consentContent:b?.consentContent,isFullScreen:Q}),E?.isOpen&&c(np,{isOpen:!0,botName:x,consentContent:b?.consentContent,onAccept:E.onAccept,isFullScreen:Q}),m?.isOpen&&c(up,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),Q&&n,Re==="user"&&!Q&&r,c("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[c("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...Q?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!Q&&!I&&{cursor:e?"grab":"default"}},children:c(jm,{onClose:y,showCloseButton:k,title:x,titleImg:T,tagline:C,iconUrl:S,startNewConversation:v,voiceAgentState:g,headerTinted:Q?!1:K.headerTinted,onToggleDisplayMode:P,onOpenSessionDrawer:Q?void 0:B})}),(()=>{const z=Q&&!!o,Ie=s&&g===M.VOICE_AGENT_STATE.IDLE?c(Xe,{fallback:c(Dl,{}),children:c($m,{value:s.value,onChange:s.onChange,onSend:He?ae: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:K,onStartNewChat:v,showStartNewChatButton:N,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:_,activeElicitationState:f,isFullScreen:Q&&!z,showAttention:s.showAttention})}):null,we={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Le=c(me,{children:[i&&a==="development"&&c("div",{className:"px-6 flex justify-center items-center",children:c("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),Q?c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:c("span",{className:"text-[10px] leading-[14px]",style:we,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):b?.explicitDisclaimer?c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c("div",{className:"flex justify-center items-center gap-1",children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:["AI can make mistakes. ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):c("div",{onClick:()=>V(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[b?.hideWatermark!==!0&&c(me,{children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c(yl,{className:"w-3 h-3"})]})]}),qe=o&&Q?o({composer:z?Ie:null,composerFooter:z?Le:null}):null;return c(me,{children:[c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[qe??t,c(Wm,{})]}),s&&!z&&c("div",{className:L("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[c("div",{className:L(Q&&"max-w-2xl mx-auto w-full"),children:Ie}),Le]})]})})()]})]})]})}function hp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function mp(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 pp(e){const t=new Date(e.c_at),n=mp(t),r=hp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function fp(){return c("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function gp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=pp(e);return c("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[c("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),c("div",{className:"flex items-center gap-2 w-full min-w-0",children:[c("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&c(fp,{})]})]})}function lc({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?c(Nm,{}):e.length===0?c("div",{className:"flex items-center justify-center h-full px-4 text-center",children:c("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):c(me,{children:e.map(o=>c(gp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function cc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:l,onClose:d}=e;return c(me,{children:[c("div",{className:L("absolute inset-0 z-[60] transition-opacity duration-200",l?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),c("div",{className:L("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",l?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:"flex items-center justify-between",children:[c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:c(Tn,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),c("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return c("div",{id:"synapse-session-sidebar","data-collapsed":s,className:L("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:L("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:c(Oh,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?c("button",{type:"button",onClick:o,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:c(dr,{className:"w-6 h-6"})}):c("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&c("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function _p(){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 Ep=180;function yp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=l=>{const d=l.label||l.value||"";d&&n({message:l.value||d,messageId:Date.now().toString()})};return c("div",{className:"flex-1 flex flex-col overflow-y-auto",children:c("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[c("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=Ep&&c("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:_p()}),e&&c("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&c("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((l,d)=>{const h=l.label||l.value||"";return h?c("button",{type:"button",onClick:()=>a(l),disabled:r,className:L("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&c("div",{children:[o,i]})]})})}const nn={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Cn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function Sp(e,t){return`${e}:${t}`}function dc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function uc(){const[e,t]=F(typeof navigator<"u"?navigator.onLine:!0);return Y(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const hc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),bp=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",vp=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}},wp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},mc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Np=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===M.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),l=n||a,d=n&&r?Cp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:mc(l,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const l=a.date?s.findIndex(d=>d.date===a.date):-1;if(l===-1)s.push({...a});else{const d=s[l];s[l]={...d,...hc(a),slots:a.slots??d.slots}}}return s},Tp=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,l=s.end_date||o.end_date;r[i]={...s,...hc(o),availability:Np({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:l,format:n})}}}return r},pc=e=>!!e&&Array.isArray(e.doctors),xp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!pc(e)||!pc(t))return e;const r=e.format||t.format;return{...t,doctors:Tp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Cp=(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},fc=(e,t)=>`${e}::${t}`,kp=e=>e<1e12?e*1e3:e,Op=(e,t)=>`${e}::${t}::answer`,Rp=e=>!!e?.tool_id&&!!e?.component;function Ap(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(Rp),i=r.timestamp?Qt(kp(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=>fc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[fc(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:Op(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Ip=Math.round(Il/(1024*1024)),gc=(e,t=0)=>e.length+t>Al?{title:`You can only upload up to ${Al} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Il?{title:`Total file size limit of ${Ip} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,_c="initial-bot-message",rn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Mp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,l]=F([]),d=X([]),[h,u]=F(!1),[p,_]=F(!1),f=X(new Map),g=X(0),[b,m]=F(!1),E=X([]),y=X(null),k=X({}),x=X({}),T=X(null),C=sm(),S=X(null),{isOnline:v}=uc(),N=X(!1),P=X([]),B=j(w=>w.agentId),G=j(w=>w.sessionId),he=j(w=>w.isStreaming),pe=j(w=>w.isWaitingForResponse),se=j(w=>w.initialMessage),Ee=j(w=>w.userId),V=j(w=>w.fileUploadPerSession),{setSessionId:le,setRefreshToken:Re,setSessToken:te,setLevel:Q,setError:I,setConnectionStatus:W,setShowRetryButton:re,setStartNewConnection:ve,setIsStreaming:K,setIsWaitingForResponse:Ae,setProgressMessage:He,setRecordingStatus:ae,clearSession:Pe,clearUser:De,addMessageToSession:xt,getMessagesForSession:$t,setMessagesForSession:z,updateMessageInSession:Ie,setUserId:we,setFileUploadPerSession:Le,setToastMessage:qe,upsertElicitationState:Ue,setElicitationState:Et,setInitialMessage:ht,setSessionInitialMessage:ze}=j.getState();Y(()=>{if(!v)I({title:"No internet connection",description:"Please check your internet connection."}),W(_e.NOT_CONNECTED);else if(!b)W(_e.CONNECTING);else if(Oe())W(_e.CONNECTED),yt();else{const{showRetryButton:w,startNewConnection:O,error:D}=j.getState();(w||O||D)&&!Oe()&&yt(),T.current!==null&&!O&&!On()&&rt(j.getState().sessionId||void 0)}},[v,b]),Y(()=>{G&&(l(w=>{const O=new Set(w.map(A=>A.id)),D=[...w];for(const A of $t(G)||[])O.has(A.id)||(O.add(A.id),D.push(A));return D}),E.current=[])},[G]),Y(()=>{if(m(!1),!B)return;const w=new M.SynapseSDK({agentId:B,...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:Ee,callbacks:{onError:O=>{if(gr(O),typeof navigator<"u"&&!navigator.onLine){W(_e.NOT_CONNECTED),I({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),cn()):wr();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:wr();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:I(null),W(_e.NOT_CONNECTED),ve(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:W(_e.CONNECTING);return}switch(O.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const D=O;D.status===404||D?.context?.status===404?ve(!0):(W(_e.NOT_CONNECTED),I({title:"Something went wrong!",description:rn(O)}),re(!0));break}case M.SynapseErrorCode.RECORDING:I({title:"Recording failed",description:rn(O)});break;case M.SynapseErrorCode.CONNECTION:Oe()||(W(_e.NOT_CONNECTED),g.current<2?(g.current=g.current+1,rt(j.getState().sessionId||void 0)):(re(!0),I({title:"Trying to connect...",description:rn(O)})));break;default:I({title:"Something went wrong",description:rn(O)}),re(!0);break}},onTokenExchange:O=>{const D=j.getState().userId;(O?.user_id&&D&&O.user_id!==D||O?.userid_change_detected)&&Pe(),O?.refresh_token&&Re(O.refresh_token),O?.sess_token&&te(O.sess_token),O?.level&&Q(O.level),O?.user_id&&we(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=w,C(w),m(!0),()=>{m(!1),Bt(),y.current=null,C(null),S.current&&(clearTimeout(S.current),S.current=null)}},[B,e,o]),Y(()=>{d.current=a},[a]),Y(()=>{const w=d.current[d.current.length-1];if(!w?.role||!G)return;const O=()=>l(D=>D.map(A=>A.id===w.id&&A.role===w.role?{...A,isStored:!0}:A));w?.role===Ne.USER&&!w.isStored?(O(),xt(G,{...w,isStored:!0})):!he&&!w.isStored&&(O(),xt(G,{...w,isStored:!0}))},[a,he]),Y(()=>()=>{const w=d.current[d.current.length-1],O=j.getState().sessionId;w&&!w?.isStored&&O&&((j.getState().chats[O]||[]).some(D=>D.id===w.id)||xt(O,{...w,isStored:!0}))},[]),Y(()=>(S.current&&(clearTimeout(S.current),S.current=null),pe&&!he?S.current=setTimeout(()=>{Ae(!1),S.current=null},3e4):he&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[pe,he,Ae]);const rt=async w=>{T.current=performance.now();try{const O=await y.current?.startSession(w?{session_id:w}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===w),le(O.session_id)),O?.user_id&&we(O.user_id),O?.initial_message){ht(O.initial_message);const D=O.session_id||w;D&&ze(D,O.initial_message)}O?.error?.msg&&qe(O.error.msg)}catch(O){if(O?.reason)return;const D=O;D.status===404||D.context?.status==404?(I(null),W(_e.NOT_CONNECTED),ve(!0)):(I({title:"Connection Lost!",description:rn(O)}),re(!0))}},Be=async w=>{const O=j.getState().chats[w];if(O?.length)return l(O),O;const D=f.current.get(w);if(D)return D;const A=(async()=>{try{const q=await y.current?.getSessionMessages(w);if(!q?.length)return[];const{messages:oe,elicitations:ce}=Ap(q);return Object.keys(ce).length&&Et({...j.getState().elicitationState,...ce}),z(w,oe),l(oe),oe}catch{return[]}finally{f.current.delete(w)}})();f.current.set(w,A),_(!0);try{return await A}finally{_(!1)}},Ge=async({forceNewSession:w=!1,sessionId:O}={})=>{try{if(!y.current){I({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),w){W(_e.CONNECTING),l([]),await Pe(),await y?.current?.endSession(),yt(),await rt(),yr();return}const D=j.getState()?.sessionId,A=O||D||void 0;A!==D&&(Bt(),l([]),A&&await Be(A)),await rt(A),yr()}catch{}finally{u(!1)}},Oe=()=>y.current?.isConnected()??!1,Bt=()=>{y.current?.endSession()},yt=()=>{g.current=0;const{showRetryButton:w,startNewConnection:O,error:D}=j.getState();w&&re(!1),O&&ve(!1),D&&I(null)},an=()=>{Rn(nn.CONNECTION_ESTABLISHED)},ln=()=>{let w;try{w=y.current?.getSessionConfig()?.session_id}catch{w=void 0}return w||j.getState().sessionId||void 0},On=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Rn=(w,O={})=>{const D=ln();!D||k.current[w]===D||(k.current[w]=D,dc(w,{sessionId:D,resumed:x.current[D]??!1,...O}))},Qr=(w,O={})=>{const D=ln();dc(w,{...D&&{sessionId:D},...O})},Lt=(w,O,D={})=>{Qr(nn.SESSION_ERROR,{reason:Sp(w,O),...D})},gr=w=>{if(Oe())return;const O=w?.code,D=[M.SynapseErrorCode.RECORDING,M.SynapseErrorCode.FILE,M.SynapseErrorCode.MESSAGE,M.SynapseErrorCode.VALIDATION,M.SynapseErrorCode.CONFIGURATION,M.SynapseErrorCode.STORE];if(O&&D.includes(O))return;const A=typeof w?.status=="number"?w.status:void 0,q=w?.error,oe=typeof q?.code=="string"?q.code:typeof q?.type=="string"?q.type:void 0,ce={...A!==void 0&&{status:A}};if(w?.reason===M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||w?.reason===M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===M.SynapseErrorCode.AUTH||A===401||A===403){Lt(Cn.AUTH,w?.reason??oe??O??"auth_error",ce);return}const ue=O===M.SynapseErrorCode.API&&A===void 0;if(O===M.SynapseErrorCode.CONNECTION||A===0||ue){Lt(Cn.CONNECTION,w?.reason??oe??(ue?"timeout":O)??"connection_error",ce);return}Lt(Cn.SESSION,w?.reason??oe??O??"session_error",ce)},_r=w=>{switch(w){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Lt(Cn.SESSION,w);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Lt(Cn.CONNECTION,w);return}},Gt=()=>{Rn(nn.FIRST_MESSAGE_SENT)},eo=[nn.CONNECTION_ESTABLISHED,nn.FIRST_MESSAGE_SENT,nn.FIRST_BOT_REPLY],to=()=>{for(const w of eo)delete k.current[w];Oe()&&On()&&an()},Er=w=>{w!==_c&&Rn(nn.FIRST_BOT_REPLY,{messageId:w})},yr=()=>{const w=y.current;if(!w)return;for(const[D,A]of P.current)w.off(D,A);P.current=[];const O=(D,A)=>{w.on(D,A),P.current.push([D,A])};O(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,D=>{const A=D;if(A.data?.text&&A.messageId){const q=j.getState();q.isStreaming||(Ae(!1),K(!0),yt()),q.connectionStatus!==_e.CONNECTED&&Oe()&&W(_e.CONNECTED);const oe=A.data.text,ce=A.messageId,ue=N.current;N.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&Er(ce),l(We=>{const Te=We[We.length-1];if(Te&&Te.id===ce&&Te.role===Ne.ASSISTANT){const xe=[...We],Je=ue&&Te.content.length>0&&!/\s$/.test(Te.content)&&!/^\s/.test(oe)?`
|
|
39
39
|
|
|
40
|
-
`:"";return xe[xe.length-1]={...Te,content:Te.content+Ze+oe},xe}else return[...We,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]})}}),O(I.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{N.current=!1,K(!1),He(null),Ae(!1)}),O(I.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{Et(),W(_e.CONNECTED),an()}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,P=>{N.current=!0;const M=P;if(!M?.messageId||!M?.data||!M?.data?.details?.component||!M?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:q,data:oe}=M,ce=oe.tool_id,ue=`${q}::${ce}`,Me=j.getState().elicitationState[ue],We=oe.details?.component,Te=M?.data?.details?._meta?.tool_result,xe=oe.details?.input,Ze=xp(Me?.input,xe,We);let xt=M.data.details?._meta?.disp_toast_msg;const Ct=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case I.SYNAPSE_EICITATION_STATUS.PROGRESS:{const J=M?.data?.details?.input||{},ht=Ct.reduce((Rt,yt)=>(J[yt]!==void 0&&(Rt[yt]=J[yt]),Rt),{}),et={...Me?.server_input||{},...ht},mt=Ct.filter(Rt=>!et[Rt]),Ot=M.data.details?._meta?.mcp_meta_fields||[];Ue(ue,{tool_id:ce,active:!0,disabled:!1,input:Ze,server_input:et,messageId:q,required:Ct,component:We,pattern:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.pattern,minLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.minLength,maxLength:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.maxLength,type:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.type,disp_toast_msg:M.data.details?._meta?.disp_toast_msg,description:M.data.details?._meta?.schema?.properties?.[M.data.details?.component]?.description,tool_result:Te,orientation:M.data.details?._meta?.orientation,...Ot.length&&{mcp_meta_fields:Ot},...mt?{toolSelectionNames:mt}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case I.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(ue,{...Me||{},tool_id:ce,disabled:!0,active:oh(We),messageId:q,component:We,input:Ze,tool_result:Te,send_to_llm:!0});break}case I.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(ue,{...Me||{},tool_id:ce,active:!1,messageId:q,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:Te,disabled:!0});break}default:Ue(ue,{tool_id:ce,disabled:!1,active:!1,messageId:q,tool_result:Te,input:Ze,component:We})}xt&&qe(xt);const kt=M?.data?.details?._meta?.user_hint;l(J=>{let ht=J[J.length-1]?.id===q?J.length-1:J.findIndex?.(et=>et.id===q);if(ht==-1){const et={id:q,content:M.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[ue],isResponseFromTool:!0,isStored:!1,...kt?{userHint:kt}:{}};return[...J,et]}else{const et={...J[ht],isResponseFromTool:!0,tool_keys:[...new Set([...J[ht].tool_keys||[],ue])],...kt?{userHint:kt}:{}};J[ht]=et;const mt=j.getState().sessionId;mt&&Ie(mt,q,et)}return[...J]});const Kt=M?.data?.details?._meta?.disp_message,Qe=j.getState().elicitationState;if((!Qe[ue]?.active||Qe[ue]?.send_to_llm)&&(Kt||Object.keys(Te||{}).length))try{Wt({message:Kt||"",tool_result:Te,toolCalled:!0,tool_key:ue})}catch{}}),O(I.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,P=>{if(P?.reason===I.DisconnectionReason.CLIENT_CLOSED)return;const M=P;Lt(Cn.CONNECTION,M?.reason??"unknown",{...typeof M?.code=="number"&&{closeCode:M.code}}),T.current=performance.now();const q=typeof navigator<"u"&&!navigator.onLine;if(W(_e.NOT_CONNECTED),q){A({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),re(!1);return}g.current<2?(g.current=g.current+1,re(!0),A({title:"Something went wrong!",description:"Please try again."})):(A({title:"Something went wrong!",description:"Please start a new Chat."}),ve(!0))}),O(I.SYNAPSE_REALTIME_EVENTS.ERROR,P=>{const M=P?.data?.code;switch(_r(M),M){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:ve(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:A({title:"Session not found",description:"Please start a new chat from onError callback"}),ve(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:cn();return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case I.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(g.current<1){g.current++,In();return}A({title:"Error parsing request",description:"please try again"}),re(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:A({title:"Request timed out",description:"please try again"}),re(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:A({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:A({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;default:A({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return}}),O(I.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async P=>{const M=P;M?.data?.text&&(l(q=>[...q,{id:Date.now().toString(),content:M.data.text||"",role:Ne.USER,timestamp:Qt(Date.now()),isStored:!0}]),ae(be.IDLE)),K(!1),Ae(!1),He(null)}),O(I.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,P=>{N.current=!0;const M=P;M.data?.text&&(Ae(!1),He(M.data.text))}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_START,P=>{N.current=!0;const M=P;if(M.data?.name&&M.messageId){const q=M.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:`Calling tool: ${M.data.name}...`};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:`Calling tool: ${M.data.name}...`}),ue}return oe})}}),O(I.SYNAPSE_REALTIME_EVENTS.TOOL_END,P=>{N.current=!0;const M=P;if(M.data?.name&&M.messageId){const q=M.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:"Tool call completed."}),ue}return oe})}})},Wt=async({message:w,files:O,audio:P,toolCalled:M,selectedComponent:q,resend:oe,tool_declined:ce,tool_result:ue,tool_key:Me})=>{const We=j.getState().elicitationState,Te=Object.values(We).some(xe=>xe.active);if(!(!M&&(!O||O.length===0)&&!w?.trim()&&!P?.audio&&!q&&!Te&&!ue&&!Object.keys(ue||{}).length)){if(O&&O.length>0){const xe=gc(O);if(xe){A(xe);return}}if(O&&O.length>0&&O.length+V>Jo){const xe=Jo-V;A({title:`You can only upload up to ${Jo} files per session`,description:`${xe<=0?"Maximum file upload limit reached":`You have ${xe} file${xe===1?"":"s"} upload${xe===1?"":"s"} left`}`});return}else O&&O.length&&Le(V+O.length);A(null),re(!1),Oe()&&W(_e.CONNECTED);try{const xe=a.length<=2&&E.current.length==1?E.current:null;let Ze=null,xt=null;const Ct=a.length-1,kt=Ct>=0?a[Ct]:null,Kt=j.getState().elicitationState,Qe=Me||null,J=Qe?Kt[Qe]:void 0,ht=J?.component===I.SYNAPSE_COMPONENTS.DOCTOR_CARD||J?.component===I.SYNAPSE_COMPONENTS.CARD?!!J&&!ue&&!!J.active:!!J?.active,et=!!(O||[]).length||!!P?.audio||!!ce||!ht||!M,mt=q?q.label:void 0,Ot=J?.component===I.SYNAPSE_COMPONENTS.PILL&&typeof mt=="string"?mt:null;if(!et&&ht&&Qe&&J?.messageId){const Fe=J.toolSelectionNames?.length?J.toolSelectionNames:J.required?.filter(fe=>!J.server_input?.[fe])??[],ot=Fe.reduce((fe,ye)=>{if(q){const Mn=q[ye];Mn!==void 0&&(fe[ye]=Mn)}else Fe.length===1&&(fe[ye]=w);return fe},{}),At=J.mcp_meta_fields?.reduce((fe,ye)=>(Fe.includes(ye)?fe[ye]=ot[ye]:J.server_input?.[ye]&&(fe[ye]=J.server_input[ye]),oe&&!fe.is_resend&&(fe.is_resend=oe),fe),{}),U=Object.keys(J.server_input||{})?.reduce((fe,ye)=>{const Mn=!Object.keys(At||{})?.includes(ye),Ns=!!J.server_input?.[ye];return(oe?Mn&&Ns:Mn&&J.required?.includes(ye)&&Ns)&&(fe[ye]=J.server_input?.[ye]),fe},{}),ke=oe?{}:(J.required||Fe).reduce((fe,ye)=>(Object.keys(At||{}).includes(ye)||(ot[ye]!==void 0?fe[ye]=ot[ye]:q&&q[ye]!==void 0&&(fe[ye]=q[ye])),fe),{}),Ve={...U||{},...ke,...Object.keys(At||{}).length&&{mcp_meta_fields:At}};if(!Object.keys(Ve).length)return;await Ue(Qe,{...J,server_input:{...J.server_input||{},...Ve}});try{await An(J.tool_id,J.messageId,Ve),Ze=!0}catch(fe){await y.current?.sendMessage({tool_result:{...J.tool_result,error:`Tool call failed: ${rn(fe)}`}}),xt="Tool call failed",Ue(Qe,{...J,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${rn(fe)}`}})}}else{const Fe=kt?.id,ot=Fe?Object.entries(We).filter(([U,ke])=>{const[Ve]=U.split("::");return Ve===Fe&&ke.active}):[],At=ue??J?.tool_result;await y.current?.sendMessage({message:w??"",files:O,audio:P,...xe&&{initial_prompts:xe},...ce||ot.length>0?{tool_declined:!0,tool_id:J?.tool_id||""}:{},...At&&{tool_result:At}})}(w||O&&O.length>0||P?.audio||Ot||xt)&&(Ze||Gt(),l(Fe=>{if(Ze)return Fe;const ot=Fe.length===0&&se?.text?[{id:_c,content:se.text,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]:[];return[...Fe,...ot,{id:Date.now().toString(),content:Ot||xt||w||"",files:O||[],audio:P,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]}),Ze||Ae(!0),Ze=null);const Rt=j.getState().elicitationState,yt=new Set;Qe&&yt.add(Qe),kt?.tool_keys?.forEach(Fe=>yt.add(Fe)),yt.forEach(Fe=>{const ot=Rt[Fe];ot&&Ue(Fe,{...ot,...et&&{active:!1,disabled:!0},...Fe===Qe?{response_value:{...ot?.response_value||{},label:Ot||w||""}}:{}})})}catch{}}},Sr=w=>w.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(w.type)?(A({title:`File type not supported: ${w.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):w.size>3*1024*1024?(A({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,no=async()=>{try{await y.current?.startRecording({onChunks:async w=>{ae(be.PROCESSING),await Wt({audio:w}),ae(be.TRANSCRIBING)},onError(w){ae(be.IDLE)}}),ae(be.LISTENING)}catch(w){throw ae(be.IDLE),w}},br=()=>{y.current?.endRecording()},An=async(w,O,P)=>{try{if(!Oe())throw new Error("Not connected to the server");await y.current?.callTool(w,O,P)}catch(M){throw M}},cn=async()=>{Et(),await Pe(),await Ge({forceNewSession:!0})},vr=async()=>{await Ge({forceNewSession:!0})},wr=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),W(_e.NOT_CONNECTED),A({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},In=async()=>{if(Oe()){W(_e.CONNECTED);const w=d.current[d.current.length-1];if(w&&w.role===Ne.USER)try{y.current?.sendMessage({message:w.content,files:w.files||[],messageId:w.id,audio:w.audio})}catch{}}else if(W(_e.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:w}=j.getState();await rt(w)}else g.current===2?(g.current++,re(!0),A({title:"Trying to connect..."})):(A({title:"Something went wrong!",description:"Please start a new chat."}),ve(!0))};return{sendMessage:Wt,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Bt,isReady:b,startRecording:no,stopRecording:br,getPastSessions:async()=>{try{const w=await y.current?.getPastSessions();return!w||!w?.data?.length?[]:w.data}catch{return[]}},handleRetry:In,isValidFile:Sr,handleStartNewConnection:cn,startNewChat:vr,callTool:An,handleInitialTaskClick:async w=>{const{message:O}=w;if(!se?.suggestions?.length||!O)return;const P=se.suggestions.find(q=>q.value===O);if(E.current=[{role:"assistant",text:`${se.text} ${P?.response||""}`}],!P||!P.response){await Wt(w);return}Gt(),l(q=>[...q,{id:Date.now().toString(),content:O,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]),Ae(!0),await sh(1e3),Ae(!1);const M=Date.now().toString();Er(M),l(q=>[...q,{id:M,content:P.response||"Please try again",role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(w,O,P)=>{if(Oe())try{await y.current?.sendMessageFeedback(O,w,P)}catch{}},sendSessionFeedback:async(w,O)=>{if(!(!Oe()||!w?.length&&!O))try{await y.current?.sendSessionFeedback(w,O)}catch{}},clearElicitationState:async(w,O)=>{const P=j.getState().elicitationState,M=w?P[w]:void 0;try{await Wt({message:O||"User aborted elicitation",tool_declined:!0,tool_result:M?.tool_result,tool_key:w})}catch{}finally{w&&M&&Ue(w,{...M,active:!1,disabled:!0})}},markWidgetOpened:to}};function Ke(e){const t=X(e);return Y(()=>{t.current=e}),de(((...n)=>t.current(...n)),[])}function Pp(e){return e==="full"?I.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?I.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":I.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Dp=32,Lp=100,Up=320;function Fp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=F(!1),l=X(null),d=X(!1),h=X("auto"),u=X(!0),p=de(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),_=de(b=>Fp()?"auto":b,[]),f=de(b=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:_(b)}),a(!1))},[p,_]),g=de(b=>{d.current=!0,h.current=b,l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,d.current&&(d.current=!1,f(h.current))}))},[f]);return Y(()=>()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),d.current=!1},[]),Y(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),Y(()=>{if(!e||!u.current)return;const b=setTimeout(()=>g("auto"),Up);return()=>clearTimeout(b)},[r,e,g]),Y(()=>{let b=!1,m=null,E=null,y=0;const k=()=>{if(b)return;const x=p(),T=i.current?.parentElement;if(!x||!T){requestAnimationFrame(k);return}const C=()=>{const{scrollTop:N,scrollHeight:D,clientHeight:B}=x;return D-N-B<=Dp};u.current=!0;let S=0;const v=()=>{if(S>0){S--;return}u.current=C()};x.addEventListener("scroll",v,{passive:!0}),E=()=>x.removeEventListener("scroll",v),m=new ResizeObserver(()=>{if(!u.current)return;const N=Date.now();N-y<Lp||(y=N,S++,g("auto"))}),m.observe(T)};return k(),()=>{b=!0,m?.disconnect(),E?.()}},[p,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:f,scheduleScrollToBottom:g}}const jp=["Type a reply\u2026","Ask me anything\u2026","Tell me what's on your mind\u2026","Short messages are fine\u2026","You can type in any language\u2026","Not sure what to ask? Just say hi\u2026"],zp=3500;function Yp(e,t=jp){if(t.length===0)return"";const n=(e%t.length+t.length)%t.length;return t[n]}const us="eka-medassist-agent-config",Ec="feedback_hidden",hs="upfront_consent_accepted",Hp=4e3;function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function yc(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 $p({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:l}=im(),d=Ke(()=>{r===I.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==I.VOICE_AGENT_STATE.IDLE,[u,p]=F(""),[_,f]=F(!1),[g,b]=F(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=de(()=>b(U=>U==="full"?"widget":"full"),[]),E=Ql()?"mobile":g,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??lm,cm),dm),x=n.sidePanelMode??"push",[T,C]=F([]),S=X(!1),[v,N]=F(!1),[D,B]=F(!1),[G,he]=F(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=X(null),se=j(U=>U.startNewConnection),Ee=j(U=>U.showRetryButton),V=j(U=>U.clearError),le=j(U=>U.error),Re=j(U=>U.connectionStatus),te=j(U=>U.recordingStatus),Q=j(U=>U.isWaitingForResponse),A=j(U=>U.isStreaming),W=j(U=>U.setError),re=j(U=>U.sessionId),ve=j(U=>U.initialMessage),K=j(U=>U.sessionInitialMessages),Ae=j(U=>U.elicitationState),He=j(U=>U.level),{incomingMessages:ae,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:Tt,markWidgetOpened:$t,startSession:z,startNewChat:Ie,isReady:we,startRecording:Le,stopRecording:qe,handleRetry:Ue,isValidFile:_t,sendMessageFeedback:ut,clearElicitationState:ze,sendSessionFeedback:rt,getPastSessions:Be}=Mp({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:Pp(n.displayMode)}),Ge=Ke(Ue),Oe=Ke(ut),Bt=Ke(ze),Et=Ke(U=>{z({sessionId:U})}),an=Ke(()=>{Ie()}),[ln,On]=F(!1),[Rn,Qr]=F([]),[Lt,gr]=F(!0),_r=X(Be);Y(()=>{_r.current=Be});const Gt=de(async()=>{gr(!0);try{const U=await _r.current();Qr(U)}catch{}finally{gr(!1)}},[]),eo=de(async()=>{On(!0),await Gt()},[Gt]),to=de(()=>{On(!1)},[]),[Er,yr]=F(!1),Wt=de(()=>yr(U=>!U),[]);Y(()=>{E!=="full"||He!=="user"||Gt()},[E,He,re,Gt]),Y(()=>{if(t){if(pe.current!==t){const U=j.getState();Qh(t),nm(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&&we&&!S.current&&(S.current=!0,z({forceNewSession:!1}))}},[e,we,t]),Y(()=>{e&&$t()},[e]),Y(()=>{zm([tc])},[]),Y(()=>()=>{s()},[]),Y(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||he(!0)},[n.theme?.upfrontConsent,t]);const Sr=de(()=>{yc(t,hs),he(!1)},[t]),no=Ke(()=>{n.feedback&&!ms(t,Ec)?B(!0):n.onClose()}),br=Ke(async(U,ke)=>{await rt(U,ke),B(!1),n.onClose()}),An=Ke(()=>{B(!1),n.onClose()}),cn=Ke(()=>{yc(t,Ec),B(!1),n.onClose()}),vr=de(()=>{B(!1)},[]),wr=ae.length>0,In=ae.length===1,w=ie(()=>{const U=ae[ae.length-1],ke=U?.tool_keys?.[U.tool_keys.length-1];if(!ke)return null;const Ve=Ae[ke];return Ve?.active?{...Ve,tool_key:ke}:null},[ae,Ae]),O=ie(()=>(re?K[re]:void 0)??ve??n?.initialMessage??null,[re,K,ve,n?.initialMessage]),P=ie(()=>!!O?.text||!!O?.suggestions?.length,[O]),M=ie(()=>P&&ae?.length===0&&!Pe,[ae,P,Pe]),q=ie(()=>w?w.component===I.SYNAPSE_COMPONENTS.MOBILE||w.component===I.SYNAPSE_COMPONENTS.OTP||w.component===I.SYNAPSE_COMPONENTS.EMAIL:!1,[w]),{scrollAreaRef:oe,messagesEndRef:ce,showScrollButton:ue,scrollToBottom:Me}=Vp({messageCount:ae.length,isStreaming:A,isFirstMessage:In,resolvedMode:E}),We=Re===_e.CONNECTED,Te=Q||A,xe=!Te&&We&&!le&&!h&&!_&&te===be.IDLE&&!v&&u.trim().length===0,[Ze,xt]=F(!1);Y(()=>{if(!xe){xt(!1);return}const U=setTimeout(()=>xt(!0),Hp);return()=>clearTimeout(U)},[xe]);const Ct=ie(()=>te===be.IDLE?null:te===be.LISTENING?"Listening...":te===be.PROCESSING?"Processing...":te===be.TRANSCRIBING?"Transcribing...":null,[te]),[kt,Kt]=F(0);Y(()=>{if(!xe){Kt(0);return}const U=setInterval(()=>Kt(ke=>ke+1),zp);return()=>clearInterval(U)},[xe]);const Qe=Ct&&te!==be.IDLE?Ct:Q||A?"Please wait for the response...":Yp(kt),J=Ke(async(U,ke)=>{if(Te)return;const Ve=ke?Tt:De,fe=U?.message??u;T.length>0?(await Ve({files:T,message:fe.trim()}),C([]),N(!1)):fe.trim()?await Ve({...U,message:fe.trim()}):U?.resend?await Ve(U):U&&await Ve(U),p(""),f(!1),N(!1)}),ht=Ke(U=>J(U,M)),et=Ke(U=>J(U,!0)),mt=Ke(U=>{if(U&&U.length>0){const ke=U.filter(fe=>_t(fe));if(ke.length===0)return;const Ve=gc(ke,T.length);if(Ve){W(Ve);return}U=ke}C(ke=>(N((ke?.length??0)+(U?.length??0)>0),[...ke,...U]))}),Ot=de(U=>{C(ke=>{const Ve=ke.filter((fe,ye)=>ye!==U);return N(Ve.length>0),Ve})},[]),Rt=Ke(async()=>{if(_)await qe(),f(!1);else{if(Te)return;try{await Le(),f(!0)}catch{}}}),yt=Ke(U=>{p(U)}),Fe=ie(()=>({value:u,onChange:yt,onSend:J,onFileChange:mt,onRemoveFile:Ot,onRecording:Rt,isRecording:_,hasAttachment:v,attachmentFiles:T,isDisabled:Te,placeholder:Qe,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d,showAttention:Ze}),[u,yt,J,mt,Ot,Rt,_,v,T,Te,Qe,te,n.allowed,h,d,Ze]),ot=ie(()=>n.feedback?{isOpen:D,config:n.feedback,onSubmit:br,onSkip:An,onClose:vr,onDontShowAgain:cn}:void 0,[n.feedback,D,br,An,vr,cn]),At=ie(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Sr}:void 0,[n.theme?.upfrontConsent,G,Sr]);return{showScrollButton:ue,toggleDisplayMode:m,resolvedMode:E,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:ce,startNewConnection:se,showRetryButton:Ee,clearError:V,error:le,sessionId:re,activeElicitation:w,inConversation:wr,isFirstMessage:In,isEmptyChat:M,isAuthComponent:q,isConnected:We,isComposerDisabled:Te,isLoadingSessionMessages:Pe,initialMessage:O,incomingMessages:ae,sendMessageFeedback:Oe,clearElicitationState:Bt,handleRetry:Ge,handleChatSendMessage:ht,handleEmptyStateSendMessage:et,handleSelectSession:Et,handleStartNewChat:an,scrollToBottom:Me,handleClose:no,chatComposerProps:Fe,feedbackModalProps:ot,consentModalProps:At,isSessionDrawerOpen:ln,pastSessions:Rn,isLoadingPastSessions:Lt,openSessionDrawer:eo,closeSessionDrawer:to,userLevel:He,isSidebarCollapsed:Er,toggleSidebar:Wt,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:l}}function Sc({bare:e}){return c("div",{className:"flex justify-start synapse-message-in",children:c(en,{className:L("px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",e&&"!bg-transparent !shadow-none !px-0 !backdrop-blur-none"),children:c("div",{className:"flex items-center gap-1.5 h-5",role:"status","aria-label":"Bot is typing",children:[0,1,2].map(t=>c("span",{className:"synapse-typing-dot w-2 h-2 rounded-full bg-foreground",style:{animationDelay:`${t*160}ms`}},t))})})})}function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},on.apply(this,arguments)}const Bp=["children","options"],bc=["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"}),vc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Gp=["style","script","pre"],Wp=["src","href","data","formAction","srcDoc","action"],Kp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,qp=/\n{2,}$/,wc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Xp=/^ *> ?/gm,Jp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Zp=/^ {2,}\n/,Qp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Nc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Tc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,ef=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,tf=/^(?:\n *)*\n/,nf=/\r\n?/g,rf=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,of=/^\[\^([^\]]+)]/,sf=/\f/g,af=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,lf=/^\s*?\[(x|\s)\]/,xc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,kc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,cf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Oc=/^<!--[\s\S]*?(?:-->)/,df=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,uf=/^\{.*\}$/,hf=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,mf=/^<([^ >]+[:@\/][^ >]+)>/,pf=/-([a-z])?/gi,Rc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,ff=/^[^\n]+(?: \n|\n{2,})/,gf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,_f=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Ef=/^\[([^\]]*)\] ?\[([^\]]*)\]/,yf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Sf=/\t/g,bf=/(^ *\||\| *$)/g,vf=/^ *:-+: *$/,wf=/^ *:-+ *$/,Nf=/^ *-+: *$/,Gr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Wr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Tf=RegExp(`^([*_])\\1${Gr(1)}${Wr}\\1\\1(?!\\1)`),xf=RegExp(`^([*_])${Gr(0)}${Wr}\\1(?!\\1)`),Cf=RegExp(`^(==)${Gr(0)}${Wr}\\1`),kf=RegExp(`^(~~)${Gr(0)}${Wr}\\1`),Of=/^(:[a-zA-Z0-9-_]+:)/,Rf=/^\\([^0-9A-Za-z\s])/,Af=/\\([^0-9A-Za-z\s])/g,If=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Mf=/^\n+/,Pf=/^([ \t]*)/,Df=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Ac(e){return"( *)("+(e===1?gs:_s)+") +"}const Ic=Ac(1),Mc=Ac(2);function Pc(e){return RegExp("^"+(e===1?Ic:Mc))}const Lf=Pc(1),Uf=Pc(2);function Dc(e){return RegExp("^"+(e===1?Ic:Mc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Ff=Dc(1),Vf=Dc(2);function Lc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Uc=Lc(1),Fc=Lc(2);function Vc(e,t){const n=t===1,r=n?Uc:Fc,o=n?Ff:Vf,i=n?Lf:Uf;return{t:s=>i.test(s),o:kn(function(s,a){const l=Df.exec(a.prevCapture);return l&&(a.list||!a.inline&&!a.simple)?r.exec(s=l[1]+s):null}),i:1,u(s,a,l){const d=n?+s[2]:void 0,h=s[0].replace(qp,`
|
|
40
|
+
`:"";return xe[xe.length-1]={...Te,content:Te.content+Je+oe},xe}else return[...We,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]})}}),O(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{N.current=!1,K(!1),He(null),Ae(!1)}),O(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{yt(),W(_e.CONNECTED),an()}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,D=>{N.current=!0;const A=D;if(!A?.messageId||!A?.data||!A?.data?.details?.component||!A?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:q,data:oe}=A,ce=oe.tool_id,ue=`${q}::${ce}`,Me=j.getState().elicitationState[ue],We=oe.details?.component,Te=A?.data?.details?._meta?.tool_result,xe=oe.details?.input,Je=xp(Me?.input,xe,We);let Ct=A.data.details?._meta?.disp_toast_msg;const kt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Z=A?.data?.details?.input||{},mt=kt.reduce((Rt,St)=>(Z[St]!==void 0&&(Rt[St]=Z[St]),Rt),{}),et={...Me?.server_input||{},...mt},pt=kt.filter(Rt=>!et[Rt]),lt=A.data.details?._meta?.mcp_meta_fields||[];Ue(ue,{tool_id:ce,active:!0,disabled:!1,input:Je,server_input:et,messageId:q,required:kt,component:We,pattern:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.pattern,minLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.minLength,maxLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.maxLength,type:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.type,disp_toast_msg:A.data.details?._meta?.disp_toast_msg,description:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.description,tool_result:Te,orientation:A.data.details?._meta?.orientation,...lt.length&&{mcp_meta_fields:lt},...pt?{toolSelectionNames:pt}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(ue,{...Me||{},tool_id:ce,disabled:!0,active:oh(We),messageId:q,component:We,input:Je,tool_result:Te,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(ue,{...Me||{},tool_id:ce,active:!1,messageId:q,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:Te,disabled:!0});break}default:Ue(ue,{tool_id:ce,disabled:!1,active:!1,messageId:q,tool_result:Te,input:Je,component:We})}Ct&&qe(Ct);const Ot=A?.data?.details?._meta?.user_hint;l(Z=>{let mt=Z[Z.length-1]?.id===q?Z.length-1:Z.findIndex?.(et=>et.id===q);if(mt==-1){const et={id:q,content:A.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[ue],isResponseFromTool:!0,isStored:!1,...Ot?{userHint:Ot}:{}};return[...Z,et]}else{const et={...Z[mt],isResponseFromTool:!0,tool_keys:[...new Set([...Z[mt].tool_keys||[],ue])],...Ot?{userHint:Ot}:{}},pt=j.getState().sessionId;pt&&Ie(pt,q,et);const lt=[...Z];return lt[mt]=et,lt}});const Kt=A?.data?.details?._meta?.disp_message,Qe=j.getState().elicitationState;if((!Qe[ue]?.active||Qe[ue]?.send_to_llm)&&(Kt||Object.keys(Te||{}).length))try{Wt({message:Kt||"",tool_result:Te,toolCalled:!0,tool_key:ue})}catch{}}),O(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,D=>{if(D?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const A=D;Lt(Cn.CONNECTION,A?.reason??"unknown",{...typeof A?.code=="number"&&{closeCode:A.code}}),T.current=performance.now();const q=typeof navigator<"u"&&!navigator.onLine;if(W(_e.NOT_CONNECTED),q){I({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),re(!1);return}g.current<2?(g.current=g.current+1,re(!0),I({title:"Something went wrong!",description:"Please try again."})):(I({title:"Something went wrong!",description:"Please start a new Chat."}),ve(!0))}),O(M.SYNAPSE_REALTIME_EVENTS.ERROR,D=>{const A=D?.data?.code;switch(_r(A),A){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:ve(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:I({title:"Session not found",description:"Please start a new chat from onError callback"}),ve(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:cn();return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case M.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(g.current<1){g.current++,In();return}I({title:"Error parsing request",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:I({title:"Request timed out",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;default:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return}}),O(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async D=>{const A=D;A?.data?.text&&(l(q=>[...q,{id:Date.now().toString(),content:A.data.text||"",role:Ne.USER,timestamp:Qt(Date.now()),isStored:!0}]),ae(be.IDLE)),K(!1),Ae(!1),He(null)}),O(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,D=>{N.current=!0;const A=D;A.data?.text&&(Ae(!1),He(A.data.text))}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,D=>{N.current=!0;const A=D;if(A.data?.name&&A.messageId){const q=A.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:`Calling tool: ${A.data.name}...`};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:`Calling tool: ${A.data.name}...`}),ue}return oe})}}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,D=>{N.current=!0;const A=D;if(A.data?.name&&A.messageId){const q=A.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:"Tool call completed."}),ue}return oe})}})},Wt=async({message:w,files:O,audio:D,toolCalled:A,selectedComponent:q,resend:oe,tool_declined:ce,tool_result:ue,tool_key:Me})=>{const We=j.getState().elicitationState,Te=Object.values(We).some(xe=>xe.active);if(!(!A&&(!O||O.length===0)&&!w?.trim()&&!D?.audio&&!q&&!Te&&!ue&&!Object.keys(ue||{}).length)){if(O&&O.length>0){const xe=gc(O);if(xe){I(xe);return}}if(O&&O.length>0&&O.length+V>Zo){const xe=Zo-V;I({title:`You can only upload up to ${Zo} files per session`,description:`${xe<=0?"Maximum file upload limit reached":`You have ${xe} file${xe===1?"":"s"} upload${xe===1?"":"s"} left`}`});return}else O&&O.length&&Le(V+O.length);I(null),re(!1),Oe()&&W(_e.CONNECTED);try{const xe=a.length<=2&&E.current.length==1?E.current:null;let Je=null,Ct=null;const kt=a.length-1,Ot=kt>=0?a[kt]:null,Kt=j.getState().elicitationState,Qe=Me||null,Z=Qe?Kt[Qe]:void 0,mt=Z?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||Z?.component===M.SYNAPSE_COMPONENTS.CARD?!!Z&&!ue&&!!Z.active:!!Z?.active,et=!!(O||[]).length||!!D?.audio||!!ce||!mt||!A,pt=q?q.label:void 0,lt=Z?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof pt=="string"?pt:null;if(!et&&mt&&Qe&&Z?.messageId){const Fe=Z.toolSelectionNames?.length?Z.toolSelectionNames:Z.required?.filter(fe=>!Z.server_input?.[fe])??[],ot=Fe.reduce((fe,ye)=>{if(q){const Mn=q[ye];Mn!==void 0&&(fe[ye]=Mn)}else Fe.length===1&&(fe[ye]=w);return fe},{}),At=Z.mcp_meta_fields?.reduce((fe,ye)=>(Fe.includes(ye)?fe[ye]=ot[ye]:Z.server_input?.[ye]&&(fe[ye]=Z.server_input[ye]),oe&&!fe.is_resend&&(fe.is_resend=oe),fe),{}),U=Object.keys(Z.server_input||{})?.reduce((fe,ye)=>{const Mn=!Object.keys(At||{})?.includes(ye),Ns=!!Z.server_input?.[ye];return(oe?Mn&&Ns:Mn&&Z.required?.includes(ye)&&Ns)&&(fe[ye]=Z.server_input?.[ye]),fe},{}),ke=oe?{}:(Z.required||Fe).reduce((fe,ye)=>(Object.keys(At||{}).includes(ye)||(ot[ye]!==void 0?fe[ye]=ot[ye]:q&&q[ye]!==void 0&&(fe[ye]=q[ye])),fe),{}),Ve={...U||{},...ke,...Object.keys(At||{}).length&&{mcp_meta_fields:At}};if(!Object.keys(Ve).length)return;await Ue(Qe,{...Z,server_input:{...Z.server_input||{},...Ve}});try{await An(Z.tool_id,Z.messageId,Ve),Je=!0}catch(fe){await y.current?.sendMessage({tool_result:{...Z.tool_result,error:`Tool call failed: ${rn(fe)}`}}),Ct="Tool call failed",Ue(Qe,{...Z,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${rn(fe)}`}})}}else{const Fe=Ot?.id,ot=Fe?Object.entries(We).filter(([U,ke])=>{const[Ve]=U.split("::");return Ve===Fe&&ke.active}):[],At=ue??Z?.tool_result;await y.current?.sendMessage({message:w??"",files:O,audio:D,...xe&&{initial_prompts:xe},...ce||ot.length>0?{tool_declined:!0,tool_id:Z?.tool_id||""}:{},...At&&{tool_result:At}})}(w||O&&O.length>0||D?.audio||lt||Ct)&&(Je||Gt(),l(Fe=>{if(Je)return Fe;const ot=Fe.length===0&&se?.text?[{id:_c,content:se.text,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]:[];return[...Fe,...ot,{id:Date.now().toString(),content:lt||Ct||w||"",files:O||[],audio:D,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]}),Je||Ae(!0),Je=null);const Rt=j.getState().elicitationState,St=new Set;Qe&&St.add(Qe),Ot?.tool_keys?.forEach(Fe=>St.add(Fe)),St.forEach(Fe=>{const ot=Rt[Fe];ot&&Ue(Fe,{...ot,...et&&{active:!1,disabled:!0},...Fe===Qe?{response_value:{...ot?.response_value||{},label:lt||w||""}}:{}})})}catch{}}},Sr=w=>w.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(w.type)?(I({title:`File type not supported: ${w.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):w.size>3*1024*1024?(I({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,no=async()=>{try{await y.current?.startRecording({onChunks:async w=>{ae(be.PROCESSING),await Wt({audio:w}),ae(be.TRANSCRIBING)},onError(w){ae(be.IDLE)}}),ae(be.LISTENING)}catch(w){throw ae(be.IDLE),w}},br=()=>{y.current?.endRecording()},An=async(w,O,D)=>{try{if(!Oe())throw new Error("Not connected to the server");await y.current?.callTool(w,O,D)}catch(A){throw A}},cn=async()=>{yt(),await Pe(),await Ge({forceNewSession:!0})},vr=async()=>{await Ge({forceNewSession:!0})},wr=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),W(_e.NOT_CONNECTED),I({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},In=async()=>{if(Oe()){W(_e.CONNECTED);const w=d.current[d.current.length-1];if(w&&w.role===Ne.USER)try{y.current?.sendMessage({message:w.content,files:w.files||[],messageId:w.id,audio:w.audio})}catch{}}else if(W(_e.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:w}=j.getState();await rt(w)}else g.current===2?(g.current++,re(!0),I({title:"Trying to connect..."})):(I({title:"Something went wrong!",description:"Please start a new chat."}),ve(!0))};return{sendMessage:Wt,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Bt,isReady:b,startRecording:no,stopRecording:br,getPastSessions:async()=>{try{const w=await y.current?.getPastSessions();return!w||!w?.data?.length?[]:w.data}catch{return[]}},handleRetry:In,isValidFile:Sr,handleStartNewConnection:cn,startNewChat:vr,callTool:An,handleInitialTaskClick:async w=>{const{message:O}=w;if(!se?.suggestions?.length||!O)return;const D=se.suggestions.find(q=>q.value===O);if(E.current=[{role:"assistant",text:`${se.text} ${D?.response||""}`}],!D||!D.response){await Wt(w);return}Gt(),l(q=>[...q,{id:Date.now().toString(),content:O,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]),Ae(!0),await sh(1e3),Ae(!1);const A=Date.now().toString();Er(A),l(q=>[...q,{id:A,content:D.response||"Please try again",role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(w,O,D)=>{if(Oe())try{await y.current?.sendMessageFeedback(O,w,D)}catch{}},sendSessionFeedback:async(w,O)=>{if(!(!Oe()||!w?.length&&!O))try{await y.current?.sendSessionFeedback(w,O)}catch{}},clearElicitationState:async(w,O)=>{const D=j.getState().elicitationState,A=w?D[w]:void 0;try{await Wt({message:O||"User aborted elicitation",tool_declined:!0,tool_result:A?.tool_result,tool_key:w})}catch{}finally{w&&A&&Ue(w,{...A,active:!1,disabled:!0})}},markWidgetOpened:to}};function Ke(e){const t=X(e);return Y(()=>{t.current=e}),de(((...n)=>t.current(...n)),[])}function Pp(e){return e==="full"?M.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?M.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":M.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Dp=32,Lp=100,Up=320;function Fp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=F(!1),l=X(null),d=X(!1),h=X("auto"),u=X(!0),p=de(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),_=de(b=>Fp()?"auto":b,[]),f=de(b=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:_(b)}),a(!1))},[p,_]),g=de(b=>{d.current=!0,h.current=b,l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,d.current&&(d.current=!1,f(h.current))}))},[f]);return Y(()=>()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),d.current=!1},[]),Y(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),Y(()=>{if(!e||!u.current)return;const b=setTimeout(()=>g("auto"),Up);return()=>clearTimeout(b)},[r,e,g]),Y(()=>{let b=!1,m=null,E=null,y=0;const k=()=>{if(b)return;const x=p(),T=i.current?.parentElement;if(!x||!T){requestAnimationFrame(k);return}const C=()=>{const{scrollTop:N,scrollHeight:P,clientHeight:B}=x;return P-N-B<=Dp};u.current=!0;let S=0;const v=()=>{if(S>0){S--;return}u.current=C()};x.addEventListener("scroll",v,{passive:!0}),E=()=>x.removeEventListener("scroll",v),m=new ResizeObserver(()=>{if(!u.current)return;const N=Date.now();N-y<Lp||(y=N,S++,g("auto"))}),m.observe(T)};return k(),()=>{b=!0,m?.disconnect(),E?.()}},[p,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:f,scheduleScrollToBottom:g}}const jp=["Type a reply\u2026","Ask me anything\u2026","Tell me what's on your mind\u2026","Short messages are fine\u2026","You can type in any language\u2026","Not sure what to ask? Just say hi\u2026"],zp=3500;function Yp(e,t=jp){if(t.length===0)return"";const n=(e%t.length+t.length)%t.length;return t[n]}const us="eka-medassist-agent-config",Ec="feedback_hidden",hs="upfront_consent_accepted",Hp=4e3;function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function yc(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 $p({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:l}=im(),d=Ke(()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==M.VOICE_AGENT_STATE.IDLE,[u,p]=F(""),[_,f]=F(!1),[g,b]=F(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=de(()=>b(U=>U==="full"?"widget":"full"),[]),E=Ql()?"mobile":g,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??lm,cm),dm),x=n.sidePanelMode??"push",[T,C]=F([]),S=X(!1),[v,N]=F(!1),[P,B]=F(!1),[G,he]=F(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=X(null),se=j(U=>U.startNewConnection),Ee=j(U=>U.showRetryButton),V=j(U=>U.clearError),le=j(U=>U.error),Re=j(U=>U.connectionStatus),te=j(U=>U.recordingStatus),Q=j(U=>U.isWaitingForResponse),I=j(U=>U.isStreaming),W=j(U=>U.setError),re=j(U=>U.sessionId),ve=j(U=>U.initialMessage),K=j(U=>U.sessionInitialMessages),Ae=j(U=>U.elicitationState),He=j(U=>U.level),{incomingMessages:ae,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:xt,markWidgetOpened:$t,startSession:z,startNewChat:Ie,isReady:we,startRecording:Le,stopRecording:qe,handleRetry:Ue,isValidFile:Et,sendMessageFeedback:ht,clearElicitationState:ze,sendSessionFeedback:rt,getPastSessions:Be}=Mp({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:Pp(n.displayMode)}),Ge=Ke(Ue),Oe=Ke(ht),Bt=Ke(ze),yt=Ke(U=>{z({sessionId:U})}),an=Ke(()=>{Ie()}),[ln,On]=F(!1),[Rn,Qr]=F([]),[Lt,gr]=F(!0),_r=X(Be);Y(()=>{_r.current=Be});const Gt=de(async()=>{gr(!0);try{const U=await _r.current();Qr(U)}catch{}finally{gr(!1)}},[]),eo=de(async()=>{On(!0),await Gt()},[Gt]),to=de(()=>{On(!1)},[]),[Er,yr]=F(!1),Wt=de(()=>yr(U=>!U),[]);Y(()=>{E!=="full"||He!=="user"||Gt()},[E,He,re,Gt]),Y(()=>{if(t){if(pe.current!==t){const U=j.getState();Qh(t),nm(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&&we&&!S.current&&(S.current=!0,z({forceNewSession:!1}))}},[e,we,t]),Y(()=>{e&&$t()},[e]),Y(()=>{zm([tc])},[]),Y(()=>()=>{s()},[]),Y(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||he(!0)},[n.theme?.upfrontConsent,t]);const Sr=de(()=>{yc(t,hs),he(!1)},[t]),no=Ke(()=>{n.feedback&&!ms(t,Ec)?B(!0):n.onClose()}),br=Ke(async(U,ke)=>{await rt(U,ke),B(!1),n.onClose()}),An=Ke(()=>{B(!1),n.onClose()}),cn=Ke(()=>{yc(t,Ec),B(!1),n.onClose()}),vr=de(()=>{B(!1)},[]),wr=ae.length>0,In=ae.length===1,w=ie(()=>{const U=ae[ae.length-1],ke=U?.tool_keys?.[U.tool_keys.length-1];if(!ke)return null;const Ve=Ae[ke];return Ve?.active?{...Ve,tool_key:ke}:null},[ae,Ae]),O=ie(()=>(re?K[re]:void 0)??ve??n?.initialMessage??null,[re,K,ve,n?.initialMessage]),D=ie(()=>!!O?.text||!!O?.suggestions?.length,[O]),A=ie(()=>D&&ae?.length===0&&!Pe,[ae,D,Pe]),q=ie(()=>w?w.component===M.SYNAPSE_COMPONENTS.MOBILE||w.component===M.SYNAPSE_COMPONENTS.OTP||w.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[w]),{scrollAreaRef:oe,messagesEndRef:ce,showScrollButton:ue,scrollToBottom:Me}=Vp({messageCount:ae.length,isStreaming:I,isFirstMessage:In,resolvedMode:E}),We=Re===_e.CONNECTED,Te=Q||I,xe=!Te&&We&&!le&&!h&&!_&&te===be.IDLE&&!v&&u.trim().length===0,[Je,Ct]=F(!1);Y(()=>{if(!xe){Ct(!1);return}const U=setTimeout(()=>Ct(!0),Hp);return()=>clearTimeout(U)},[xe]);const kt=ie(()=>te===be.IDLE?null:te===be.LISTENING?"Listening...":te===be.PROCESSING?"Processing...":te===be.TRANSCRIBING?"Transcribing...":null,[te]),[Ot,Kt]=F(0);Y(()=>{if(!xe){Kt(0);return}const U=setInterval(()=>Kt(ke=>ke+1),zp);return()=>clearInterval(U)},[xe]);const Qe=kt&&te!==be.IDLE?kt:Q||I?"Please wait for the response...":Yp(Ot),Z=Ke(async(U,ke)=>{if(Te)return;const Ve=ke?xt:De,fe=U?.message??u;T.length>0?(await Ve({files:T,message:fe.trim()}),C([]),N(!1)):fe.trim()?await Ve({...U,message:fe.trim()}):U?.resend?await Ve(U):U&&await Ve(U),p(""),f(!1),N(!1)}),mt=Ke(U=>Z(U,A)),et=Ke(U=>Z(U,!0)),pt=Ke(U=>{if(U&&U.length>0){const ke=U.filter(fe=>Et(fe));if(ke.length===0)return;const Ve=gc(ke,T.length);if(Ve){W(Ve);return}U=ke}C(ke=>(N((ke?.length??0)+(U?.length??0)>0),[...ke,...U]))}),lt=de(U=>{C(ke=>{const Ve=ke.filter((fe,ye)=>ye!==U);return N(Ve.length>0),Ve})},[]),Rt=Ke(async()=>{if(_)await qe(),f(!1);else{if(Te)return;try{await Le(),f(!0)}catch{}}}),St=Ke(U=>{p(U)}),Fe=ie(()=>({value:u,onChange:St,onSend:Z,onFileChange:pt,onRemoveFile:lt,onRecording:Rt,isRecording:_,hasAttachment:v,attachmentFiles:T,isDisabled:Te,placeholder:Qe,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d,showAttention:Je}),[u,St,Z,pt,lt,Rt,_,v,T,Te,Qe,te,n.allowed,h,d,Je]),ot=ie(()=>n.feedback?{isOpen:P,config:n.feedback,onSubmit:br,onSkip:An,onClose:vr,onDontShowAgain:cn}:void 0,[n.feedback,P,br,An,vr,cn]),At=ie(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Sr}:void 0,[n.theme?.upfrontConsent,G,Sr]);return{showScrollButton:ue,toggleDisplayMode:m,resolvedMode:E,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:ce,startNewConnection:se,showRetryButton:Ee,clearError:V,error:le,sessionId:re,activeElicitation:w,inConversation:wr,isFirstMessage:In,isEmptyChat:A,isAuthComponent:q,isConnected:We,isComposerDisabled:Te,isLoadingSessionMessages:Pe,initialMessage:O,incomingMessages:ae,sendMessageFeedback:Oe,clearElicitationState:Bt,handleRetry:Ge,handleChatSendMessage:mt,handleEmptyStateSendMessage:et,handleSelectSession:yt,handleStartNewChat:an,scrollToBottom:Me,handleClose:no,chatComposerProps:Fe,feedbackModalProps:ot,consentModalProps:At,isSessionDrawerOpen:ln,pastSessions:Rn,isLoadingPastSessions:Lt,openSessionDrawer:eo,closeSessionDrawer:to,userLevel:He,isSidebarCollapsed:Er,toggleSidebar:Wt,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:l}}function Sc({bare:e}){return c("div",{className:"flex justify-start synapse-message-in",children:c(en,{className:L("px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",e&&"!bg-transparent !shadow-none !px-0 !backdrop-blur-none"),children:c("div",{className:"flex items-center gap-1.5 h-5",role:"status","aria-label":"Bot is typing",children:[0,1,2].map(t=>c("span",{className:"synapse-typing-dot w-2 h-2 rounded-full bg-foreground",style:{animationDelay:`${t*160}ms`}},t))})})})}function on(){return on=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},on.apply(this,arguments)}const Bp=["children","options"],bc=["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"}),vc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Gp=["style","script","pre"],Wp=["src","href","data","formAction","srcDoc","action"],Kp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,qp=/\n{2,}$/,wc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Xp=/^ *> ?/gm,Zp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Jp=/^ {2,}\n/,Qp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Nc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Tc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,ef=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,tf=/^(?:\n *)*\n/,nf=/\r\n?/g,rf=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,of=/^\[\^([^\]]+)]/,sf=/\f/g,af=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,lf=/^\s*?\[(x|\s)\]/,xc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,kc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,cf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Oc=/^<!--[\s\S]*?(?:-->)/,df=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,uf=/^\{.*\}$/,hf=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,mf=/^<([^ >]+[:@\/][^ >]+)>/,pf=/-([a-z])?/gi,Rc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,ff=/^[^\n]+(?: \n|\n{2,})/,gf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,_f=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Ef=/^\[([^\]]*)\] ?\[([^\]]*)\]/,yf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Sf=/\t/g,bf=/(^ *\||\| *$)/g,vf=/^ *:-+: *$/,wf=/^ *:-+ *$/,Nf=/^ *-+: *$/,Gr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Wr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Tf=RegExp(`^([*_])\\1${Gr(1)}${Wr}\\1\\1(?!\\1)`),xf=RegExp(`^([*_])${Gr(0)}${Wr}\\1(?!\\1)`),Cf=RegExp(`^(==)${Gr(0)}${Wr}\\1`),kf=RegExp(`^(~~)${Gr(0)}${Wr}\\1`),Of=/^(:[a-zA-Z0-9-_]+:)/,Rf=/^\\([^0-9A-Za-z\s])/,Af=/\\([^0-9A-Za-z\s])/g,If=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Mf=/^\n+/,Pf=/^([ \t]*)/,Df=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Ac(e){return"( *)("+(e===1?gs:_s)+") +"}const Ic=Ac(1),Mc=Ac(2);function Pc(e){return RegExp("^"+(e===1?Ic:Mc))}const Lf=Pc(1),Uf=Pc(2);function Dc(e){return RegExp("^"+(e===1?Ic:Mc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Ff=Dc(1),Vf=Dc(2);function Lc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Uc=Lc(1),Fc=Lc(2);function Vc(e,t){const n=t===1,r=n?Uc:Fc,o=n?Ff:Vf,i=n?Lf:Uf;return{t:s=>i.test(s),o:kn(function(s,a){const l=Df.exec(a.prevCapture);return l&&(a.list||!a.inline&&!a.simple)?r.exec(s=l[1]+s):null}),i:1,u(s,a,l){const d=n?+s[2]:void 0,h=s[0].replace(qp,`
|
|
41
41
|
`).match(o);let u=!1;return{items:h.map(function(p,_){const f=i.exec(p)[0].length,g=RegExp("^ {1,"+f+"}","gm"),b=p.replace(g,"").replace(i,""),m=_===h.length-1,E=b.indexOf(`
|
|
42
42
|
|
|
43
43
|
`)!==-1||m&&u;u=E;const y=l.inline,k=l.list;let x;l.list=!0,E?(l.inline=!1,x=mr(b)+`
|
|
44
44
|
|
|
45
45
|
`):(l.inline=!0,x=mr(b));const T=a(x,l);return l.inline=y,l.list=k,T}),ordered:n,start:d}},l:(s,a,l)=>e(s.ordered?"ol":"ul",{key:l.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,l))}))}}const jf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),zf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function jc(e){return typeof e=="string"}function mr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Kr(e,t){return e.startsWith(t)}function Yf(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Kr(e,n[r]))return!0;return!1}return n(e,t)}function pr(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function Hf(e){return Nf.test(e)?"right":vf.test(e)?"center":wf.test(e)?"left":null}function zc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const l=i[i.length-1];l.push.apply(l,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((l,d,h)=>{l.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=l}),a(),n.inTable=o,i}function $f(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(bf,"").split("|").map(Hf):[],o=e[3]?(function(s,a,l){return s.trim().split(`
|
|
46
|
-
`).map(function(d){return zc(d,a,l,!0)})})(e[3],t,n):[],i=zc(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 Yc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function kn(e){return e.inline=1,e}function sn(e){return kn(function(t,n){return n.inline?e.exec(t):null})}function Ht(e){return kn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Dt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function qr(e){return kn(function(t){return e.exec(t)})}const Bf=/(javascript|vbscript|data(?!:image)):/i;function Gf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Bf.test(t))return null}catch{return null}return e}function
|
|
46
|
+
`).map(function(d){return zc(d,a,l,!0)})})(e[3],t,n):[],i=zc(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 Yc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function kn(e){return e.inline=1,e}function sn(e){return kn(function(t,n){return n.inline?e.exec(t):null})}function Ht(e){return kn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Dt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function qr(e){return kn(function(t){return e.exec(t)})}const Bf=/(javascript|vbscript|data(?!:image)):/i;function Gf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Bf.test(t))return null}catch{return null}return e}function Tt(e){return e&&e.replace(Af,"$1")}function Xr(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!0,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function Wf(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 Kf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Es=(e,t,n)=>({children:Xr(t,e[2],n)});function ys(){return{}}function Ss(){return null}function qf(...e){return e.filter(Boolean).join(" ")}function bs(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function Xf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?on({},vc,t.namedCodesToUnicode):vc;const n=t.slugify||pr,r=t.sanitizer||Gf,o=t.createElement||tt,i=[wc,Nc,Tc,t.enforceAtxHeadings?Cc:xc,kc,Rc,Uc,Fc],s=[...i,ff,ps,Oc,fs];function a(m,E){for(let y=0;y<m.length;y++)if(m[y].test(E))return!0;return!1}function l(m,E,...y){const k=bs(t.overrides,m+".props",{});return o((function(x,T){const C=bs(T,x);return C?typeof C=="function"||typeof C=="object"&&"render"in C?C:bs(T,x+".component",x):x})(m,t.overrides),on({},E,k,{className:qf(E?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(af,"");let E=!1;t.forceInline?E=!0:t.forceBlock||(E=yf.test(m)===!1);const y=g(f(E?m:mr(m).replace(Mf,"")+`
|
|
47
47
|
|
|
48
|
-
`,{inline:E}));for(;jc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(E?"span":"div");let x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?l("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,E){if(!E||!E.trim())return null;const y=E.match(Kp);return y?y.reduce(function(k,x){const T=x.indexOf("=");if(T!==-1){const C=(function(
|
|
49
|
-
`);return E>0&&E<m.length-1&&(m[E+1]==="="||m[E+1]==="-")},o:Dt(kc),i:1,u:(m,E,y)=>({children:Xr(E,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:qr(ps),i:1,u(m,E,y){const[,k]=m[3].match(Pf),x=RegExp("^"+k,"gm"),T=m[3].replace(x,""),C=a(s,T)?Kf:Xr,S=m[1].toLowerCase(),v=Gp.indexOf(S)!==-1,N=(v?S:m[1]).trim(),
|
|
48
|
+
`,{inline:E}));for(;jc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(E?"span":"div");let x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?l("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,E){if(!E||!E.trim())return null;const y=E.match(Kp);return y?y.reduce(function(k,x){const T=x.indexOf("=");if(T!==-1){const C=(function(P){return P.indexOf("-")!==-1&&P.match(df)===null&&(P=P.replace(pf,function(B,G){return G.toUpperCase()})),P})(x.slice(0,T)).trim(),S=(function(P){const B=P[0];return(B==='"'||B==="'")&&P.length>=2&&P[P.length-1]===B?P.slice(1,-1):P})(x.slice(T+1).trim()),v=bc[C]||C;if(v==="ref")return k;const N=k[v]=(function(P,B,G,he){return B==="style"?(function(pe){const se=[];let Ee="",V=!1,le=!1,Re="";if(!pe)return se;for(let Q=0;Q<pe.length;Q++){const I=pe[Q];if(I!=='"'&&I!=="'"||V||(le?I===Re&&(le=!1,Re=""):(le=!0,Re=I)),I==="("&&Ee.endsWith("url")?V=!0:I===")"&&V&&(V=!1),I!==";"||le||V)Ee+=I;else{const W=Ee.trim();if(W){const re=W.indexOf(":");if(re>0){const ve=W.slice(0,re).trim(),K=W.slice(re+1).trim();se.push([ve,K])}}Ee=""}}const te=Ee.trim();if(te){const Q=te.indexOf(":");if(Q>0){const I=te.slice(0,Q).trim(),W=te.slice(Q+1).trim();se.push([I,W])}}return se})(G).reduce(function(pe,[se,Ee]){return pe[se.replace(/(-[a-z])/g,V=>V[1].toUpperCase())]=he(Ee,P,se),pe},{}):Wp.indexOf(B)!==-1?he(Tt(G),P,B):(G.match(uf)&&(G=Tt(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,C,S,r);typeof N=="string"&&(ps.test(N)||fs.test(N))&&(k[v]=d(N.trim()))}else x!=="style"&&(k[bc[x]||x]=!0);return k},{}):null}const u=[],p={},_={0:{t:[">"],o:Dt(wc),i:1,u(m,E,y){const[,k,x]=m[0].replace(Xp,"").match(Zp);return{alert:k,children:E(x,y)}},l(m,E,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),pr),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),l("blockquote",k,E(m.children,y))}},1:{t:[" "],o:qr(Jp),i:1,u:ys,l:(m,E,y)=>l("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Dt(Qp),i:1,u:ys,l:(m,E,y)=>l("hr",{key:y.key})},3:{t:[" "],o:Dt(Tc),i:0,u:m=>({lang:void 0,text:Tt(mr(m[0].replace(/^ {4}/gm,"")))}),l:(m,E,y)=>l("pre",{key:y.key},l("code",on({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Dt(Nc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Ht(ef),i:3,u:m=>({text:Tt(m[2])}),l:(m,E,y)=>l("code",{key:y.key},m.text)},6:{t:["[^"],o:Dt(rf),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Ss},7:{t:["[^"],o:sn(of),i:1,u:m=>({target:"#"+n(m[1],pr),text:m[1]}),l:(m,E,y)=>l("a",{key:y.key,href:r(m.target,"a","href")},l("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:sn(lf),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,E,y)=>l("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Dt(t.enforceAtxHeadings?Cc:xc),i:1,u:(m,E,y)=>({children:Xr(E,m[2],y),id:n(m[2],pr),level:m[1].length}),l:(m,E,y)=>l("h"+m.level,{id:m.id,key:y.key},E(m.children,y))},10:{t:m=>{const E=m.indexOf(`
|
|
49
|
+
`);return E>0&&E<m.length-1&&(m[E+1]==="="||m[E+1]==="-")},o:Dt(kc),i:1,u:(m,E,y)=>({children:Xr(E,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:qr(ps),i:1,u(m,E,y){const[,k]=m[3].match(Pf),x=RegExp("^"+k,"gm"),T=m[3].replace(x,""),C=a(s,T)?Kf:Xr,S=m[1].toLowerCase(),v=Gp.indexOf(S)!==-1,N=(v?S:m[1]).trim(),P={attrs:h(N,m[2]),noInnerParse:v,tag:N};if(y.inAnchor=y.inAnchor||S==="a",v)P.text=m[3];else{const B=y.inHTML;y.inHTML=!0,P.children=C(E,T,y),y.inHTML=B}return y.inAnchor=!1,P},l:(m,E,y)=>l(m.tag,on({key:y.key},m.attrs),m.text||(m.children?E(m.children,y):""))},13:{t:["<"],o:qr(fs),i:1,u(m){const E=m[1].trim();return{attrs:h(E,m[2]||""),tag:E}},l:(m,E,y)=>l(m.tag,on({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:qr(Oc),i:1,u:()=>({}),l:Ss},14:{t:["!["],o:Ht(zf),i:1,u:m=>({alt:Tt(m[1]),target:Tt(m[2]),title:Tt(m[3])}),l:(m,E,y)=>l("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:sn(jf),i:3,u:(m,E,y)=>({children:Wf(E,m[1],y),target:Tt(m[2]),title:Tt(m[3])}),l:(m,E,y)=>l("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},E(m.children,y))},16:{t:["<"],o:sn(mf),i:0,u(m){let E=m[1],y=!1;return E.indexOf("@")!==-1&&E.indexOf("//")===-1&&(y=!0,E=E.replace("mailto:","")),{children:[{text:E,type:"27"}],target:y?"mailto:"+E:E,type:"15"}}},17:{t:(m,E)=>!E.inAnchor&&!t.disableAutoLink&&(Kr(m,"http://")||Kr(m,"https://")),o:sn(hf),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Vc(l,1),33:Vc(l,2),19:{t:[`
|
|
50
50
|
`],o:Dt(tf),i:3,u:ys,l:()=>`
|
|
51
51
|
`},21:{o:kn(function(m,E){if(E.inline||E.simple||E.inHTML&&m.indexOf(`
|
|
52
52
|
|
|
53
53
|
`)===-1&&E.prevCapture.indexOf(`
|
|
54
54
|
|
|
55
55
|
`)===-1)return null;let y="",k=0;for(;;){const T=m.indexOf(`
|
|
56
|
-
`,k),C=m.slice(k,T===-1?void 0:T+1);if(a(i,C)||(y+=C,T===-1||!C.trim()))break;k=T+1}const x=mr(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,E,y)=>l("p",{key:y.key},E(m.children,y))},22:{t:["["],o:sn(gf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:Ht(_f),i:0,u:m=>({alt:m[1]?
|
|
57
|
-
`).replace(sf,"").replace(Sf," ")})(k),x)}})(_),g=(function(m,E){return function y(k,x={}){if(Array.isArray(k)){const T=x.key,C=[];let S=!1;for(let v=0;v<k.length;v++){x.key=v;const N=y(k[v],x),D=jc(N);D&&S?C[C.length-1]+=N:N!==null&&C.push(N),S=D}return x.key=T,C}return(function(T,C,S){const v=m[T.type].l;return E?E(()=>v(T,C,S),T,C,S):v(T,C,S)})(k,y,x)}})(_,t.renderRule),b=d(e);return u.length?l("div",null,b,l("footer",{key:"footer"},u.map(function(m){return l("div",{id:n(m.identifier,pr),key:m.identifier},m.identifier,g(f(m.footnote,{inline:!0})))}))):b}const Jf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,l={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(l[s]=o[s]);return l})(e,Bp);return Ft(Xf(t??"",n),r)},Zf={disableParsingRawHTML:!0,forceBlock:!0};function Qf({children:e}){return c(Jf,{options:Zf,children:e})}const Jr=Xt(Qf),eg=45,tg=8,ng=15,rg=25,og=16,sg=4,ig=1200,ag=5e3,lg=/\s*\S+\s*/g;function Hc(){return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function $c(e,t,n){const[r]=F(Hc),o=t&&!r,[i,s]=F(()=>o&&n?0:e.length),a=o?Math.min(i,e.length):e.length,l=a>=e.length;return Y(()=>{if(!o||l)return;const d=e.slice(a).match(lg)??[],h=n&&!/\s$/.test(e)?d.slice(0,-1):d;if(!h.length)return;const u=Math.max(1,Math.ceil(h.length/(n?rg:sg))),p=n?eg+Math.max(0,tg-h.length)*ng:og,_=a+h.slice(0,u).join("").length,f=setTimeout(()=>s(_),p);return()=>clearTimeout(f)},[o,l,e,a,n]),{displayedText:e.slice(0,a),caughtUp:l}}function cg(e,t){const[n,r]=F(0);return Y(()=>{if(r(0),!e)return;const o=setTimeout(()=>r(1),ig),i=setTimeout(()=>r(2),ag);return()=>{clearTimeout(o),clearTimeout(i)}},[e,t]),e?n:0}function Bc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?c("div",{onClick:i?void 0:o,className:L("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&c("span",{className:s?"text-primary-foreground":"text-primary",children:r}),c("span",{className:"block whitespace-normal",children:e})]}):null}const dg=nt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),ug=nt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),hg=nt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),mg=nt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),pg=nt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function $e({className:e}){return c("div",{className:L("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function fr({variant:e}){return e==="pill"?c("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[c(Zr,{}),c($e,{className:"h-8 w-20 rounded-full"}),c($e,{className:"h-8 w-24 rounded-full"}),c($e,{className:"h-8 w-16 rounded-full"})]}):e==="media"?c("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[c(Zr,{}),c($e,{className:"h-24 w-full rounded-lg"}),c("div",{className:"mt-3 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?c("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[c(Zr,{}),c($e,{className:"h-3 w-32 rounded mb-3"}),c("div",{className:"space-y-2",children:[c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"})]}),c($e,{className:"mt-4 h-9 w-full rounded-lg"})]}):c("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[c(Zr,{}),c("div",{className:"flex items-center gap-3",children:[c($e,{className:"h-10 w-10 rounded-full"}),c("div",{className:"flex-1 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}),c("div",{className:"mt-4 space-y-2",children:[c($e,{className:"h-3 w-full rounded"}),c($e,{className:"h-3 w-5/6 rounded"})]}),c($e,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Zr(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function fg({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=F([]),[a,l]=F({}),[d,h]=F(!1),[u,p]=F(5),_=n.component,f=n.disabled,g=ie(()=>n.input,[n.input]);Y(()=>{_===I.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&l(g.doctor_details)},[_,g?.doctor_details]),Y(()=>{n.disabled||(h(!1),p(5),s([]))},[g,n.disabled]);const b=async v=>{h(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},m=async(v,N,D,B=!0)=>{await r({toolCalled:B,selectedComponent:v,selected_id:v.doctor_id,message:N,tool_key:t,messageId:e,...D&&{tool_result:D}})},E=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const v=_===I.SYNAPSE_COMPONENTS.MULTI&&g?.options;return v?Array.isArray(v)?v.map((N,D)=>({id:`option-${D}`,label:N.label,value:N.value})):Object.keys(v).map((N,D)=>({id:`option-${D}`,label:N,value:N})):[]},x=ie(()=>{if(_===I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[_,g?.doctors]);if(!_)return null;const T=_===I.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,C=_===I.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,S=_===I.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return c("div",{className:"flex justify-end",children:[T&&c("div",{className:`flex ${T.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[T.slice(0,u).map((v,N)=>c(Bc,{disabled:f||o||d,text:v?.label||"",onClick:()=>b(v),className:"cursor-pointer"},N)),T.length>u&&c("button",{type:"button",disabled:f||o||d,onClick:()=>p(v=>v+5),className:L("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[c(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,T.length-u)," more"]})]}),_===I.SYNAPSE_COMPONENTS.MULTI&&g?.options&&c(Xe,{fallback:c(fr,{variant:"input"}),children:c("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[c("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),c(dg,{options:k(),selectedValues:i,onSelectionChange:s,disabled:f||o}),c(Se,{onClick:y,disabled:i.length===0||f||o,className:L("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),x&&x.length>0?c(Xe,{fallback:c(fr,{variant:"card"}),children:c(ug,{count:x.length>1?x.length+1:x.length,renderItem:(v,N)=>{if(x.length>1&&v===x.length&&n?.hide_show_more!==!0)return c("button",{type:"button",onClick:E,disabled:o||f,className:L("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[c("span",{className:L("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:c($h,{className:"w-4 h-4 text-primary"})}),c("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const D=x[v];return c(Xe,{fallback:c(fr,{variant:"card"}),children:c(hg,{doctor:D,doctorDetails:a?.[D.doctor_id],disabled:o,onSelect:m,isActive:N})},D.doctor_id)}})}):null,C&&c(Xe,{fallback:c(fr,{variant:"card"}),children:c(mg,{cards:C,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:f||o})}),S&&c(Xe,{fallback:c(fr,{variant:"media"}),children:c("div",{className:"mt-3",children:c(pg,{card:S})})})]})}function Gc({userFeedback:e,onToggleFeedback:t}){if(e===I.USER_FEEDBACK.NONE)return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c("div",{className:"flex items-center gap-1",children:[c(Se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.LIKE),children:c(vl,{className:"h-3 w-3"})}),c(Se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>t(I.USER_FEEDBACK.DISLIKE),children:c(wl,{className:"h-3 w-3"})})]})});if(e===I.USER_FEEDBACK.LIKE||e===I.USER_FEEDBACK.DISLIKE){const n=e===I.USER_FEEDBACK.LIKE?vl:wl;return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:c(n,{className:"h-3 w-3"})})})}return null}function gg({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:l,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:p,onClearElicitationState:_,isAuthComponent:f,isFullScreen:g}){const b=t===Ne.USER,[m,E]=F(I.USER_FEEDBACK.NONE),y=j(B=>B.isStreaming),k=!b&&!!o,x=k&&y,{displayedText:T,caughtUp:C}=$c(n||"",k,x),S=x||!C,v=cg(x&&!i,T.length),N=B=>{E(B),u(B,e)},D=!!(n?.trim()||r&&r.length>0||d||i||a);return c(me,{children:[D&&c("div",{className:L("flex",b?"justify-end":"justify-start"),children:c("div",{className:L("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:L("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":L("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&c("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),T&&c("div",{className:L("markdown-content",g&&!b?"text-base leading-6":"text-sm",S&&"synapse-streaming"),children:c(Jr,{children:T})}),T&&v>0&&c("p",{className:"synapse-shimmer-text mt-1.5 text-xs font-medium text-muted-foreground",role:"status",children:v===1?"Thinking\u2026":"Still working on it\u2026"},v),r&&r.length>0&&c("div",{className:"mt-2",children:c(ls,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!S&&o&&(n||m!==I.USER_FEEDBACK.NONE)&&c(Gc,{userFeedback:m,onToggleFeedback:N}),f&&o&&s?.length?c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{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 B=s[s.length-1];B&&l[B]?.active&&_(B,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(B=>{const G=l[B];return G?c(fg,{messageId:e,tool_key:B,entry:G,onSendMessage:h,disabled:p||G.disabled},B):null}),a&&!b&&c("div",{className:"flex justify-start",children:c("div",{className:L("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:L("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",g&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:c("div",{className:L("markdown-content",g?"text-base leading-6":"text-sm"),children:c(Jr,{children:a})})}),!S&&o&&c(Gc,{userFeedback:m,onToggleFeedback:N})]})})})]})}const _g=Xt(gg),vs=3,Eg=700,yg=450,Sg=70;function bg(e=""){const t=(e.includes("```")?[e]:e.split(/\n\s*\n/)).filter(n=>n.trim());return t.length>vs?[...t.slice(0,vs-1),t.slice(vs-1).join(`
|
|
56
|
+
`,k),C=m.slice(k,T===-1?void 0:T+1);if(a(i,C)||(y+=C,T===-1||!C.trim()))break;k=T+1}const x=mr(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,E,y)=>l("p",{key:y.key},E(m.children,y))},22:{t:["["],o:sn(gf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:Ht(_f),i:0,u:m=>({alt:m[1]?Tt(m[1]):void 0,ref:m[2]}),l:(m,E,y)=>p[m.ref]?l("img",{key:y.key,alt:m.alt,src:r(p[m.ref].target,"img","src"),title:p[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:sn(Ef),i:0,u:(m,E,y)=>({children:E(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,E,y)=>p[m.ref]?l("a",{key:y.key,href:r(p[m.ref].target,"a","href"),title:p[m.ref].title},E(m.children,y)):l("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Dt(Rc),i:1,u:$f,l(m,E,y){const k=m;return l("table",{key:y.key},l("thead",null,l("tr",null,k.header.map(function(x,T){return l("th",{key:T,style:Yc(k,T)},E(x,y))}))),l("tbody",null,k.cells.map(function(x,T){return l("tr",{key:T},x.map(function(C,S){return l("td",{key:S,style:Yc(k,S)},E(C,y))}))})))}},27:{o:kn(function(m,E){let y;return Kr(m,":")&&(y=Of.exec(m)),y||If.exec(m)}),i:4,u(m){const E=m[0];return{text:E.indexOf("&")===-1?E:E.replace(cf,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Ht(Tf),i:2,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>l("strong",{key:y.key},E(m.children,y))},29:{t:m=>{const E=m[0];return(E==="*"||E==="_")&&m[1]!==E},o:Ht(xf),i:3,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>l("em",{key:y.key},E(m.children,y))},30:{t:["\\"],o:Ht(Rf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Ht(Cf),i:3,u:Es,l:(m,E,y)=>l("mark",{key:y.key},E(m.children,y))},32:{t:["~~"],o:Ht(kf),i:3,u:Es,l:(m,E,y)=>l("del",{key:y.key},E(m.children,y))}};t.disableParsingRawHTML===!0&&(delete _[11],delete _[13]);const f=(function(m){var E=Object.keys(m);function y(k,x){var T=[];if(x.prevCapture=x.prevCapture||"",k.trim())for(;k;)for(var C=0;C<E.length;){var S=E[C],v=m[S];if(!v.t||Yf(k,x,v.t)){var N=v.o(k,x);if(N&&N[0]){k=k.substring(N[0].length);var P=v.u(N,y,x);x.prevCapture+=N[0],P.type||(P.type=S),T.push(P);break}C++}else C++}return x.prevCapture="",T}return E.sort(function(k,x){return m[k].i-m[x].i||(k<x?-1:1)}),function(k,x){return y((function(T){return T.replace(nf,`
|
|
57
|
+
`).replace(sf,"").replace(Sf," ")})(k),x)}})(_),g=(function(m,E){return function y(k,x={}){if(Array.isArray(k)){const T=x.key,C=[];let S=!1;for(let v=0;v<k.length;v++){x.key=v;const N=y(k[v],x),P=jc(N);P&&S?C[C.length-1]+=N:N!==null&&C.push(N),S=P}return x.key=T,C}return(function(T,C,S){const v=m[T.type].l;return E?E(()=>v(T,C,S),T,C,S):v(T,C,S)})(k,y,x)}})(_,t.renderRule),b=d(e);return u.length?l("div",null,b,l("footer",{key:"footer"},u.map(function(m){return l("div",{id:n(m.identifier,pr),key:m.identifier},m.identifier,g(f(m.footnote,{inline:!0})))}))):b}const Zf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,l={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(l[s]=o[s]);return l})(e,Bp);return Ft(Xf(t??"",n),r)},Jf={disableParsingRawHTML:!0,forceBlock:!0};function Qf({children:e}){return c(Zf,{options:Jf,children:e})}const Zr=Xt(Qf),eg=45,tg=8,ng=15,rg=25,og=16,sg=4,ig=1200,ag=5e3,lg=/\s*\S+\s*/g;function Hc(){return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function $c(e,t,n){const[r]=F(Hc),o=t&&!r,[i,s]=F(()=>o&&n?0:e.length),a=o?Math.min(i,e.length):e.length,l=a>=e.length;return Y(()=>{if(!o||l)return;const d=e.slice(a).match(lg)??[],h=n&&!/\s$/.test(e)?d.slice(0,-1):d;if(!h.length)return;const u=Math.max(1,Math.ceil(h.length/(n?rg:sg))),p=n?eg+Math.max(0,tg-h.length)*ng:og,_=a+h.slice(0,u).join("").length,f=setTimeout(()=>s(_),p);return()=>clearTimeout(f)},[o,l,e,a,n]),{displayedText:e.slice(0,a),caughtUp:l}}function cg(e,t){const[n,r]=F(0);return Y(()=>{if(r(0),!e)return;const o=setTimeout(()=>r(1),ig),i=setTimeout(()=>r(2),ag);return()=>{clearTimeout(o),clearTimeout(i)}},[e,t]),e?n:0}function Bc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?c("div",{onClick:i?void 0:o,className:L("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&c("span",{className:s?"text-primary-foreground":"text-primary",children:r}),c("span",{className:"block whitespace-normal",children:e})]}):null}const dg=nt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),ug=nt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),hg=nt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),mg=nt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),pg=nt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function $e({className:e}){return c("div",{className:L("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function fr({variant:e}){return e==="pill"?c("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[c(Jr,{}),c($e,{className:"h-8 w-20 rounded-full"}),c($e,{className:"h-8 w-24 rounded-full"}),c($e,{className:"h-8 w-16 rounded-full"})]}):e==="media"?c("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[c(Jr,{}),c($e,{className:"h-24 w-full rounded-lg"}),c("div",{className:"mt-3 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?c("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[c(Jr,{}),c($e,{className:"h-3 w-32 rounded mb-3"}),c("div",{className:"space-y-2",children:[c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"})]}),c($e,{className:"mt-4 h-9 w-full rounded-lg"})]}):c("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[c(Jr,{}),c("div",{className:"flex items-center gap-3",children:[c($e,{className:"h-10 w-10 rounded-full"}),c("div",{className:"flex-1 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}),c("div",{className:"mt-4 space-y-2",children:[c($e,{className:"h-3 w-full rounded"}),c($e,{className:"h-3 w-5/6 rounded"})]}),c($e,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Jr(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function fg({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=F([]),[a,l]=F({}),[d,h]=F(!1),[u,p]=F(5),_=n.component,f=n.disabled,g=ie(()=>n.input,[n.input]);Y(()=>{_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&l(g.doctor_details)},[_,g?.doctor_details]),Y(()=>{n.disabled||(h(!1),p(5),s([]))},[g,n.disabled]);const b=async v=>{h(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},m=async(v,N,P,B=!0)=>{await r({toolCalled:B,selectedComponent:v,selected_id:v.doctor_id,message:N,tool_key:t,messageId:e,...P&&{tool_result:P}})},E=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const v=_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options;return v?Array.isArray(v)?v.map((N,P)=>({id:`option-${P}`,label:N.label,value:N.value})):Object.keys(v).map((N,P)=>({id:`option-${P}`,label:N,value:N})):[]},x=ie(()=>{if(_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[_,g?.doctors]);if(!_)return null;const T=_===M.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,C=_===M.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,S=_===M.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return c("div",{className:"flex justify-end",children:[T&&c("div",{className:`flex ${T.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[T.slice(0,u).map((v,N)=>c(Bc,{disabled:f||o||d,text:v?.label||"",onClick:()=>b(v),className:"cursor-pointer"},N)),T.length>u&&c("button",{type:"button",disabled:f||o||d,onClick:()=>p(v=>v+5),className:L("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[c(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,T.length-u)," more"]})]}),_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options&&c(Xe,{fallback:c(fr,{variant:"input"}),children:c("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[c("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),c(dg,{options:k(),selectedValues:i,onSelectionChange:s,disabled:f||o}),c(Se,{onClick:y,disabled:i.length===0||f||o,className:L("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),x&&x.length>0?c(Xe,{fallback:c(fr,{variant:"card"}),children:c(ug,{count:x.length>1?x.length+1:x.length,renderItem:(v,N)=>{if(x.length>1&&v===x.length&&n?.hide_show_more!==!0)return c("button",{type:"button",onClick:E,disabled:o||f,className:L("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[c("span",{className:L("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:c($h,{className:"w-4 h-4 text-primary"})}),c("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const P=x[v];return c(Xe,{fallback:c(fr,{variant:"card"}),children:c(hg,{doctor:P,doctorDetails:a?.[P.doctor_id],disabled:o,onSelect:m,isActive:N})},P.doctor_id)}})}):null,C&&c(Xe,{fallback:c(fr,{variant:"card"}),children:c(mg,{cards:C,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:f||o})}),S&&c(Xe,{fallback:c(fr,{variant:"media"}),children:c("div",{className:"mt-3",children:c(pg,{card:S})})})]})}function Gc({userFeedback:e,onToggleFeedback:t}){if(e===M.USER_FEEDBACK.NONE)return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c("div",{className:"flex items-center gap-1",children:[c(Se,{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(M.USER_FEEDBACK.LIKE),children:c(vl,{className:"h-3 w-3"})}),c(Se,{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(M.USER_FEEDBACK.DISLIKE),children:c(wl,{className:"h-3 w-3"})})]})});if(e===M.USER_FEEDBACK.LIKE||e===M.USER_FEEDBACK.DISLIKE){const n=e===M.USER_FEEDBACK.LIKE?vl:wl;return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:c(n,{className:"h-3 w-3"})})})}return null}function gg({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:l,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:p,onClearElicitationState:_,isAuthComponent:f,isFullScreen:g}){const b=t===Ne.USER,[m,E]=F(M.USER_FEEDBACK.NONE),y=j(B=>B.isStreaming),k=!b&&!!o,x=k&&y,{displayedText:T,caughtUp:C}=$c(n||"",k,x),S=x||!C,v=cg(x&&!i,T.length),N=B=>{E(B),u(B,e)},P=!!(n?.trim()||r&&r.length>0||d||i||a);return c(me,{children:[P&&c("div",{className:L("flex",b?"justify-end":"justify-start"),children:c("div",{className:L("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:L("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":L("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&c("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),T&&c("div",{className:L("markdown-content",g&&!b?"text-base leading-6":"text-sm",S&&"synapse-streaming"),children:c(Zr,{children:T})}),T&&v>0&&c("p",{className:"synapse-shimmer-text mt-1.5 text-xs font-medium text-muted-foreground",role:"status",children:v===1?"Thinking\u2026":"Still working on it\u2026"},v),r&&r.length>0&&c("div",{className:"mt-2",children:c(ls,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!S&&o&&(n||m!==M.USER_FEEDBACK.NONE)&&c(Gc,{userFeedback:m,onToggleFeedback:N}),f&&o&&s?.length?c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{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 B=s[s.length-1];B&&l[B]?.active&&_(B,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(B=>{const G=l[B];return G?c(fg,{messageId:e,tool_key:B,entry:G,onSendMessage:h,disabled:p||G.disabled},B):null}),a&&!b&&c("div",{className:"flex justify-start",children:c("div",{className:L("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:L("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",g&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:c("div",{className:L("markdown-content",g?"text-base leading-6":"text-sm"),children:c(Zr,{children:a})})}),!S&&o&&c(Gc,{userFeedback:m,onToggleFeedback:N})]})})})]})}const _g=Xt(gg),vs=3,Eg=700,yg=450,Sg=70;function bg(e=""){const t=(e.includes("```")?[e]:e.split(/\n\s*\n/)).filter(n=>n.trim());return t.length>vs?[...t.slice(0,vs-1),t.slice(vs-1).join(`
|
|
58
58
|
|
|
59
|
-
`)]:t}function vg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){const i=ie(()=>bg(e),[e]),[s]=F(Hc),[a,l]=F(s?1/0:0),d=a<i.length*2,h=d&&a%2===0;if(Y(()=>{if(!h)return;const p=setTimeout(()=>l(a+1),a?yg:Eg);return()=>clearTimeout(p)},[h,a]),!i.length&&!t?.length)return null;const u=p=>{const _=p.value||p.label||"";_&&n({message:_})};return c(me,{children:[i.length>0&&c("div",{className:"flex flex-col items-start gap-1.5","aria-live":"polite","aria-busy":d,children:[i.slice(0,Math.ceil(a/2)).map((p,_)=>c(wg,{text:p,isFullScreen:o,onDone:()=>l(f=>f===_*2+1?f+1:f)},_)),h&&c(Sc,{bare:o})]}),!d&&t&&t.length>0&&c("div",{className:"flex justify-end",children:c("div",{className:L("flex gap-2 mt-3 justify-end",t.length>3?"flex-col items-end":"flex-wrap"),children:t.map((p,_)=>c("div",{className:L("flex",!s&&"synapse-pill-in"),style:s?void 0:{animationDelay:`${120+_*Sg}ms`},children:c(Bc,{text:p.label||"",onClick:()=>u(p),disabled:r,className:"cursor-pointer"})},_))})})]})}function wg({text:e,isFullScreen:t,onDone:n}){const{displayedText:r,caughtUp:o}=$c(`${e} `,!0,!0);return Y(()=>{o&&n()},[o]),c("div",{className:L("flex gap-3 flex-row synapse-message-in",t?"w-full":"max-w-xs"),children:c(en,{className:L("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",t&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:c("div",{className:L("markdown-content",t?"text-base leading-6":"text-sm"),children:c(Jr,{children:r})})})})}const Ng=[];function Tg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const l=j(u=>u.isWaitingForResponse),d=j(u=>u.elicitationState),h=j(u=>u.progressMessage);return e.length===0&&!h?c(vg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):c(me,{children:[(e&&e.length>0||h)&&c(me,{children:e.map((u,p)=>c("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:p===e.length-1?"last-message":void 0,children:c(_g,{id:u.id,role:u.role,content:u.content,files:u.files||Ng,toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,onSendMessage:t,isLastMessage:p===e.length-1,progressMessage:p===e.length-1?h:null,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),l&&c(Sc,{})]})}const xg=Xt(Tg);function Wc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=uc(),[l,d]=F(!0);return Y(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?c("div",{className:L("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:c("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),c("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),c("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[c("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!l||!s&&!i?.title&&a?null:c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),c("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&c("div",{className:"flex-shrink-0",children:c("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const Cg=nt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function kg({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:l,showRetryButton:d,clearError:h,error:u,sessionId:p,activeElicitation:_,isAuthComponent:f,isConnected:g,inConversation:b,isFirstMessage:m,isEmptyChat:E,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:x,sendMessageFeedback:T,clearElicitationState:C,handleRetry:S,scrollToBottom:v,chatComposerProps:N,isComposerDisabled:D,voiceAgentState:B,isMuted:G,isVoiceAgentActive:he,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:Ee,handleClose:V,isSessionDrawerOpen:le,pastSessions:Re,isLoadingPastSessions:te,openSessionDrawer:Q,closeSessionDrawer:A,userLevel:W,isSidebarCollapsed:re,toggleSidebar:ve,feedbackModalProps:K,consentModalProps:Ae,handleChatSendMessage:He,handleEmptyStateSendMessage:ae,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:Tt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie}=$p({isOpen:e,agentId:t,config:n});Y(()=>{x.length||v("auto")},[x.length,v]);const we=ie(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=ie(()=>o==="full"&&W==="user"?c(cc,{variant:"sidebar",sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:ve,isLoading:te}):void 0,[o,W,Re,p,Pe,De,re,ve,te]),qe=ie(()=>({onRetry:S,showRetryButton:d,startNewConnection:l,clearError:h,error:u,isConnected:g}),[S,d,l,h,u,g]),Ue=ie(()=>({onClose:V,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:De,showStartNewChatButton:l,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:Q}),[V,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,l,n.resize,r,Q]),_t=ie(()=>c(cc,{variant:"drawer",isOpen:le,onClose:A,sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:te}),[le,A,Re,p,Pe,De,te]);return c(Um,{enabled:!!n.resize,children:c(oc,{value:Ue,children:c(ac,{isOpen:e,feedbackModal:K,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:Tt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie,theme:n.theme,isAuthComponent:f,activeElicitation:_,voiceAgentState:B,chatComposer:N,sessionDrawer:_t,sidebar:Le,fullScreenEmptyState:E?ut=>c(yp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ae,disabled:D,composer:ut.composer,composerFooter:ut.composerFooter,connectionBanner:c(Wc,{...qe})}):void 0,children:he?c(Xe,{fallback:c(Kc,{}),children:c(Cg,{state:B,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:Ee,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):c(Xe,{fallback:c(Kc,{}),children:c("div",{className:L("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[c("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:c(dl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[c("div",{className:"flex-1"}),c("div",{className:L("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?c(wm,{}):c(me,{children:[m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:we}),c(xg,{messages:x,onSendMessage:He,onToggleFeedback:T,onClearElicitationState:C,isAuthComponent:f,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),c("div",{ref:s})]})]})}),a&&c("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:c(Se,{onClick:()=>v("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:c(Wo,{className:"w-5 h-5 text-text-primary"})})}),c(Wc,{className:"mt-2",...qe})]})})})})})}function Kc(){return c("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[c("div",{className:"flex-1 p-6 space-y-4",children:[c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),c("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function qc(e){return!!e&&e.startsWith("ResizeObserver loop")}function ws(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);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:ws(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?c(Ig,{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 Rg({error:e}){throw e}function Ag(e){const[t,n]=F(null);return Y(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||qc(i?.message)||qc(i?.error?.message)||(i?.error?n(ws(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(ws(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),c(Og,{...e,children:t?c(Rg,{error:t}):e.children})}function Ig({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:l}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ie(()=>l?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[l?.textColor]),_=ie(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return c(oc,{value:_,children:c(ac,{isOpen:!0,environment:u,mode:a??"widget",theme:l,children:c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:c("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:c("div",{className:"w-full max-w-[320px] text-center",children:[c("div",{className:"mx-auto mb-4 grid place-items-center",children:c("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:c(zh,{className:"h-8 w-8",style:{color:l?.primary??"hsl(var(--primary))"}})})}),c("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),c("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),c("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",p].join(" "),children:e?.message||String(e)}),c("div",{className:"mt-5 flex items-center justify-center gap-3",children:c(Se,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:l?.primary??void 0},children:[c(Lh,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function Mg({agentId:e,config:t}){const[n,r]=F(t.displayMode==="full");Y(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return c(Ag,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:c(rm,{children:c(kg,{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 Xc=(e,t,n)=>{const r=n||{},o=wd(e);return o.render(c(me,{children:c(Mg,{agentId:t,config:r})})),o},Pg=e=>{try{const t=sessionStorage.getItem(ur(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Jc=e=>{const{refreshToken:t,sessToken:n}=Pg(e.agentId);return t&&n?Promise.resolve(null):I.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Zc=e=>I.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Xc,window.fetchAgentConfig=Zc,window.prefetchAuth=Jc);export{X as A,Se as B,Wo as C,ee as D,El as F,yl as I,Ko as M,Xt as N,pn as P,Oo as R,cs as S,ie as T,Tn as X,pt as _,I as a,L as b,Ye as c,F as d,me as e,Jt as f,Zc as fetchAgentConfig,bi as g,fn as h,Vt as i,zt as j,vp as k,Cl as l,ss as m,ql as n,is as o,bp as p,Jc as prefetchAuth,de as q,Ol as r,Xc as renderMedAssist,Jr as s,mc as t,c as u,en as v,wp as w,kl as x,Y as y,Rl as z};
|
|
59
|
+
`)]:t}function vg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){const i=ie(()=>bg(e),[e]),[s]=F(Hc),[a,l]=F(s?1/0:0),d=a<i.length*2,h=d&&a%2===0;if(Y(()=>{if(!h)return;const p=setTimeout(()=>l(a+1),a?yg:Eg);return()=>clearTimeout(p)},[h,a]),!i.length&&!t?.length)return null;const u=p=>{const _=p.value||p.label||"";_&&n({message:_})};return c(me,{children:[i.length>0&&c("div",{className:"flex flex-col items-start gap-1.5","aria-live":"polite","aria-busy":d,children:[i.slice(0,Math.ceil(a/2)).map((p,_)=>c(wg,{text:p,isFullScreen:o,onDone:()=>l(f=>f===_*2+1?f+1:f)},_)),h&&c(Sc,{bare:o})]}),!d&&t&&t.length>0&&c("div",{className:"flex justify-end",children:c("div",{className:L("flex gap-2 mt-3 justify-end",t.length>3?"flex-col items-end":"flex-wrap"),children:t.map((p,_)=>c("div",{className:L("flex",!s&&"synapse-pill-in"),style:s?void 0:{animationDelay:`${120+_*Sg}ms`},children:c(Bc,{text:p.label||"",onClick:()=>u(p),disabled:r,className:"cursor-pointer"})},_))})})]})}function wg({text:e,isFullScreen:t,onDone:n}){const{displayedText:r,caughtUp:o}=$c(`${e} `,!0,!0);return Y(()=>{o&&n()},[o]),c("div",{className:L("flex gap-3 flex-row synapse-message-in",t?"w-full":"max-w-xs"),children:c(en,{className:L("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",t&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:c("div",{className:L("markdown-content",t?"text-base leading-6":"text-sm"),children:c(Zr,{children:r})})})})}const Ng=[];function Tg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const l=j(u=>u.isWaitingForResponse),d=j(u=>u.elicitationState),h=j(u=>u.progressMessage);return e.length===0&&!h?c(vg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):c(me,{children:[(e&&e.length>0||h)&&c(me,{children:e.map((u,p)=>c("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:p===e.length-1?"last-message":void 0,children:c(_g,{id:u.id,role:u.role,content:u.content,files:u.files||Ng,toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,onSendMessage:t,isLastMessage:p===e.length-1,progressMessage:p===e.length-1?h:null,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),l&&c(Sc,{})]})}const xg=Xt(Tg);function Wc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=uc(),[l,d]=F(!0);return Y(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?c("div",{className:L("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:c("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),c("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),c("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[c("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!l||!s&&!i?.title&&a?null:c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),c("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&c("div",{className:"flex-shrink-0",children:c("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const Cg=nt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function kg({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:l,showRetryButton:d,clearError:h,error:u,sessionId:p,activeElicitation:_,isAuthComponent:f,isConnected:g,inConversation:b,isFirstMessage:m,isEmptyChat:E,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:x,sendMessageFeedback:T,clearElicitationState:C,handleRetry:S,scrollToBottom:v,chatComposerProps:N,isComposerDisabled:P,voiceAgentState:B,isMuted:G,isVoiceAgentActive:he,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:Ee,handleClose:V,isSessionDrawerOpen:le,pastSessions:Re,isLoadingPastSessions:te,openSessionDrawer:Q,closeSessionDrawer:I,userLevel:W,isSidebarCollapsed:re,toggleSidebar:ve,feedbackModalProps:K,consentModalProps:Ae,handleChatSendMessage:He,handleEmptyStateSendMessage:ae,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:xt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie}=$p({isOpen:e,agentId:t,config:n});Y(()=>{x.length||v("auto")},[x.length,v]);const we=ie(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=ie(()=>o==="full"&&W==="user"?c(cc,{variant:"sidebar",sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:ve,isLoading:te}):void 0,[o,W,Re,p,Pe,De,re,ve,te]),qe=ie(()=>({onRetry:S,showRetryButton:d,startNewConnection:l,clearError:h,error:u,isConnected:g}),[S,d,l,h,u,g]),Ue=ie(()=>({onClose:V,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:De,showStartNewChatButton:l,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:Q}),[V,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,l,n.resize,r,Q]),Et=ie(()=>c(cc,{variant:"drawer",isOpen:le,onClose:I,sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:te}),[le,I,Re,p,Pe,De,te]);return c(Um,{enabled:!!n.resize,children:c(oc,{value:Ue,children:c(ac,{isOpen:e,feedbackModal:K,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:xt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie,theme:n.theme,isAuthComponent:f,activeElicitation:_,voiceAgentState:B,chatComposer:N,sessionDrawer:Et,sidebar:Le,fullScreenEmptyState:E?ht=>c(yp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ae,disabled:P,composer:ht.composer,composerFooter:ht.composerFooter,connectionBanner:c(Wc,{...qe})}):void 0,children:he?c(Xe,{fallback:c(Kc,{}),children:c(Cg,{state:B,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:Ee,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):c(Xe,{fallback:c(Kc,{}),children:c("div",{className:L("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[c("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:c(dl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[c("div",{className:"flex-1"}),c("div",{className:L("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?c(wm,{}):c(me,{children:[m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:we}),c(xg,{messages:x,onSendMessage:He,onToggleFeedback:T,onClearElicitationState:C,isAuthComponent:f,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),c("div",{ref:s})]})]})}),a&&c("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:c(Se,{onClick:()=>v("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:c(Wo,{className:"w-5 h-5 text-text-primary"})})}),c(Wc,{className:"mt-2",...qe})]})})})})})}function Kc(){return c("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[c("div",{className:"flex-1 p-6 space-y-4",children:[c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),c("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function qc(e){return!!e&&e.startsWith("ResizeObserver loop")}function ws(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 ct{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:ws(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?c(Ig,{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 Rg({error:e}){throw e}function Ag(e){const[t,n]=F(null);return Y(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||qc(i?.message)||qc(i?.error?.message)||(i?.error?n(ws(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(ws(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),c(Og,{...e,children:t?c(Rg,{error:t}):e.children})}function Ig({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:l}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ie(()=>l?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[l?.textColor]),_=ie(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return c(oc,{value:_,children:c(ac,{isOpen:!0,environment:u,mode:a??"widget",theme:l,children:c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:c("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:c("div",{className:"w-full max-w-[320px] text-center",children:[c("div",{className:"mx-auto mb-4 grid place-items-center",children:c("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:c(zh,{className:"h-8 w-8",style:{color:l?.primary??"hsl(var(--primary))"}})})}),c("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),c("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),c("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",p].join(" "),children:e?.message||String(e)}),c("div",{className:"mt-5 flex items-center justify-center gap-3",children:c(Se,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:l?.primary??void 0},children:[c(Lh,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function Mg({agentId:e,config:t}){const[n,r]=F(t.displayMode==="full");Y(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return c(Ag,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:c(rm,{children:c(kg,{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 Xc=(e,t,n)=>{const r=n||{},o=wd(e);return o.render(c(me,{children:c(Mg,{agentId:t,config:r})})),o},Pg=e=>{try{const t=sessionStorage.getItem(ur(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Zc=e=>{const{refreshToken:t,sessToken:n}=Pg(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Jc=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Xc,window.fetchAgentConfig=Jc,window.prefetchAuth=Zc);export{X as A,Se as B,Wo as C,ee as D,El as F,yl as I,Ko as M,Xt as N,pn as P,Oo as R,cs as S,ie as T,Tn as X,ft as _,M as a,L as b,Ye as c,F as d,me as e,Zt as f,Jc as fetchAgentConfig,bi as g,fn as h,Vt as i,zt as j,vp as k,Cl as l,ss as m,ql as n,is as o,bp as p,Zc as prefetchAuth,de as q,Ol as r,Xc as renderMedAssist,Zr as s,mc as t,c as u,en as v,wp as w,kl as x,Y as y,Rl as z};
|