@evelan/jexity-widget 0.11.7 → 0.11.9

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/widget.js CHANGED
@@ -1,8 +1,16 @@
1
- (function(){"use strict";var ze,b,Fn,Qn,de,Dn,Un,Vn,Hn,Ot,Nt,zt,Wn,Be={},Jn=[],ho=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Fe=Array.isArray;function Z(t,e){for(var n in e)t[n]=e[n];return t}function Bt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Q(t,e,n){var r,i,o,s={};for(o in e)o=="key"?r=e[o]:o=="ref"?i=e[o]:s[o]=e[o];if(arguments.length>2&&(s.children=arguments.length>3?ze.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return Qe(t,s,r,i,null)}function Qe(t,e,n,r,i){var o={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Fn,__i:-1,__u:0};return i==null&&b.vnode!=null&&b.vnode(o),o}function fo(){return{current:null}}function B(t){return t.children}function H(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Gn(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Gn(t)}}function Ft(t){(!t.__d&&(t.__d=!0)&&de.push(t)&&!ut.__r++||Dn!=b.debounceRendering)&&((Dn=b.debounceRendering)||Un)(ut)}function ut(){for(var t,e,n,r,i,o,s,l=1;de.length;)de.length>l&&de.sort(Vn),t=de.shift(),l=de.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,o=[],s=[],e.__P&&((n=Z({},r)).__v=r.__v+1,b.vnode&&b.vnode(n),Qt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,o,i??we(r),!!(32&r.__u),s),n.__v=r.__v,n.__.__k[n.__i]=n,er(o,n,s),r.__e=r.__=null,n.__e!=i&&Gn(n)));ut.__r=0}function Kn(t,e,n,r,i,o,s,l,a,u,d){var h,f,p,g,m,x,v,y=r&&r.__k||Jn,L=e.length;for(a=po(n,e,y,a,L),h=0;h<L;h++)(p=n.__k[h])!=null&&(f=p.__i==-1?Be:y[p.__i]||Be,p.__i=h,x=Qt(t,p,f,i,o,s,l,a,u,d),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&Ut(f.ref,null,p),d.push(p.ref,p.__c||g,p)),m==null&&g!=null&&(m=g),(v=!!(4&p.__u))||f.__k===p.__k?a=Zn(p,a,t,v):typeof p.type=="function"&&x!==void 0?a=x:g&&(a=g.nextSibling),p.__u&=-7);return n.__e=m,a}function po(t,e,n,r,i){var o,s,l,a,u,d=n.length,h=d,f=0;for(t.__k=new Array(i),o=0;o<i;o++)(s=e[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=o+f,(s=t.__k[o]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?Qe(null,s,null,null,null):Fe(s)?Qe(B,{children:s},null,null,null):s.constructor==null&&s.__b>0?Qe(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,l=null,(u=s.__i=go(s,n,a,h))!=-1&&(h--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?f--:i<d&&f++),typeof s.type!="function"&&(s.__u|=4)):u!=a&&(u==a-1?f--:u==a+1?f++:(u>a?f--:f++,s.__u|=4))):t.__k[o]=null;if(h)for(o=0;o<d;o++)(l=n[o])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=we(l)),nr(l,l));return r}function Zn(t,e,n,r){var i,o;if(typeof t.type=="function"){for(i=t.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=t,e=Zn(i[o],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Y(t,e){return e=e||[],t==null||typeof t=="boolean"||(Fe(t)?t.some(function(n){Y(n,e)}):e.push(t)),e}function go(t,e,n,r){var i,o,s,l=t.key,a=t.type,u=e[n],d=u!=null&&(2&u.__u)==0;if(u===null&&t.key==null||d&&l==u.key&&a==u.type)return n;if(r>(d?1:0)){for(i=n-1,o=n+1;i>=0||o<e.length;)if((u=e[s=i>=0?i--:o++])!=null&&(2&u.__u)==0&&l==u.key&&a==u.type)return s}return-1}function Yn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||ho.test(e)?n:n+"px"}function ht(t,e,n,r,i){var o,s;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof r=="string"&&(t.style.cssText=r=""),r)for(e in r)n&&e in n||Yn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Yn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Hn,"$1")),s=e.toLowerCase(),e=s in t||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?r?n.u=r.u:(n.u=Ot,t.addEventListener(e,o?zt:Nt,o)):t.removeEventListener(e,o?zt:Nt,o);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Xn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Ot++;else if(e.t<n.u)return;return n(b.event?b.event(e):e)}}}function Qt(t,e,n,r,i,o,s,l,a,u){var d,h,f,p,g,m,x,v,y,L,V,K,F,uo,qt,ct,Nn,re=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),o=[l=e.__e=n.__e]),(d=b.__b)&&d(e);e:if(typeof re=="function")try{if(v=e.props,y="prototype"in re&&re.prototype.render,L=(d=re.contextType)&&r[d.__c],V=d?L?L.props.value:d.__:r,n.__c?x=(h=e.__c=n.__c).__=h.__E:(y?e.__c=h=new re(v,V):(e.__c=h=new H(v,V),h.constructor=re,h.render=xo),L&&L.sub(h),h.props=v,h.state||(h.state={}),h.context=V,h.__n=r,f=h.__d=!0,h.__h=[],h._sb=[]),y&&h.__s==null&&(h.__s=h.state),y&&re.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=Z({},h.__s)),Z(h.__s,re.getDerivedStateFromProps(v,h.__s))),p=h.props,g=h.state,h.__v=e,f)y&&re.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),y&&h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(y&&re.getDerivedStateFromProps==null&&v!==p&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(v,V),!h.__e&&h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(v,h.__s,V)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(h.props=v,h.state=h.__s,h.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Ne){Ne&&(Ne.__=e)}),K=0;K<h._sb.length;K++)h.__h.push(h._sb[K]);h._sb=[],h.__h.length&&s.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(v,h.__s,V),y&&h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(p,g,m)})}if(h.context=V,h.props=v,h.__P=t,h.__e=!1,F=b.__r,uo=0,y){for(h.state=h.__s,h.__d=!1,F&&F(e),d=h.render(h.props,h.state,h.context),qt=0;qt<h._sb.length;qt++)h.__h.push(h._sb[qt]);h._sb=[]}else do h.__d=!1,F&&F(e),d=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++uo<25);h.state=h.__s,h.getChildContext!=null&&(r=Z(Z({},r),h.getChildContext())),y&&!f&&h.getSnapshotBeforeUpdate!=null&&(m=h.getSnapshotBeforeUpdate(p,g)),ct=d,d!=null&&d.type===B&&d.key==null&&(ct=tr(d.props.children)),l=Kn(t,Fe(ct)?ct:[ct],e,n,r,i,o,s,l,a,u),h.base=e.__e,e.__u&=-161,h.__h.length&&s.push(h),x&&(h.__E=h.__=null)}catch(Ne){if(e.__v=null,a||o!=null)if(Ne.then){for(e.__u|=a?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;o[o.indexOf(l)]=null,e.__e=l}else{for(Nn=o.length;Nn--;)Bt(o[Nn]);Dt(e)}else e.__e=n.__e,e.__k=n.__k,Ne.then||Dt(e);b.__e(Ne,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=mo(n.__e,e,n,r,i,o,s,a,u);return(d=b.diffed)&&d(e),128&e.__u?void 0:l}function Dt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Dt)}function er(t,e,n){for(var r=0;r<n.length;r++)Ut(n[r],n[++r],n[++r]);b.__c&&b.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(o){o.call(i)})}catch(o){b.__e(o,i.__v)}})}function tr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Fe(t)?t.map(tr):Z({},t)}function mo(t,e,n,r,i,o,s,l,a){var u,d,h,f,p,g,m,x=n.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(u=0;u<o.length;u++)if((p=o[u])&&"setAttribute"in p==!!y&&(y?p.localName==y:p.nodeType==3)){t=p,o[u]=null;break}}if(t==null){if(y==null)return document.createTextNode(v);t=document.createElementNS(i,y,v.is&&v),l&&(b.__m&&b.__m(e,o),l=!1),o=null}if(y==null)x===v||l&&t.data==v||(t.data=v);else{if(o=o&&ze.call(t.childNodes),x=n.props||Be,!l&&o!=null)for(x={},u=0;u<t.attributes.length;u++)x[(p=t.attributes[u]).name]=p.value;for(u in x)if(p=x[u],u!="children"){if(u=="dangerouslySetInnerHTML")h=p;else if(!(u in v)){if(u=="value"&&"defaultValue"in v||u=="checked"&&"defaultChecked"in v)continue;ht(t,u,null,p,i)}}for(u in v)p=v[u],u=="children"?f=p:u=="dangerouslySetInnerHTML"?d=p:u=="value"?g=p:u=="checked"?m=p:l&&typeof p!="function"||x[u]===p||ht(t,u,p,x[u],i);if(d)l||h&&(d.__html==h.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(h&&(t.innerHTML=""),Kn(e.type=="template"?t.content:t,Fe(f)?f:[f],e,n,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&we(n,0),l,a),o!=null)for(u=o.length;u--;)Bt(o[u]);l||(u="value",y=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[u]||y=="progress"&&!g||y=="option"&&g!=x[u])&&ht(t,u,g,x[u],i),u="checked",m!=null&&m!=t[u]&&ht(t,u,m,x[u],i))}return t}function Ut(t,e,n){try{if(typeof t=="function"){var r=typeof t.__u=="function";r&&t.__u(),r&&e==null||(t.__u=t(e))}else t.current=e}catch(i){b.__e(i,n)}}function nr(t,e,n){var r,i;if(b.unmount&&b.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Ut(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){b.__e(o,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&nr(r[i],e,n||typeof t.type!="function");n||Bt(t.__e),t.__c=t.__=t.__e=void 0}function xo(t,e,n){return this.constructor(t,n)}function fe(t,e,n){var r,i,o,s;e==document&&(e=document.documentElement),b.__&&b.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,o=[],s=[],Qt(e,t=(!r&&n||e).__k=Q(B,null,[t]),i||Be,Be,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?ze.call(e.childNodes):null,o,!r&&n?n:i?i.__e:e.firstChild,r,s),er(o,t,s)}function rr(t,e){fe(t,e,rr)}function bo(t,e,n){var r,i,o,s,l=Z({},t.props);for(o in t.type&&t.type.defaultProps&&(s=t.type.defaultProps),e)o=="key"?r=e[o]:o=="ref"?i=e[o]:l[o]=e[o]===void 0&&s!=null?s[o]:e[o];return arguments.length>2&&(l.children=arguments.length>3?ze.call(arguments,2):n),Qe(t.type,l,r||t.key,i||t.ref,null)}function yo(t){function e(n){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&r.forEach(function(s){s.__e=!0,Ft(s)})},this.sub=function(o){r.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){r&&r.delete(o),s&&s.call(o)}}),n.children}return e.__c="__cC"+Wn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}ze=Jn.slice,b={__e:function(t,e,n,r){for(var i,o,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(t)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),s=i.__d),s)return i.__E=i}catch(l){t=l}throw t}},Fn=0,Qn=function(t){return t!=null&&t.constructor==null},H.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Z({},this.state),typeof t=="function"&&(t=t(Z({},n),this.props)),t&&Z(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ft(this))},H.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ft(this))},H.prototype.render=B,de=[],Un=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Vn=function(t,e){return t.__v.__b-e.__v.__b},ut.__r=0,Hn=/(PointerCapture)$|Capture$/i,Ot=0,Nt=Xn(!1),zt=Xn(!0),Wn=0;var vo=0;function c(t,e,n,r,i,o){e||(e={});var s,l,a=e;if("ref"in a)for(l in a={},e)l=="ref"?s=e[l]:a[l]=e[l];var u={type:t,props:a,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vo,__i:-1,__u:0,__source:i,__self:o};if(typeof t=="function"&&(s=t.defaultProps))for(l in s)a[l]===void 0&&(a[l]=s[l]);return b.vnode&&b.vnode(u),u}var ae,j,Vt,ir,ke=0,or=[],S=b,sr=S.__b,ar=S.__r,lr=S.diffed,cr=S.__c,ur=S.unmount,hr=S.__;function je(t,e){S.__h&&S.__h(j,t,ke||e),ke=0;var n=j.__H||(j.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return ke=1,Ht(mr,t)}function Ht(t,e,n){var r=je(ae++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):mr(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],u=r.t(a,l);a!==u&&(r.__N=[u,r.__[1]],r.__c.setState({}))}],r.__c=j,!j.__f)){var i=function(l,a,u){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!o||o.call(this,l,a,u);var h=r.__c.props!==l;return d.forEach(function(f){if(f.__N){var p=f.__[0];f.__=f.__N,f.__N=void 0,p!==f.__[0]&&(h=!0)}}),o&&o.call(this,l,a,u)||h};j.__f=!0;var o=j.shouldComponentUpdate,s=j.componentWillUpdate;j.componentWillUpdate=function(l,a,u){if(this.__e){var d=o;o=void 0,i(l,a,u),o=d}s&&s.call(this,l,a,u)},j.shouldComponentUpdate=i}return r.__N||r.__}function T(t,e){var n=je(ae++,3);!S.__s&&Jt(n.__H,e)&&(n.__=t,n.u=e,j.__H.__h.push(n))}function De(t,e){var n=je(ae++,4);!S.__s&&Jt(n.__H,e)&&(n.__=t,n.u=e,j.__h.push(n))}function le(t){return ke=5,W(function(){return{current:t}},[])}function dr(t,e,n){ke=6,De(function(){if(typeof t=="function"){var r=t(e());return function(){t(null),r&&typeof r=="function"&&r()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function W(t,e){var n=je(ae++,7);return Jt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Se(t,e){return ke=8,W(function(){return t},e)}function dt(t){var e=j.context[t.__c],n=je(ae++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(j)),e.props.value):t.__}function fr(t,e){S.useDebugValue&&S.useDebugValue(e?e(t):t)}function pr(){var t=je(ae++,11);if(!t.__){for(var e=j.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function _o(){for(var t;t=or.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ft),t.__H.__h.forEach(Wt),t.__H.__h=[]}catch(e){t.__H.__h=[],S.__e(e,t.__v)}}S.__b=function(t){j=null,sr&&sr(t)},S.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),hr&&hr(t,e)},S.__r=function(t){ar&&ar(t),ae=0;var e=(j=t.__c).__H;e&&(Vt===j?(e.__h=[],j.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ft),e.__h.forEach(Wt),e.__h=[],ae=0)),Vt=j},S.diffed=function(t){lr&&lr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(or.push(e)!==1&&ir===S.requestAnimationFrame||((ir=S.requestAnimationFrame)||wo)(_o)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Vt=j=null},S.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ft),n.__h=n.__h.filter(function(r){return!r.__||Wt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],S.__e(r,n.__v)}}),cr&&cr(t,e)},S.unmount=function(t){ur&&ur(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{ft(r)}catch(i){e=i}}),n.__H=void 0,e&&S.__e(e,n.__v))};var gr=typeof requestAnimationFrame=="function";function wo(t){var e,n=function(){clearTimeout(r),gr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);gr&&(e=requestAnimationFrame(n))}function ft(t){var e=j,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),j=e}function Wt(t){var e=j;t.__c=t.__(),j=e}function Jt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function mr(t,e){return typeof e=="function"?e(t):e}function xr(t,e){for(var n in e)t[n]=e[n];return t}function Gt(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var r in e)if(r!=="__source"&&t[r]!==e[r])return!0;return!1}function br(t,e){var n=e(),r=C({t:{__:n,u:e}}),i=r[0].t,o=r[1];return De(function(){i.__=n,i.u=e,Kt(i)&&o({t:i})},[t,n,e]),T(function(){return Kt(i)&&o({t:i}),t(function(){Kt(i)&&o({t:i})})},[t]),n}function Kt(t){var e,n,r=t.u,i=t.__;try{var o=r();return!((e=i)===(n=o)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function yr(t){t()}function vr(t){return t}function _r(){return[!1,yr]}var wr=De;function Zt(t,e){this.props=t,this.context=e}function ko(t,e){function n(i){var o=this.props.ref,s=o==i.ref;return!s&&o&&(o.call?o(null):o.current=null),e?!e(this.props,i)||!s:Gt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,Q(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Zt.prototype=new H).isPureReactComponent=!0,Zt.prototype.shouldComponentUpdate=function(t,e){return Gt(this.props,t)||Gt(this.state,e)};var kr=b.__b;b.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),kr&&kr(t)};var jo=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function So(t){function e(n){var r=xr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=jo,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var jr=function(t,e){return t==null?null:Y(Y(t).map(e))},Co={map:jr,forEach:jr,count:function(t){return t?Y(t).length:0},only:function(t){var e=Y(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Y},To=b.__e;b.__e=function(t,e,n,r){if(t.then){for(var i,o=e;o=o.__;)if((i=o.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}To(t,e,n,r)};var Sr=b.unmount;function Cr(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),t.__c.__H=null),(t=xr({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(r){return Cr(r,e,n)})),t}function Tr(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return Tr(r,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function pt(){this.__u=0,this.o=null,this.__b=null}function Rr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Ro(t){var e,n,r;function i(o){if(e||(e=t()).then(function(s){n=s.default||s},function(s){r=s}),r)throw r;if(!n)throw e;return Q(n,o)}return i.displayName="Lazy",i.__f=!0,i}function Ue(){this.i=null,this.l=null}b.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Sr&&Sr(t)},(pt.prototype=new H).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=Rr(r.__v),o=!1,s=function(){o||(o=!0,n.__R=null,i?i(l):l())};n.__R=s;var l=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Tr(a,a.__c.__P,a.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(s,s)},pt.prototype.componentWillUnmount=function(){this.o=[]},pt.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Cr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&Q(B,null,t.fallback);return i&&(i.__u&=-33),[Q(B,null,e.__a?null:t.children),i]};var $r=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function $o(t){return this.getChildContext=function(){return t.context},t.children}function Ao(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){fe(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var r=e.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},insertBefore:function(i,o){this.childNodes.push(i),e.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}fe(Q($o,{context:e.context},t.__v),e.v)}function Eo(t,e){var n=Q(Ao,{__v:t,h:e});return n.containerInfo=e,n}(Ue.prototype=new H).__a=function(t){var e=this,n=Rr(e.__v),r=e.l.get(t);return r[0]++,function(i){var o=function(){e.props.revealOrder?(r.push(i),$r(e,t,r)):i()};n?n(o):o()}},Ue.prototype.render=function(t){this.i=null,this.l=new Map;var e=Y(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Ue.prototype.componentDidUpdate=Ue.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){$r(t,n,e)})};var Ar=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Io=/^(?: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]/,Lo=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Po=/[A-Z0-9]/g,Mo=typeof document<"u",qo=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function Oo(t,e,n){return e.__k==null&&(e.textContent=""),fe(t,e),typeof n=="function"&&n(),t?t.__c:null}function No(t,e,n){return rr(t,e),typeof n=="function"&&n(),t?t.__c:null}H.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(H.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Er=b.event;function zo(){}function Bo(){return this.cancelBubble}function Fo(){return this.defaultPrevented}b.event=function(t){return Er&&(t=Er(t)),t.persist=zo,t.isPropagationStopped=Bo,t.isDefaultPrevented=Fo,t.nativeEvent=t};var Yt,Qo={enumerable:!1,configurable:!0,get:function(){return this.class}},Ir=b.vnode;b.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},o=r.indexOf("-")===-1;for(var s in n){var l=n[s];if(!(s==="value"&&"defaultValue"in n&&l==null||Mo&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&l===!0?l="":a==="translate"&&l==="no"?l=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||qo(n.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":Lo.test(s)&&(s=a):a=s="oninput":o&&Io.test(s)?s=s.replace(Po,"-$&").toLowerCase():l===null&&(l=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=l}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=Y(n.children).forEach(function(u){u.props.selected=i.value.indexOf(u.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=Y(n.children).forEach(function(u){u.props.selected=i.multiple?i.defaultValue.indexOf(u.props.value)!=-1:i.defaultValue==u.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",Qo)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=Ar,Ir&&Ir(t)};var Lr=b.__r;b.__r=function(t){Lr&&Lr(t),Yt=t.__c};var Pr=b.diffed;b.diffed=function(t){Pr&&Pr(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Yt=null};var Do={ReactCurrentDispatcher:{current:{readContext:function(t){return Yt.__n[t.__c].props.value},useCallback:Se,useContext:dt,useDebugValue:fr,useDeferredValue:vr,useEffect:T,useId:pr,useImperativeHandle:dr,useInsertionEffect:wr,useLayoutEffect:De,useMemo:W,useReducer:Ht,useRef:le,useState:C,useSyncExternalStore:br,useTransition:_r}}};function Uo(t){return Q.bind(null,t)}function gt(t){return!!t&&t.$$typeof===Ar}function Vo(t){return gt(t)&&t.type===B}function Ho(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function Wo(t){return gt(t)?bo.apply(null,arguments):t}function Jo(t){return!!t.__k&&(fe(null,t),!0)}function Go(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var Ko=function(t,e){return t(e)},Zo=function(t,e){return t(e)},Yo=B,Xo=gt,Xt={useState:C,useId:pr,useReducer:Ht,useEffect:T,useLayoutEffect:De,useInsertionEffect:wr,useTransition:_r,useDeferredValue:vr,useSyncExternalStore:br,startTransition:yr,useRef:le,useImperativeHandle:dr,useMemo:W,useCallback:Se,useContext:dt,useDebugValue:fr,version:"18.3.1",Children:Co,render:Oo,hydrate:No,unmountComponentAtNode:Jo,createPortal:Eo,createElement:Q,createContext:yo,createFactory:Uo,cloneElement:Wo,createRef:fo,Fragment:B,isValidElement:gt,isElement:Xo,isFragment:Vo,isMemo:Ho,findDOMNode:Go,Component:H,PureComponent:Zt,memo:ko,forwardRef:So,flushSync:Zo,unstable_batchedUpdates:Ko,StrictMode:Yo,Suspense:pt,SuspenseList:Ue,lazy:Ro,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Do},X=[],D=[],es=Uint8Array,en="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ce=0,ts=en.length;Ce<ts;++Ce)X[Ce]=en[Ce],D[en.charCodeAt(Ce)]=Ce;D[45]=62,D[95]=63;function ns(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function rs(t,e,n){return(e+n)*3/4-n}function Ve(t){var e,n=ns(t),r=n[0],i=n[1],o=new es(rs(t,r,i)),s=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=D[t.charCodeAt(a)]<<18|D[t.charCodeAt(a+1)]<<12|D[t.charCodeAt(a+2)]<<6|D[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=D[t.charCodeAt(a)]<<2|D[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=D[t.charCodeAt(a)]<<10|D[t.charCodeAt(a+1)]<<4|D[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function is(t){return X[t>>18&63]+X[t>>12&63]+X[t>>6&63]+X[t&63]}function os(t,e,n){for(var r,i=[],o=e;o<n;o+=3)r=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(is(r));return i.join("")}function He(t){for(var e,n=t.length,r=n%3,i=[],o=16383,s=0,l=n-r;s<l;s+=o)i.push(os(t,s,s+o>l?l:s+o));return r===1?(e=t[n-1],i.push(X[e>>2]+X[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(X[e>>10]+X[e>>4&63]+X[e<<2&63]+"=")),i.join("")}function ie(t){if(t===void 0)return{};if(!Mr(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function ss(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function Mr(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const qr=!0,Te=BigInt("-9223372036854775808"),tn=BigInt("9223372036854775807"),nn=BigInt("0"),as=BigInt("8"),ls=BigInt("256");function Or(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function cs(t){t<nn&&(t-=Te+Te);let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new Uint8Array(new ArrayBuffer(8));let r=0;for(const i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=as;return He(n)}function us(t){const e=Ve(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=nn,r=nn;for(const i of e)n+=BigInt(i)*ls**r,r++;return n>tn&&(n+=Te+Te),n}function hs(t){if(t<Te||tn<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);const e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),He(new Uint8Array(e))}function ds(t){const e=Ve(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}const fs=DataView.prototype.setBigInt64?hs:cs,ps=DataView.prototype.getBigInt64?ds:us,Nr=1024;function zr(t){if(t.length>Nr)throw new Error(`Field name ${t} exceeds maximum field name length ${Nr}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){const n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}function Re(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Re(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);const e=Object.entries(t);if(e.length===1){const r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return Ve(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return ps(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=Ve(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,qr);if(!Or(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,i]of Object.entries(t))zr(r),n[r]=Re(i);return n}const Br=16384;function We(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Br){const n="[...truncated]";let r=Br-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function rn(t,e,n,r){if(t===void 0){const s=n&&` (present at path ${n} in original object ${We(e)})`;throw new Error(`undefined is not a valid Convex value${s}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<Te||tn<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:fs(t)}}if(typeof t=="number")if(Or(t)){const s=new ArrayBuffer(8);return new DataView(s).setFloat64(0,t,qr),{$float:He(new Uint8Array(s))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:He(new Uint8Array(t))};if(Array.isArray(t))return t.map((s,l)=>rn(s,e,n+`[${l}]`));if(t instanceof Set)throw new Error(on(n,"Set",[...t],e));if(t instanceof Map)throw new Error(on(n,"Map",[...t],e));if(!Mr(t)){const s=t?.constructor?.name,l=s?`${s} `:"";throw new Error(on(n,l,t,e))}const i={},o=Object.entries(t);o.sort(([s,l],[a,u])=>s===a?0:s<a?-1:1);for(const[s,l]of o)l!==void 0&&(zr(s),i[s]=rn(l,e,n+`.${s}`));return i}function on(t,e,n,r){return t?`${e}${We(n)} is not a supported Convex type (present at path ${t} in original object ${We(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${We(n)} is not a supported Convex type.`}function ee(t){return rn(t,t,"")}var gs=Object.defineProperty,ms=(t,e,n)=>e in t?gs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sn=(t,e,n)=>ms(t,typeof e!="symbol"?e+"":e,n),Fr,Qr;const xs=Symbol.for("ConvexError");class mt extends(Qr=Error,Fr=xs,Qr){constructor(e){super(typeof e=="string"?e:We(e)),sn(this,"name","ConvexError"),sn(this,"data"),sn(this,Fr,!0),this.data=e}}const Dr=()=>Array.from({length:4},()=>0);Dr(),Dr();const Ur="1.39.1";var bs=Object.defineProperty,ys=(t,e,n)=>e in t?bs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vr=(t,e,n)=>ys(t,typeof e!="symbol"?e+"":e,n);const vs="color:rgb(0, 145, 255)";function Hr(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Wr{constructor(e){Vr(this,"_onLogLineFuncs"),Vr(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(const n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(const n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(const n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(const n of Object.values(this._onLogLineFuncs))n("error",...e)}}function Jr(t){const e=new Wr(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}function Gr(t){return new Wr(t)}function xt(t,e,n,r,i){const o=Hr(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const s=i.match(/^\[.*?\] /);if(s===null){t.error(`[CONVEX ${o}(${r})] Could not parse console.log`);return}const l=i.slice(1,s[0].length-2),a=i.slice(s[0].length);t.log(`%c[CONVEX ${o}(${r})] [${l}]`,vs,a)}else t.error(`[CONVEX ${o}(${r})] ${i}`)}function _s(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function $e(t,e,n){return`[CONVEX ${Hr(t)}(${e})] ${n.errorMessage}
2
- Called by client`}function an(t,e){return e.data=t.errorData,e}function pe(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function ge(t,e){return JSON.stringify({udfPath:pe(t),args:ee(e)})}function Kr(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:pe(t),args:ee(e),options:ee({initialNumItems:r,id:i})})}var ws=Object.defineProperty,ks=(t,e,n)=>e in t?ws(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,te=(t,e,n)=>ks(t,typeof e!="symbol"?e+"":e,n);class js{constructor(){te(this,"nextQueryId"),te(this,"querySetVersion"),te(this,"querySet"),te(this,"queryIdToToken"),te(this,"identityVersion"),te(this,"auth"),te(this,"outstandingQueriesOlderThanRestart"),te(this,"outstandingAuthOlderThanRestart"),te(this,"paused"),te(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const o=pe(e),s=ge(o,n),l=this.querySet.get(s);if(l!==void 0)return l.numSubscribers+=1,{queryToken:s,modification:null,unsubscribe:()=>this.removeSubscriber(s)};{const a=this.nextQueryId++,u={id:a,canonicalizedUdfPath:o,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(s,u),this.queryIdToToken.set(a,s);const d=this.querySetVersion,h=this.querySetVersion+1,f={type:"Add",queryId:a,udfPath:o,args:[ee(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,f):this.querySetVersion=h,{queryToken:s,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:h,modifications:[f]},unsubscribe:()=>this.removeSubscriber(s)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=pe(e),i=ge(r,n),o=this.querySet.get(i);return o!==void 0?o.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const e=[];for(const i of this.querySet.values()){const o={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[ee(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(o),this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const n={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[n,void 0];this.outstandingAuthOlderThanRestart=!0;const r={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[n,r]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,o={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,o):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[o]}}}}var Ss=Object.defineProperty,Cs=(t,e,n)=>e in t?Ss(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,bt=(t,e,n)=>Cs(t,typeof e!="symbol"?e+"":e,n);class Ts{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,bt(this,"inflightRequests"),bt(this,"requestsOlderThanRestart"),bt(this,"inflightMutationsCount",0),bt(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const o=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:o,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const a of e.logLines)xt(this.logger,"info",r,i,a);const o=n.status;let s,l;if(e.success)s={success:!0,logLines:e.logLines,value:Re(e.result)},l=()=>o.onResult(s);else{const a=e.result,{errorData:u}=e;xt(this.logger,"error",r,i,a),s={success:!1,errorMessage:a,errorData:u!==void 0?Re(u):void 0,logLines:e.logLines},l=()=>o.onResult(s)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:s}):(n.status={status:"Completed",result:s,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const o=i.status;o.status==="Completed"&&o.ts.lessThanOrEqual(e)&&(o.onResolve(),n.set(r,o.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Je=Symbol.for("functionName"),Zr=Symbol.for("toReferencePath");function Rs(t){return t[Zr]??null}function $s(t){return t.startsWith("function://")}function As(t){let e;if(typeof t=="string")$s(t)?e={functionHandle:t}:e={name:t};else if(t[Je])e={name:t[Je]};else{const n=Rs(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function q(t){const e=As(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Je];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Yr(t){return{[Je]:t}}function Xr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Xr(i)}else if(r===Je){if(t.length<2){const s=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${s}\``)}const i=t.slice(0,-1).join("/"),o=t[t.length-1];return o==="default"?i:i+":"+o}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Es=Xr();var Is=Object.defineProperty,Ls=(t,e,n)=>e in t?Is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,yt=(t,e,n)=>Ls(t,typeof e!="symbol"?e+"":e,n);class Ge{constructor(e){yt(this,"queryResults"),yt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=ie(n[0]),i=q(e),o=this.queryResults.get(ge(i,r));if(o!==void 0)return Ge.queryValue(o.result)}getAllQueries(e){const n=[],r=q(e);for(const i of this.queryResults.values())i.udfPath===pe(r)&&n.push({args:i.args,value:Ge.queryValue(i.result)});return n}setQuery(e,n,r){const i=ie(n),o=q(e),s=ge(o,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:o,args:i,result:l};this.queryResults.set(s,a),this.modifiedQueries.push(s)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class Ps{constructor(){yt(this,"queryResults"),yt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(s=>!n.has(s.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Ge(this.queryResults);for(const s of this.optimisticUpdates)s.update(i);const o=[];for(const[s,l]of this.queryResults){const a=r.get(s);(a===void 0||a.result!==l.result)&&o.push(s)}return o}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Ge(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){const n=this.queryResults.get(e);if(n!==void 0)return n.result}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?an(r,new mt($e("query",n.udfPath,r))):new Error($e("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var Ms=Object.defineProperty,qs=(t,e,n)=>e in t?Ms(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ln=(t,e,n)=>qs(t,typeof e!="symbol"?e+"":e,n);class O{constructor(e,n){ln(this,"low"),ln(this,"high"),ln(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new O(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?ei:e>=Os?Ns:new O(e%Ke|0,e/Ke|0)}toString(){return(BigInt(this.high)*BigInt(Ke)+BigInt(this.low)).toString()}equals(e){return O.isLong(e)||(e=O.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return O.isLong(e)||(e=O.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?O.fromNumber(e):new O(e.low,e.high)}}const ei=new O(0,0),ti=65536,Ke=ti*ti,Os=Ke*Ke,Ns=new O(-1,-1);var zs=Object.defineProperty,Bs=(t,e,n)=>e in t?zs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vt=(t,e,n)=>Bs(t,typeof e!="symbol"?e+"":e,n);class ni{constructor(e,n){vt(this,"version"),vt(this,"remoteQuerySet"),vt(this,"queryPath"),vt(this,"logger"),this.version={querySet:0,ts:O.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)xt(this.logger,"info","query",i,s);const o=Re(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:o,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)xt(this.logger,"info","query",i,s);const{errorData:o}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:o!==void 0?Re(o):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function cn(t){const e=Ve(t);return O.fromBytesLE(Array.from(e))}function Fs(t){const e=new Uint8Array(t.toBytesLE());return He(e)}function ri(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:cn(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:cn(t.startVersion.ts)},endVersion:{...t.endVersion,ts:cn(t.endVersion.ts)}}}}function Qs(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:Fs(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var Ds=Object.defineProperty,Us=(t,e,n)=>e in t?Ds(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,R=(t,e,n)=>Us(t,typeof e!="symbol"?e+"":e,n);const Vs=1e3,Hs=1001,Ws=1005,Js=4040;let _t;function Ae(){return _t===void 0&&(_t=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(_t+performance.now())}function ii(){return`t=${Math.round((Ae()-_t)/100)/10}s`}const oi={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Gs(t){if(t===void 0)return"Unknown";for(const e of Object.keys(oi))if(t.startsWith(e))return e;return"Unknown"}class Ks{constructor(e,n,r,i,o,s){this.markConnectionStateDirty=o,this.debug=s,R(this,"socket"),R(this,"connectionCount"),R(this,"_hasEverConnected",!1),R(this,"lastCloseReason"),R(this,"transitionChunkBuffer",null),R(this,"defaultInitialBackoff"),R(this,"maxBackoff"),R(this,"retries"),R(this,"serverInactivityThreshold"),R(this,"reconnectDueToServerInactivityTimeout"),R(this,"scheduledReconnect",null),R(this,"networkOnlineHandler",null),R(this,"pendingNetworkRecoveryInfo",null),R(this,"uri"),R(this,"onOpen"),R(this,"onResume"),R(this,"onMessage"),R(this,"webSocketConstructor"),R(this,"logger"),R(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=ri(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Ae()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",ii(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",ii())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){const{timeSavedMs:n}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:n}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(n/1e3)}s of waiting`)}},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let i=ri(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const s=this.assembleTransition(i);if(!s)return;i=s,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==Vs&&n.code!==Hs&&n.code!==Ws&&n.code!==Js){let i=`WebSocket closed with code ${n.code}`;n.reason&&(i+=`: ${n.reason}`),this.logger.log(i),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(i)}const r=Gs(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=Qs(e),i=JSON.stringify(r);let o=!1;try{this.socket.ws.send(i),o=!0}catch(s){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${s}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${o?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=Ae(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},n);this.scheduledReconnect={timeout:i,scheduledAt:r,backoffMs:n}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){const n=Ae()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-n),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(n)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=e!==null?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Ae()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:oi[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),o=i*(Math.random()-.5);return i+o}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=Ae()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,o=`${Math.round(n/1e4)/100}MB`,s=n/(r/1e3),l=`${Math.round(s/1e4)/100}MB per second`;this._logVerbose(`received ${o} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${o}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${o} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function Zs(){return Ys()}function Ys(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class Ze extends Error{}Ze.prototype.name="InvalidTokenError";function Xs(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function ea(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Xs(e)}catch{return atob(e)}}function si(t,e){if(typeof t!="string")throw new Ze("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new Ze(`Invalid token specified: missing part #${n+1}`);let i;try{i=ea(r)}catch(o){throw new Ze(`Invalid token specified: invalid base64 for part #${n+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Ze(`Invalid token specified: invalid json for part #${n+1} (${o.message})`)}}var ta=Object.defineProperty,na=(t,e,n)=>e in t?ta(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,U=(t,e,n)=>na(t,typeof e!="symbol"?e+"":e,n);const ra=480*60*60*1e3,ai=2;class ia{constructor(e,n,r){U(this,"authState",{state:"noAuth"}),U(this,"configVersion",0),U(this,"syncState"),U(this,"authenticate"),U(this,"stopSocket"),U(this,"tryRestartSocket"),U(this,"pauseSocket"),U(this,"resumeSocket"),U(this,"clearAuth"),U(this,"logger"),U(this,"refreshTokenLeewaySeconds"),U(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=ai){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${ai-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const o=i-r;if(o<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let s=Math.min(ra,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},s);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return si(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const oa=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function sa(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function aa(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function la(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of oa){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(aa)}var ca=Object.defineProperty,ua=(t,e,n)=>e in t?ca(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$=(t,e,n)=>ua(t,typeof e!="symbol"?e+"":e,n);class ha{constructor(e,n,r){if($(this,"address"),$(this,"state"),$(this,"requestManager"),$(this,"webSocketManager"),$(this,"authenticationManager"),$(this,"remoteQuerySet"),$(this,"optimisticQueryResults"),$(this,"_transitionHandlerCounter",0),$(this,"_nextRequestId"),$(this,"_onTransitionFns",new Map),$(this,"_sessionId"),$(this,"firstMessageReceived",!1),$(this,"debug"),$(this,"logger"),$(this,"maxObservedTimestamp"),$(this,"connectionStateSubscribers",new Map),$(this,"nextConnectionStateSubscriberId",0),$(this,"_lastPublishedConnectionState"),$(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const p=this.connectionState();if(JSON.stringify(p)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=p;for(const g of this.connectionStateSubscribers.values())g(p)}})}),$(this,"mark",p=>{this.debug&&sa(p,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&ss(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let o=r.webSocketConstructor;if(!o&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");o=o||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Gr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Jr({verbose:r.verbose??!1});const s=e.search("://");if(s===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(s+3),a=e.substring(0,s);let u;if(a==="http")u="ws";else if(a==="https")u="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${u}://${l}/api/${Ur}/sync`;this.state=new js,this.remoteQuerySet=new ni(p=>this.state.queryPath(p),this.logger),this.requestManager=new Ts(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ia(this.state,{authenticate:p=>{const g=this.state.setAuth(p);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new Ps,this.addOnTransitionHandler(p=>{n(p.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=Zs();const{unsavedChangesWarning:f}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(f===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else f!==!1&&window.addEventListener("beforeunload",p=>{if(this.requestManager.hasIncompleteRequests()){p.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(p||window.event).returnValue=g,g}});this.webSocketManager=new Ks(d,{onOpen:p=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...p,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new ni(x=>this.state.queryPath(x),this.logger);const[g,m]=this.state.restart();m&&this.webSocketManager.sendMessage(m),this.webSocketManager.sendMessage(g);for(const x of this.requestManager.restart())this.webSocketManager.sendMessage(x)},onResume:()=>{const[p,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),p&&this.webSocketManager.sendMessage(p);for(const m of this.requestManager.resume())this.webSocketManager.sendMessage(m)},onMessage:p=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),p.type){case"Transition":{this.observedTimestamp(p.endVersion.ts),this.authenticationManager.onTransition(p),this.remoteQuerySet.transition(p),this.state.transition(p);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{p.success&&this.observedTimestamp(p.ts);const g=this.requestManager.onResponse(p);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(p);break}case"AuthError":{this.authenticationManager.onAuthError(p);break}case"FatalError":{const g=_s(this.logger,p.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},o,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[o,s]of n){const l=this.state.queryToken(o);if(l!==null){const a={result:s,udfPath:this.state.queryPath(o),args:this.state.queryArgs(o)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(o=>{const s=this.optimisticQueryResults.rawQueryResult(o);return{token:o,modification:{kind:"Updated",result:s}}}),reflectedMutations:Array.from(e).map(([o,s])=>({requestId:o,result:s})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?si(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const i=ie(n),{modification:o,queryToken:s,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return o!==null&&this.webSocketManager.sendMessage(o),{queryToken:s,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=ie(n),i=ge(e,r);return this.optimisticQueryResults.queryResult(i)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=ie(n),i=ge(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=ie(n),i=ge(e,r);return this.state.queryJournal(i)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const i=await this.mutationInternal(e,n,r);if(!i.success)throw i.errorData!==void 0?an(i,new mt($e("mutation",e,i))):new Error($e("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:o}=this.enqueueMutation(e,n,r,i);return o}enqueueMutation(e,n,r,i){const o=ie(n);this.tryReportLongDisconnect();const s=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const h=g=>{d(g,o)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},p=this.optimisticQueryResults.applyOptimisticUpdate(h,s).map(g=>{const m=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:m===void 0?void 0:{success:!0,value:m,logLines:[]}}}});this.handleTransition({queries:p,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:s,udfPath:e,componentPath:i,args:[ee(o)]},a=this.webSocketManager.sendMessage(l),u=this.requestManager.request(l,a);return{requestId:s,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?an(r,new mt($e("action",e,r))):new Error($e("action",e,r));return r.value}async actionInternal(e,n,r){const i=ie(n),o=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const s={type:"Action",requestId:o,udfPath:e,componentPath:r,args:[ee(i)]},l=this.webSocketManager.sendMessage(s);return this.requestManager.request(s,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=la(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${Ur}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function un(t){if(typeof t!="object"||t===null||!Array.isArray(t.page)||typeof t.isDone!="boolean"||typeof t.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${t?.toString()}`);return t}var da=Object.defineProperty,fa=(t,e,n)=>e in t?da(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,li=(t,e,n)=>fa(t,typeof e!="symbol"?e+"":e,n);class pa{constructor(e,n){this.client=e,this.onTransition=n,li(this,"paginatedQuerySet",new Map),li(this,"lastTransitionTs"),this.lastTransitionTs=O.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=pe(e),o=Kr(i,n,r),s=()=>this.removePaginatedQuerySubscriber(o),l=this.paginatedQuerySet.get(o);return l?(l.numSubscribers+=1,{paginatedQueryToken:o,unsubscribe:s}):(this.paginatedQuerySet.set(o,{token:o,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(o,null,r.initialNumItems),{paginatedQueryToken:o,unsubscribe:s})}localQueryResult(e,n,r){const i=pe(e),o=Kr(i,n,r);return this.localQueryResultByToken(o)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)};let i=[],o=!1,s=!1;for(const a of r){const u=this.client.localQueryResultByToken(a);if(u===void 0){o=!0,s=!1;continue}const d=un(u);i=i.concat(d.page),s=!!d.isDone}let l;return o?l=i.length===0?"LoadingFirstPage":"LoadingMore":s?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(s=>s.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,s=>this.client.localQueryResultByToken(s)),i=r.map(s=>({token:s,modification:{kind:"Updated",result:this.localQueryResultByToken(s)}})));const o={...e,paginatedQueries:i};this.onTransition(o)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const o=un(i);if(o.isDone)return!1;this.addPageToPaginatedQuery(e,o.continueCursor,n);const s={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(s),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,o]of this.paginatedQuerySet)for(const s of this.allQueryTokens(o))if(r.has(s)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:o,pageKeyToQuery:s,pageKeys:l}=i;for(const[a,[u,d]]of o)n(s.get(u).queryToken)!==void 0&&n(s.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,u,d);for(const a of l){if(o.has(a))continue;const u=s.get(a).queryToken,d=n(u);if(!d)continue;const h=un(d);h.splitCursor&&(h.pageStatus==="SplitRecommended"||h.pageStatus==="SplitRequired"||h.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const o=e.nextPageKey++,s=e.nextPageKey++,l={cursor:i,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:null,endCursor:r}});e.pageKeyToQuery.set(o,a);const u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(s,u),e.ongoingSplits.set(n,[o,s])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),o=i.nextPageKey++,s={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:s},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(o),i.pageKeyToQuery.set(o,a),a}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const o=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const s=e.pageKeys.indexOf(n);e.pageKeys.splice(s,1,r,i),e.ongoingSplits.delete(n),o.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function ga({getCurrentValue:t,subscribe:e}){const[n,r]=C(()=>({getCurrentValue:t,subscribe:e,value:t()}));let i=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(i=t(),r({getCurrentValue:t,subscribe:e,value:i})),T(()=>{let o=!1;const s=()=>{o||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const u=t();return a.value===u?a:{...a,value:u}})},l=e(s);return s(),()=>{o=!0,l()}},[t,e]),i}var ma=Object.defineProperty,xa=(t,e,n)=>e in t?ma(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>xa(t,typeof e!="symbol"?e+"":e,n);const ba=5e3;if(typeof Xt>"u")throw new Error("Required dependency 'react' not found");function ci(t,e,n){function r(i){return wa(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(o){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${q(t)}`);return ci(t,e,o)},r}class ya{constructor(e,n){if(oe(this,"address"),oe(this,"cachedSync"),oe(this,"cachedPaginatedQueryClient"),oe(this,"listeners"),oe(this,"options"),oe(this,"closed",!1),oe(this,"_logger"),oe(this,"adminAuth"),oe(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?Gr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Jr({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new ha(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new pa(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,o=q(e);return{onUpdate:s=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(o,r,i),u=this.listeners.get(l);return u!==void 0?u.add(s):this.listeners.set(l,new Set([s])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(s),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(o,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(o,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(o,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??ba,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=q(e);return{onUpdate:o=>{const{paginatedQueryToken:s,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(s);return a!==void 0?a.add(o):this.listeners.set(s,new Set([o])),()=>{if(this.closed)return;const u=this.listeners.get(s);u.delete(o),u.size===0&&this.listeners.delete(s),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,o=q(e);return this.sync.mutation(o,r,i)}action(e,...n){const r=q(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((o,s)=>{const l=r.onUpdate(()=>{l();try{o(r.localQueryResult())}catch(a){s(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){const n=e.queries.map(i=>i.token),r=e.paginatedQueries.map(i=>i.token);this.transition([...n,...r])}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const i of r)i()}}}const hn=Xt.createContext(void 0);function va(){return dt(hn)}const _a=({client:t,children:e})=>Xt.createElement(hn.Provider,{value:t},e);function ui(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:ie(e[0]),i=typeof t=="string"?Yr(t):t,o=q(i),s=W(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(ee(r)),o,n]),a=Ca(s).query;if(a instanceof Error)throw a;return a}function wt(t){const e=typeof t=="string"?Yr(t):t,n=dt(hn);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return W(()=>ci(e,n),[n,q(e)])}function wa(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var ka=Object.defineProperty,ja=(t,e,n)=>e in t?ka(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>ja(t,typeof e!="symbol"?e+"":e,n);class Sa{constructor(e){dn(this,"createWatch"),dn(this,"queries"),dn(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:o}=e[n];if(q(r),this.queries[n]===void 0)this.addQuery(n,r,i,o?{paginationOptions:o}:{});else{const s=this.queries[n];(q(r)!==q(s.query)||JSON.stringify(ee(i))!==JSON.stringify(ee(s.args))||JSON.stringify(o)!==JSON.stringify(s.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,o?{paginationOptions:o}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:o}=e[r],s=e[r].paginationOptions;q(i);const l=this.createWatch(i,o,s?{paginationOptions:s}:{});let a;try{a=l.localQueryResult()}catch(u){if(u instanceof Error)a=u;else throw u}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:o,paginationOptions:s}=this.queries[n],l="journal"in o?o.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...s?{paginationOptions:s}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:o}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const s=this.createWatch(n,r,{...o?{journal:o}:[],...i?{paginationOptions:i}:{}}),l=s.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:s,unsubscribe:l,...i?{paginationOptions:i}:{}}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function Ca(t){const e=va();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=W(()=>(r,i,{journal:o,paginationOptions:s})=>s?e.watchPaginatedQuery(r,i,s):e.watchQuery(r,i,o?{journal:o}:{}),[e]);return Ta(t,n)}function Ta(t,e){const[n]=C(()=>new Sa(e));n.createWatch!==e&&n.setCreateWatch(e),T(()=>()=>n.destroy(),[n]);const r=W(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return ga(r)}var Ra=Symbol.for("preact-signals");function kt(){if(ce>1)ce--;else{for(var t,e=!1;Ye!==void 0;){var n=Ye;for(Ye=void 0,fn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&fi(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(fn=0,ce--,e)throw t}}function $a(t){if(ce>0)return t();ce++;try{return t()}finally{kt()}}var w=void 0;function hi(t){var e=w;w=void 0;try{return t()}finally{w=e}}var Ye=void 0,ce=0,fn=0,jt=0;function di(t){if(w!==void 0){var e=t.n;if(e===void 0||e.t!==w)return e={i:0,S:t,p:w.s,n:void 0,t:w,e:void 0,x:void 0,r:e},w.s!==void 0&&(w.s.n=e),w.s=e,t.n=e,32&w.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=w.s,e.n=void 0,w.s.n=e,w.s=e),e}}function P(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}P.prototype.brand=Ra,P.prototype.h=function(){return!0},P.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:hi(function(){var r;(r=e.W)==null||r.call(e)}))},P.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&hi(function(){var i;(i=e.Z)==null||i.call(e)}))}},P.prototype.subscribe=function(t){var e=this;return Xe(function(){var n=e.value,r=w;w=void 0;try{t(n)}finally{w=r}},{name:"sub"})},P.prototype.valueOf=function(){return this.value},P.prototype.toString=function(){return this.value+""},P.prototype.toJSON=function(){return this.value},P.prototype.peek=function(){var t=w;w=void 0;try{return this.value}finally{w=t}},Object.defineProperty(P.prototype,"value",{get:function(){var t=di(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(fn>100)throw new Error("Cycle detected");this.v=t,this.i++,jt++,ce++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{kt()}}}});function A(t,e){return new P(t,e)}function fi(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function pi(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function gi(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function me(t,e){P.call(this,void 0),this.x=t,this.s=void 0,this.g=jt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}me.prototype=new P,me.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===jt))return!0;if(this.g=jt,this.f|=1,this.i>0&&!fi(this))return this.f&=-2,!0;var t=w;try{pi(this),w=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return w=t,gi(this),this.f&=-2,!0},me.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}P.prototype.S.call(this,t)},me.prototype.U=function(t){if(this.t!==void 0&&(P.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},me.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(me.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=di(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function pn(t,e){return new me(t,e)}function mi(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ce++;var n=w;w=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,gn(t),r}finally{w=n,kt()}}}function gn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,mi(t)}function Aa(t){if(w!==this)throw new Error("Out-of-order effect");gi(this),w=t,this.f&=-2,8&this.f&&gn(this),kt()}function Ee(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ee.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ee.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,mi(this),pi(this),ce++;var t=w;return w=this,Aa.bind(this,t)},Ee.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ye,Ye=this)},Ee.prototype.d=function(){this.f|=8,1&this.f||gn(this)},Ee.prototype.dispose=function(){this.d()};function Xe(t,e){var n=new Ee(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var xi,St,Ea=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bi=[];Xe(function(){xi=this.N})();function Ie(t,e){b[t]=e.bind(null,b[t]||function(){})}function Ct(t){if(St){var e=St;St=void 0,e()}St=t&&t.S()}function yi(t){var e=this,n=t.data,r=et(n);r.value=n;var i=W(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var u=pn(function(){var p=r.value.value;return p===0?0:p===!0?"":p||""}),d=pn(function(){return!Array.isArray(u.value)&&!Qn(u.value)}),h=Xe(function(){if(this.N=vi,d.value){var p=u.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=p)}}),f=e.__$u.d;return e.__$u.d=function(){h(),f.call(this)},[d,u]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}yi.displayName="ReactiveTextNode",Object.defineProperties(P.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:yi},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Ie("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof P&&(n||(e.__np=n={}),n[i]=o,r[i]=o.peek())}}t(e)}),Ie("__r",function(t,e){if(t(e),e.type!==B){Ct();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Xe(function(){s=this},{name:o}),s.c=i,s})(function(){var i;Ea&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Ct(n)}}),Ie("__e",function(t,e,n,r){Ct(),t(e,n,r)}),Ie("diffed",function(t,e){Ct();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var o=n.U;if(o)for(var s in o){var l=o[s];l!==void 0&&!(s in r)&&(l.d(),o[s]=void 0)}else o={},n.U=o;for(var a in r){var u=o[a],d=r[a];u===void 0?(u=Ia(n,a,d,i),o[a]=u):u.o(d,i)}}}t(e)});function Ia(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,o=A(n);return{o:function(s,l){o.value=s,r=l},d:Xe(function(){this.N=vi;var s=o.value.value;r[e]!==s&&(r[e]=s,i?t[e]=s:s!=null&&(s!==!1||e[4]==="-")?t.setAttribute(e,s):t.removeAttribute(e))})}}Ie("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}}else{var s=e.__c;if(s){var l=s.__$u;l&&(s.__$u=void 0,l.d())}}t(e)}),Ie("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),H.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in t)if(s!=="__source"&&t[s]!==this.props[s])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function et(t,e){return W(function(){return A(t,e)},[])}var La=function(t){queueMicrotask(function(){queueMicrotask(t)})};function Pa(){$a(function(){for(var t;t=bi.shift();)xi.call(t)})}function vi(){bi.push(this)===1&&(b.requestAnimationFrame||La)(Pa)}const I=A(!1),Tt=A(void 0),ue=A(void 0),_i=A(null);function Ma(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function mn(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function qa(t,e){const n=t.title??e?.title??"Assistant";return{title:n,greeting:t.greeting??e?.welcomeMessage??`Hi! I'm ${n}. How can I help?`,locale:t.locale??e?.locale,position:t.position??e?.position,colorScheme:t.colorScheme??e?.colorScheme,hideBranding:t.hideBranding??e?.hideBranding??!1,triggerIcon:t.triggerIcon??e?.triggerIcon??"chat",triggerRadius:t.triggerRadius??e?.triggerRadius??"full",triggerLabel:t.triggerLabel??e?.triggerLabel??"Chatte mit uns",mode:t.mode??"floating",primaryColor:t.primaryColor??e?.primaryColor,accentColor:t.accentColor??e?.accentColor,fontFamily:t.fontFamily??e?.fontFamily,fontSize:t.fontSize??e?.fontSize,borderRadius:t.borderRadius??e?.borderRadius,windowWidth:t.windowWidth??e?.windowWidth,windowHeight:t.windowHeight??e?.windowHeight}}async function Oa(t,e,n,r){const i=new URL(`${t}/widget/config`);i.searchParams.set("orgSlug",e),r&&i.searchParams.set("projSlug",r);const o=await fetch(i.toString(),{signal:n});return o.ok?o.json():null}function Na(t,e,n){const[r,i]=C(null);return T(()=>{i(null);const o=n??"https://festive-mouse-978.eu-west-1.convex.cloud",s=o?mn(o):void 0;if(!s||!t)return;const l=new AbortController;async function a(u){try{const d=await Oa(u,t,l.signal,e);d&&i(d)}catch(d){if(d instanceof Error&&d.name==="AbortError")return}}return a(s),()=>{l.abort()}},[t,e,n]),r}async function xn(t,e,n){try{const r=await fetch(`${e}/widget/bootstrap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{orgSlug:t,projSlug:n}:{orgSlug:t}),credentials:"omit"});if(r.ok){const i=await r.json();return{ok:!0,token:i.token,excludePaths:i.excludePaths}}return r.status===403?{ok:!1,error:"unauthorized"}:r.status===404?{ok:!1,error:"not_found"}:r.status===429?{ok:!1,error:"rate_limited",retryAfterSec:Number(r.headers.get("Retry-After"))||60}:{ok:!1,error:"network"}}catch{return{ok:!1,error:"network"}}}function za(t,e,n,r){T(()=>{const i=r??"https://festive-mouse-978.eu-west-1.convex.cloud",o=i?mn(i):void 0;if(!o||!t||(_i.value={orgSlug:t,projSlug:e,siteUrl:o},n))return;let s=!1;return(async()=>{const l=await xn(t,o,e);if(!s)if(l.ok)ue.value=l.token;else{const a=e?`project '${t}/${e}'`:`org '${t}'`;l.error==="unauthorized"?console.error(`[JexityChat] This domain is not authorized for ${a}. Check the widget's domain rules.`):l.error==="not_found"?console.error(`[JexityChat] No active widget config found for ${a}.`):l.error==="rate_limited"?console.error(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${l.retryAfterSec??60}s.`):console.error(`[JexityChat] Bootstrap failed: ${l.error}`)}})(),()=>{s=!0}},[t,e,n,r])}const wi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",attachImagesAriaLabel:"Attach images",attachComingSoon:"File attachments — coming soon",removeAttachmentAriaLabel:"Remove attachment",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",errorRateLimited:"Too many messages. Try again in {seconds}s.",errorSessionNoToken:"Could not connect to chat. Check your connection and try again.",errorSessionUnauthorized:"This chat is not authorised on this page. Please reload.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resuming conversation…",startingConversation:"Starting conversation…",sessionNotFound:"Your previous session was not found. Starting a new conversation.",startNewConversation:"Start new conversation",chatWith:"Chat with {title}",haveReferenceNumber:"Have a reference number?",referencePlaceholder:"e.g. JEX-A3B7C2",resume:"Resume",howCanWeHelp:"How can we help?",getInstantHelp:"Get instant help",submitTicket:"Submit a ticket",replyByEmail:"We'll reply by email",ticketSubmitted:"Ticket submitted",yourReferenceNumber:"Your reference number:",sentToEmailHint:"We've sent it to your email. Use this number to follow up.",done:"Done",submittingTicket:"Submitting your ticket…",yourName:"Your name",yourEmail:"Your email",submit:"Submit",back:"Go back",escalationFormTitle:"Leave your details",escalationSubtitle:"Our team will get back to you by email so you don’t have to wait here.",escalationNameLabel:"Your name",escalationEmailLabel:"Your email",escalationSubmit:"Send to team",escalationSubmitting:"Sending…",escalationSubmitted:"Request submitted",escalationConsent:"We’ll only use your email to respond to this conversation.",escalationSkip:"Skip, I’ll wait here",escalationPromptTitle:"Talk to our team",escalationPromptSubtitle:"We can notify you by email when our team replies.",escalationPromptSubmit:"Leave details",escalationSubmitFailed:"Failed to submit. Please try again.",sessionNotFoundPrompt:"Session not found. Would you like to start a new conversation?",sessionLocked:"For your privacy, this conversation was closed after a period of inactivity. Enter your reference to resume, or start a new conversation.",sessionResolved:"This conversation has been resolved.",tryAgain:"Try again",goBack:"Go back",somethingWentWrong:"Something went wrong",fabLabel:"Chat with us",chatNoLongerAvailable:"This chat is no longer available.",talkToHuman:"Talk to human",talkToHumanAria:"Talk to a human agent",handoffPending:"Connecting you to a human agent…",handoffFailed:"Could not request a human agent. Try again.",handoffRateLimited:"You requested an agent recently. Please wait before trying again.",resumeListLabel:"Continue conversation",resumeListTimestamp:"{minutes}m ago"},Ba={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",attachImagesAriaLabel:"Bilder anhängen",attachComingSoon:"Dateianhänge — bald verfügbar",removeAttachmentAriaLabel:"Anhang entfernen",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",errorRateLimited:"Zu viele Nachrichten. Bitte in {seconds} Sek. erneut versuchen.",errorSessionNoToken:"Verbindung zum Chat fehlgeschlagen. Bitte Internet prüfen und erneut versuchen.",errorSessionUnauthorized:"Dieser Chat ist auf dieser Seite nicht autorisiert. Bitte neu laden.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch wird fortgesetzt…",startingConversation:"Konversation wird gestartet…",sessionNotFound:"Ihre vorherige Sitzung wurde nicht gefunden. Ein neues Gespräch wird gestartet.",startNewConversation:"Neues Gespräch beginnen",chatWith:"Chatte mit {title}",haveReferenceNumber:"Hast du eine Referenznummer?",referencePlaceholder:"z.B. JEX-A3B7C2",resume:"Fortsetzen",howCanWeHelp:"Wie können wir helfen?",getInstantHelp:"Soforthilfe erhalten",submitTicket:"Ticket einreichen",replyByEmail:"Wir antworten per E-Mail",ticketSubmitted:"Ticket eingereicht",yourReferenceNumber:"Deine Referenznummer:",sentToEmailHint:"Wir haben sie an deine E-Mail gesendet. Verwende diese Nummer für Rückfragen.",done:"Fertig",submittingTicket:"Dein Ticket wird übermittelt…",yourName:"Dein Name",yourEmail:"Deine E-Mail",submit:"Absenden",back:"Zurück",escalationFormTitle:"Hinterlassen Sie Ihre Daten",escalationSubtitle:"Unser Team meldet sich per E-Mail bei Ihnen — Sie müssen nicht hier warten.",escalationNameLabel:"Ihr Name",escalationEmailLabel:"Ihre E-Mail",escalationSubmit:"An Team senden",escalationSubmitting:"Wird gesendet…",escalationSubmitted:"Anfrage gesendet",escalationConsent:"Wir verwenden Ihre E-Mail nur, um auf diese Unterhaltung zu antworten.",escalationSkip:"Überspringen, ich warte hier",escalationPromptTitle:"Sprechen Sie mit unserem Team",escalationPromptSubtitle:"Wir benachrichtigen Sie per E-Mail, wenn wir antworten.",escalationPromptSubmit:"Daten hinterlassen",escalationSubmitFailed:"Senden fehlgeschlagen. Bitte versuche es erneut.",sessionNotFoundPrompt:"Sitzung nicht gefunden. Möchten Sie ein neues Gespräch beginnen?",sessionLocked:"Aus Datenschutzgründen wurde dieses Gespräch nach einer Inaktivitätszeit geschlossen. Geben Sie Ihre Referenz ein, um fortzufahren, oder beginnen Sie ein neues Gespräch.",sessionResolved:"Diese Unterhaltung wurde abgeschlossen.",tryAgain:"Erneut versuchen",goBack:"Zurück",somethingWentWrong:"Etwas ist schiefgelaufen",fabLabel:"Chatte mit uns",chatNoLongerAvailable:"Dieser Chat ist nicht mehr verfügbar.",talkToHuman:"Mit Mitarbeiter sprechen",talkToHumanAria:"Mit einem menschlichen Mitarbeiter sprechen",handoffPending:"Sie werden mit einem Mitarbeiter verbunden…",handoffFailed:"Anfrage konnte nicht gesendet werden. Erneut versuchen.",handoffRateLimited:"Sie haben kürzlich einen Mitarbeiter angefragt. Bitte warten Sie.",resumeListLabel:"Unterhaltung fortsetzen",resumeListTimestamp:"vor {minutes} Min."},Fa=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],Qa="de",Da="jex-locale",bn=A("de"),Ua={en:wi,de:Ba};function E(){return Ua[bn.value]??wi}function yn(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return Fa.some(r=>r.value===e)?e:null}function ki(t){const e=yn(t);if(e)return e;try{const n=yn(localStorage.getItem(Da));if(n)return n}catch{}if(typeof navigator<"u"){const n=yn(navigator.language);if(n)return n}return Qa}function Va(t){T(()=>{function e(n){const r=t??window.location.origin;if(n.origin!==r||n.data?.type!=="jexity:config")return;const{locale:i}=n.data.payload;i&&(bn.value=ki(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const ji="jex-session-history",Si=ji,Ci=900*1e3,N=A([]),xe=A(null),Ti=pn(()=>N.value.length>0),tt=A(null);function Ha(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function Wa(t){try{const e=sessionStorage.getItem(Si);if(!e)return[];const n=JSON.parse(e);return n.v!==1||!Array.isArray(n.entries)?[]:n.entries.filter(r=>t-r.lastActivityAt<=Ci)}catch{return[]}}function Rt(t){try{const e={v:1,entries:t};sessionStorage.setItem(Si,JSON.stringify(e))}catch{}}function Ja(){const t=Date.now(),e=Wa(t);N.value=e,Rt(e),xe.value=e.length>0?e[e.length-1].ref:null}function Ri(){const t=Ha(),e=Date.now(),n=[...N.value,{ref:t,startedAt:e,lastActivityAt:e}];return N.value=n,xe.value=t,Rt(n),t}function $i(t){const e=Date.now(),n=N.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);N.value=n,xe.value=t,Rt(n)}function vn(t){if(!t)return;const e=Date.now(),n=N.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);N.value=n,Rt(n)}const z=A(Ai());function Ai(){return Ti.value?[{id:"home"}]:[{id:"chat"}]}function Ga(){z.value=Ai()}const Ka=A("screen");function be(t){z.value=[...z.value,t]}function $t(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function _n(t){z.value=[...z.value.slice(0,-1),t]}const Za=6e4,nt=A(!1),wn=A(!1),kn=new Set;function Ya(t){return kn.add(t),()=>{kn.delete(t)}}function Xa(){const t=xe.value;return t?N.value.find(n=>n.ref===t)?.lastActivityAt??null:null}function el(t){const e=Xa();return e===null?!1:Date.now()-e>t}function Ei(){if(!(nt.value&&N.value.length===0)){N.value=[],xe.value=null;try{sessionStorage.removeItem(ji)}catch(t){console.warn("[JexityChat] Idle-lock storage clear failed:",t)}for(const t of kn)try{t()}catch(e){console.warn("[JexityChat] Lock reset callback threw:",e)}z.value=[{id:"home"}],nt.value=!0}}function jn(){nt.value&&(nt.value=!1)}function tl(t=Ci){let e=null;const n=()=>{if(document.visibilityState==="hidden"){e=Date.now();return}e!==null&&Date.now()-e>t&&Ei(),e=null};document.addEventListener("visibilitychange",n);const r=setInterval(()=>{wn.value||el(t)&&Ei()},Za);return()=>{document.removeEventListener("visibilitychange",n),clearInterval(r),e=null}}function nl(t){const e={},{primaryColor:n,theme:r}=t;if(n&&(e["--jex-primary"]=n,e["--jex-bg-trigger"]=n,e["--jex-bg-header"]=n,e["--jex-bg-msg-user"]=n,e["--jex-bg-send-btn"]=n),t.accentColor&&(e["--jex-accent"]=t.accentColor),r?.bg){const i=r.bg;i.trigger&&(e["--jex-bg-trigger"]=i.trigger),i.header&&(e["--jex-bg-header"]=i.header),i.msgUser&&(e["--jex-bg-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-bg-msg-bot"]=i.msgBot),i.window&&(e["--jex-bg-window"]=i.window),i.sendBtn&&(e["--jex-bg-send-btn"]=i.sendBtn)}if(r?.text){const i=r.text;i.header&&(e["--jex-text-header"]=i.header),i.msgUser&&(e["--jex-text-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-text-msg-bot"]=i.msgBot),i.main&&(e["--jex-text-main"]=i.main),i.muted&&(e["--jex-text-muted"]=i.muted)}if(r?.border){const i=r.border;i.window&&(e["--jex-border-window"]=i.window),i.input&&(e["--jex-border-input"]=i.input)}return t.fontFamily&&(e["--jex-font-family"]=t.fontFamily),t.fontSize&&(e["--jex-font-size"]=`${t.fontSize}px`),t.borderRadius&&(e["--jex-radius"]=t.borderRadius),t.windowWidth&&(e["--jex-window-width"]=`${t.windowWidth}px`),t.windowHeight&&(e["--jex-window-height"]=`${t.windowHeight}px`),Object.keys(e).length>0?e:void 0}function Sn({size:t=24}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M12 8V4H8"}),c("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),c("path",{d:"M2 14h2"}),c("path",{d:"M20 14h2"}),c("path",{d:"M15 13v2"}),c("path",{d:"M9 13v2"})]})}function rl(){const t=E();return z.value.length>1?c("button",{class:"jex-header-back",onClick:$t,"aria-label":t.back||"Go back",children:c("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"m15 18-6-6 6-6"})})}):c(Sn,{size:24})}function il({title:t}){const e=E();return c("div",{class:"jex-header-info",children:[c("h3",{children:t}),c("p",{children:e.statusOnline})]})}function Ii({size:t=28}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M18 6 6 18"}),c("path",{d:"m6 6 12 12"})]})}function ol(){const t=E();return c("button",{class:"jex-header-close",type:"button",onClick:()=>{I.value=!1},"aria-label":t.closeChatAriaLabel,title:t.closeChatAriaLabel,children:c(Ii,{size:18})})}function sl({action:t,showClose:e=!0}){return!t&&!e?null:c("div",{class:"jex-header-right",children:[t,e&&c(ol,{})]})}function Li({title:t,rightAction:e,showClose:n=!0}){return c("header",{class:"jex-chat-header",children:[c(rl,{}),c(il,{title:t}),c(sl,{action:e,showClose:n})]})}function al({size:t=14}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"})})}function Pi(){return c("div",{class:"jex-widget-footer",children:c("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[c(al,{size:14}),c("span",{children:["Powered by ",c("strong",{children:"Jexity"})]})]})})}function Mi({size:t=28}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ll({size:t=24,...e}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...e,children:c("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})})}const cl={chat:c(Mi,{size:28}),bot:c(Sn,{size:28}),sparkles:c(ll,{size:28})},ul={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function hl({radius:t="full",iconOption:e="chat",label:n}){const r=E(),i=n??r.fabLabel,o=i!=="";return c("button",{class:`jex-floating-button ${!I.value&&o?"jex-has-label":""}`,style:{borderRadius:ul[t]??"9999px"},onClick:()=>{I.value=!I.value},"aria-label":I.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:I.value?c(Ii,{size:28}):c("div",{class:"jex-fab-inner",children:[cl[e],o&&c("span",{class:"jex-fab-label",children:i})]})})}function dl({title:t,onStartFresh:e,onResetSession:n}){const r=E(),[i,o]=C("");function s(){jn(),tt.value="fresh",n(),e(),be({id:"chat"})}function l(u){jn(),tt.value="resume",n(),$i(u),be({id:"chat"})}function a(u){u.preventDefault();const d=i.trim().toUpperCase();d&&(jn(),tt.value="resume",n(),$i(d),be({id:"chat"}))}return c("div",{class:"jex-home",children:[nt.value&&c("div",{class:"jex-session-prompt",role:"status",children:c("div",{class:"jex-session-prompt-text",children:r.sessionLocked})}),c("div",{class:"jex-home-hero",children:[c("div",{class:"jex-home-avatar",children:[c(Mi,{size:24}),c("span",{class:"jex-home-status-dot"})]}),c("div",{class:"jex-home-hero-text",children:[c("h2",{class:"jex-home-title",children:t}),c("span",{class:"jex-home-status",children:r.statusOnline})]})]}),c("form",{class:"jex-home-lookup",onSubmit:a,children:[c("input",{class:"jex-home-lookup-input",type:"text",placeholder:r.referencePlaceholder,value:i,onInput:u=>{o(u.currentTarget.value)}}),c("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!i.trim(),children:r.resume})]}),c("div",{class:"jex-home-actions",children:[N.value.length>0&&c("div",{class:"jex-home-history",children:N.value.slice().reverse().map(u=>c("button",{class:"jex-home-resume-card",onClick:()=>{l(u.ref)},children:[c("div",{class:"jex-home-resume-top",children:[c("span",{class:"jex-home-resume-label",children:r.resumeListLabel}),c("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:c("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),c("span",{class:"jex-home-resume-ref",children:u.ref}),c("span",{class:"jex-home-resume-meta",children:r.resumeListTimestamp.replace("{minutes}",String(Math.max(1,Math.round((Date.now()-u.lastActivityAt)/6e4))))})]},u.ref))}),c("button",{class:"jex-home-new-btn",onClick:s,children:N.value.length>0?r.startNewConversation:r.chatWith.replace("{title}",t)})]})]})}function fl({title:t}){const e=E();return c("div",{class:"jex-selection",children:[c("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),c("div",{class:"jex-selection-options",children:[c("button",{class:"jex-selection-option",onClick:()=>be({id:"chat"}),children:[c("span",{class:"jex-selection-icon",children:"💬"}),c("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),c("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),c("button",{class:"jex-selection-option",onClick:()=>be({id:"form"}),children:[c("span",{class:"jex-selection-icon",children:"📝"}),c("span",{class:"jex-selection-label",children:e.submitTicket}),c("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}const pl=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const qi=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const gl=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Oi=t=>{const e=gl(t);return e.charAt(0).toUpperCase()+e.slice(1)};var ml={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};const xl=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const bl=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,children:i,iconNode:o,class:s="",...l})=>Q("svg",{...ml,width:String(e),height:e,stroke:t,"stroke-width":r?Number(n)*24/Number(e):n,class:["lucide",s].join(" "),...!i&&!xl(l)&&{"aria-hidden":"true"},...l},[...o.map(([a,u])=>Q(a,u)),...Y(i)]);const yl=(t,e)=>{const n=({class:r="",className:i="",children:o,...s})=>Q(bl,{...s,iconNode:e,class:pl(`lucide-${qi(Oi(t))}`,`lucide-${qi(t)}`,r,i)},o);return n.displayName=Oi(t),n};const vl=yl("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]);function Cn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ye=Cn();function Ni(t){ye=t}var ve={exec:()=>null};function _(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(M.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,e)};return r}var _l=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),M={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},wl=/^(?:[ \t]*(?:\n|$))+/,kl=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,rt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Sl=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Tn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Bi=_(zi).replace(/bull/g,Tn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Cl=_(zi).replace(/bull/g,Tn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Rn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Tl=/^[^\n]+/,$n=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Rl=_(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",$n).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),$l=_(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Tn).getRegex(),At="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",An=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Al=_("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",An).replace("tag",At).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Fi=_(Rn).replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",At).getRegex(),El=_(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Fi).getRegex(),En={blockquote:El,code:kl,def:Rl,fences:jl,heading:Sl,hr:rt,html:Al,lheading:Bi,list:$l,newline:wl,paragraph:Fi,table:ve,text:Tl},Qi=_("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",At).getRegex(),Il={...En,lheading:Cl,table:Qi,paragraph:_(Rn).replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qi).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",At).getRegex()},Ll={...En,html:_(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",An).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ve,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:_(Rn).replace("hr",rt).replace("heading",` *#{1,6} *[^
3
- ]`).replace("lheading",Bi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Pl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ml=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Di=/^( {2,}|\\)\n(?!\s*$)/,ql=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Le=/[\p{P}\p{S}]/u,Et=/[\s\p{P}\p{S}]/u,In=/[^\s\p{P}\p{S}]/u,Ol=_(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Et).getRegex(),Ui=/(?!~)[\p{P}\p{S}]/u,Nl=/(?!~)[\s\p{P}\p{S}]/u,zl=/(?:[^\s\p{P}\p{S}]|~)/u,Bl=_(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",_l?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Vi=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Fl=_(Vi,"u").replace(/punct/g,Le).getRegex(),Ql=_(Vi,"u").replace(/punct/g,Ui).getRegex(),Hi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Dl=_(Hi,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Le).getRegex(),Ul=_(Hi,"gu").replace(/notPunctSpace/g,zl).replace(/punctSpace/g,Nl).replace(/punct/g,Ui).getRegex(),Vl=_("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Le).getRegex(),Hl=_(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Le).getRegex(),Wl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Jl=_(Wl,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Le).getRegex(),Gl=_(/\\(punct)/,"gu").replace(/punct/g,Le).getRegex(),Kl=_(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Zl=_(An).replace("(?:-->|$)","-->").getRegex(),Yl=_("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Zl).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),It=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Xl=_(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",It).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Wi=_(/^!?\[(label)\]\[(ref)\]/).replace("label",It).replace("ref",$n).getRegex(),Ji=_(/^!?\[(ref)\](?:\[\])?/).replace("ref",$n).getRegex(),ec=_("reflink|nolink(?!\\()","g").replace("reflink",Wi).replace("nolink",Ji).getRegex(),Gi=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ln={_backpedal:ve,anyPunctuation:Gl,autolink:Kl,blockSkip:Bl,br:Di,code:Ml,del:ve,delLDelim:ve,delRDelim:ve,emStrongLDelim:Fl,emStrongRDelimAst:Dl,emStrongRDelimUnd:Vl,escape:Pl,link:Xl,nolink:Ji,punctuation:Ol,reflink:Wi,reflinkSearch:ec,tag:Yl,text:ql,url:ve},tc={...Ln,link:_(/^!?\[(label)\]\((.*?)\)/).replace("label",It).getRegex(),reflink:_(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",It).getRegex()},Pn={...Ln,emStrongRDelimAst:Ul,emStrongLDelim:Ql,delLDelim:Hl,delRDelim:Jl,url:_(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gi).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:_(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Gi).getRegex()},nc={...Pn,br:_(Di).replace("{2,}","*").getRegex(),text:_(Pn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Lt={normal:En,gfm:Il,pedantic:Ll},it={normal:Ln,gfm:Pn,breaks:nc,pedantic:tc},rc={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ki=t=>rc[t];function ne(t,e){if(e){if(M.escapeTest.test(t))return t.replace(M.escapeReplace,Ki)}else if(M.escapeTestNoEncode.test(t))return t.replace(M.escapeReplaceNoEncode,Ki);return t}function Zi(t){try{t=encodeURI(t).replace(M.percentDecode,"%")}catch{return null}return t}function Yi(t,e){let n=t.replace(M.findPipe,(o,s,l)=>{let a=!1,u=s;for(;--u>=0&&l[u]==="\\";)a=!a;return a?"|":" |"}),r=n.split(M.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(M.slashPipe,"|");return r}function ot(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r&&t.charAt(r-i-1)===e;)i++;return t.slice(0,r-i)}function ic(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function oc(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function Xi(t,e,n,r,i){let o=e.href,s=e.title||null,l=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function sc(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
1
+ (function(){"use strict";var ze,b,Fn,Qn,de,Dn,Un,Vn,Hn,Ot,Nt,zt,Wn,Be={},Jn=[],ho=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Fe=Array.isArray;function Z(t,e){for(var n in e)t[n]=e[n];return t}function Bt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Q(t,e,n){var r,i,o,s={};for(o in e)o=="key"?r=e[o]:o=="ref"?i=e[o]:s[o]=e[o];if(arguments.length>2&&(s.children=arguments.length>3?ze.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return Qe(t,s,r,i,null)}function Qe(t,e,n,r,i){var o={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Fn,__i:-1,__u:0};return i==null&&b.vnode!=null&&b.vnode(o),o}function fo(){return{current:null}}function B(t){return t.children}function H(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Kn(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Kn(t)}}function Ft(t){(!t.__d&&(t.__d=!0)&&de.push(t)&&!ut.__r++||Dn!=b.debounceRendering)&&((Dn=b.debounceRendering)||Un)(ut)}function ut(){for(var t,e,n,r,i,o,s,l=1;de.length;)de.length>l&&de.sort(Vn),t=de.shift(),l=de.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,o=[],s=[],e.__P&&((n=Z({},r)).__v=r.__v+1,b.vnode&&b.vnode(n),Qt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,o,i??we(r),!!(32&r.__u),s),n.__v=r.__v,n.__.__k[n.__i]=n,er(o,n,s),r.__e=r.__=null,n.__e!=i&&Kn(n)));ut.__r=0}function Gn(t,e,n,r,i,o,s,l,a,u,d){var h,f,p,g,m,x,v,y=r&&r.__k||Jn,M=e.length;for(a=po(n,e,y,a,M),h=0;h<M;h++)(p=n.__k[h])!=null&&(f=p.__i==-1?Be:y[p.__i]||Be,p.__i=h,x=Qt(t,p,f,i,o,s,l,a,u,d),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&Ut(f.ref,null,p),d.push(p.ref,p.__c||g,p)),m==null&&g!=null&&(m=g),(v=!!(4&p.__u))||f.__k===p.__k?a=Zn(p,a,t,v):typeof p.type=="function"&&x!==void 0?a=x:g&&(a=g.nextSibling),p.__u&=-7);return n.__e=m,a}function po(t,e,n,r,i){var o,s,l,a,u,d=n.length,h=d,f=0;for(t.__k=new Array(i),o=0;o<i;o++)(s=e[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=o+f,(s=t.__k[o]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?Qe(null,s,null,null,null):Fe(s)?Qe(B,{children:s},null,null,null):s.constructor==null&&s.__b>0?Qe(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,l=null,(u=s.__i=go(s,n,a,h))!=-1&&(h--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?f--:i<d&&f++),typeof s.type!="function"&&(s.__u|=4)):u!=a&&(u==a-1?f--:u==a+1?f++:(u>a?f--:f++,s.__u|=4))):t.__k[o]=null;if(h)for(o=0;o<d;o++)(l=n[o])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=we(l)),nr(l,l));return r}function Zn(t,e,n,r){var i,o;if(typeof t.type=="function"){for(i=t.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=t,e=Zn(i[o],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Y(t,e){return e=e||[],t==null||typeof t=="boolean"||(Fe(t)?t.some(function(n){Y(n,e)}):e.push(t)),e}function go(t,e,n,r){var i,o,s,l=t.key,a=t.type,u=e[n],d=u!=null&&(2&u.__u)==0;if(u===null&&t.key==null||d&&l==u.key&&a==u.type)return n;if(r>(d?1:0)){for(i=n-1,o=n+1;i>=0||o<e.length;)if((u=e[s=i>=0?i--:o++])!=null&&(2&u.__u)==0&&l==u.key&&a==u.type)return s}return-1}function Yn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||ho.test(e)?n:n+"px"}function ht(t,e,n,r,i){var o,s;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof r=="string"&&(t.style.cssText=r=""),r)for(e in r)n&&e in n||Yn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Yn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Hn,"$1")),s=e.toLowerCase(),e=s in t||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?r?n.u=r.u:(n.u=Ot,t.addEventListener(e,o?zt:Nt,o)):t.removeEventListener(e,o?zt:Nt,o);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Xn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Ot++;else if(e.t<n.u)return;return n(b.event?b.event(e):e)}}}function Qt(t,e,n,r,i,o,s,l,a,u){var d,h,f,p,g,m,x,v,y,M,V,G,F,uo,Pt,ct,Nn,re=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),o=[l=e.__e=n.__e]),(d=b.__b)&&d(e);e:if(typeof re=="function")try{if(v=e.props,y="prototype"in re&&re.prototype.render,M=(d=re.contextType)&&r[d.__c],V=d?M?M.props.value:d.__:r,n.__c?x=(h=e.__c=n.__c).__=h.__E:(y?e.__c=h=new re(v,V):(e.__c=h=new H(v,V),h.constructor=re,h.render=xo),M&&M.sub(h),h.props=v,h.state||(h.state={}),h.context=V,h.__n=r,f=h.__d=!0,h.__h=[],h._sb=[]),y&&h.__s==null&&(h.__s=h.state),y&&re.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=Z({},h.__s)),Z(h.__s,re.getDerivedStateFromProps(v,h.__s))),p=h.props,g=h.state,h.__v=e,f)y&&re.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),y&&h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(y&&re.getDerivedStateFromProps==null&&v!==p&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(v,V),!h.__e&&h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(v,h.__s,V)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(h.props=v,h.state=h.__s,h.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Ne){Ne&&(Ne.__=e)}),G=0;G<h._sb.length;G++)h.__h.push(h._sb[G]);h._sb=[],h.__h.length&&s.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(v,h.__s,V),y&&h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(p,g,m)})}if(h.context=V,h.props=v,h.__P=t,h.__e=!1,F=b.__r,uo=0,y){for(h.state=h.__s,h.__d=!1,F&&F(e),d=h.render(h.props,h.state,h.context),Pt=0;Pt<h._sb.length;Pt++)h.__h.push(h._sb[Pt]);h._sb=[]}else do h.__d=!1,F&&F(e),d=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++uo<25);h.state=h.__s,h.getChildContext!=null&&(r=Z(Z({},r),h.getChildContext())),y&&!f&&h.getSnapshotBeforeUpdate!=null&&(m=h.getSnapshotBeforeUpdate(p,g)),ct=d,d!=null&&d.type===B&&d.key==null&&(ct=tr(d.props.children)),l=Gn(t,Fe(ct)?ct:[ct],e,n,r,i,o,s,l,a,u),h.base=e.__e,e.__u&=-161,h.__h.length&&s.push(h),x&&(h.__E=h.__=null)}catch(Ne){if(e.__v=null,a||o!=null)if(Ne.then){for(e.__u|=a?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;o[o.indexOf(l)]=null,e.__e=l}else{for(Nn=o.length;Nn--;)Bt(o[Nn]);Dt(e)}else e.__e=n.__e,e.__k=n.__k,Ne.then||Dt(e);b.__e(Ne,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=mo(n.__e,e,n,r,i,o,s,a,u);return(d=b.diffed)&&d(e),128&e.__u?void 0:l}function Dt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Dt)}function er(t,e,n){for(var r=0;r<n.length;r++)Ut(n[r],n[++r],n[++r]);b.__c&&b.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(o){o.call(i)})}catch(o){b.__e(o,i.__v)}})}function tr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Fe(t)?t.map(tr):Z({},t)}function mo(t,e,n,r,i,o,s,l,a){var u,d,h,f,p,g,m,x=n.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(u=0;u<o.length;u++)if((p=o[u])&&"setAttribute"in p==!!y&&(y?p.localName==y:p.nodeType==3)){t=p,o[u]=null;break}}if(t==null){if(y==null)return document.createTextNode(v);t=document.createElementNS(i,y,v.is&&v),l&&(b.__m&&b.__m(e,o),l=!1),o=null}if(y==null)x===v||l&&t.data==v||(t.data=v);else{if(o=o&&ze.call(t.childNodes),x=n.props||Be,!l&&o!=null)for(x={},u=0;u<t.attributes.length;u++)x[(p=t.attributes[u]).name]=p.value;for(u in x)if(p=x[u],u!="children"){if(u=="dangerouslySetInnerHTML")h=p;else if(!(u in v)){if(u=="value"&&"defaultValue"in v||u=="checked"&&"defaultChecked"in v)continue;ht(t,u,null,p,i)}}for(u in v)p=v[u],u=="children"?f=p:u=="dangerouslySetInnerHTML"?d=p:u=="value"?g=p:u=="checked"?m=p:l&&typeof p!="function"||x[u]===p||ht(t,u,p,x[u],i);if(d)l||h&&(d.__html==h.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(h&&(t.innerHTML=""),Gn(e.type=="template"?t.content:t,Fe(f)?f:[f],e,n,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&we(n,0),l,a),o!=null)for(u=o.length;u--;)Bt(o[u]);l||(u="value",y=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[u]||y=="progress"&&!g||y=="option"&&g!=x[u])&&ht(t,u,g,x[u],i),u="checked",m!=null&&m!=t[u]&&ht(t,u,m,x[u],i))}return t}function Ut(t,e,n){try{if(typeof t=="function"){var r=typeof t.__u=="function";r&&t.__u(),r&&e==null||(t.__u=t(e))}else t.current=e}catch(i){b.__e(i,n)}}function nr(t,e,n){var r,i;if(b.unmount&&b.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Ut(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){b.__e(o,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&nr(r[i],e,n||typeof t.type!="function");n||Bt(t.__e),t.__c=t.__=t.__e=void 0}function xo(t,e,n){return this.constructor(t,n)}function fe(t,e,n){var r,i,o,s;e==document&&(e=document.documentElement),b.__&&b.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,o=[],s=[],Qt(e,t=(!r&&n||e).__k=Q(B,null,[t]),i||Be,Be,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?ze.call(e.childNodes):null,o,!r&&n?n:i?i.__e:e.firstChild,r,s),er(o,t,s)}function rr(t,e){fe(t,e,rr)}function bo(t,e,n){var r,i,o,s,l=Z({},t.props);for(o in t.type&&t.type.defaultProps&&(s=t.type.defaultProps),e)o=="key"?r=e[o]:o=="ref"?i=e[o]:l[o]=e[o]===void 0&&s!=null?s[o]:e[o];return arguments.length>2&&(l.children=arguments.length>3?ze.call(arguments,2):n),Qe(t.type,l,r||t.key,i||t.ref,null)}function yo(t){function e(n){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&r.forEach(function(s){s.__e=!0,Ft(s)})},this.sub=function(o){r.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){r&&r.delete(o),s&&s.call(o)}}),n.children}return e.__c="__cC"+Wn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}ze=Jn.slice,b={__e:function(t,e,n,r){for(var i,o,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(t)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),s=i.__d),s)return i.__E=i}catch(l){t=l}throw t}},Fn=0,Qn=function(t){return t!=null&&t.constructor==null},H.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Z({},this.state),typeof t=="function"&&(t=t(Z({},n),this.props)),t&&Z(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ft(this))},H.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ft(this))},H.prototype.render=B,de=[],Un=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Vn=function(t,e){return t.__v.__b-e.__v.__b},ut.__r=0,Hn=/(PointerCapture)$|Capture$/i,Ot=0,Nt=Xn(!1),zt=Xn(!0),Wn=0;var vo=0;function c(t,e,n,r,i,o){e||(e={});var s,l,a=e;if("ref"in a)for(l in a={},e)l=="ref"?s=e[l]:a[l]=e[l];var u={type:t,props:a,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vo,__i:-1,__u:0,__source:i,__self:o};if(typeof t=="function"&&(s=t.defaultProps))for(l in s)a[l]===void 0&&(a[l]=s[l]);return b.vnode&&b.vnode(u),u}var ae,S,Vt,ir,ke=0,or=[],j=b,sr=j.__b,ar=j.__r,lr=j.diffed,cr=j.__c,ur=j.unmount,hr=j.__;function Se(t,e){j.__h&&j.__h(S,t,ke||e),ke=0;var n=S.__H||(S.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return ke=1,Ht(mr,t)}function Ht(t,e,n){var r=Se(ae++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):mr(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],u=r.t(a,l);a!==u&&(r.__N=[u,r.__[1]],r.__c.setState({}))}],r.__c=S,!S.__f)){var i=function(l,a,u){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!o||o.call(this,l,a,u);var h=r.__c.props!==l;return d.forEach(function(f){if(f.__N){var p=f.__[0];f.__=f.__N,f.__N=void 0,p!==f.__[0]&&(h=!0)}}),o&&o.call(this,l,a,u)||h};S.__f=!0;var o=S.shouldComponentUpdate,s=S.componentWillUpdate;S.componentWillUpdate=function(l,a,u){if(this.__e){var d=o;o=void 0,i(l,a,u),o=d}s&&s.call(this,l,a,u)},S.shouldComponentUpdate=i}return r.__N||r.__}function T(t,e){var n=Se(ae++,3);!j.__s&&Jt(n.__H,e)&&(n.__=t,n.u=e,S.__H.__h.push(n))}function De(t,e){var n=Se(ae++,4);!j.__s&&Jt(n.__H,e)&&(n.__=t,n.u=e,S.__h.push(n))}function le(t){return ke=5,W(function(){return{current:t}},[])}function dr(t,e,n){ke=6,De(function(){if(typeof t=="function"){var r=t(e());return function(){t(null),r&&typeof r=="function"&&r()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function W(t,e){var n=Se(ae++,7);return Jt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function je(t,e){return ke=8,W(function(){return t},e)}function dt(t){var e=S.context[t.__c],n=Se(ae++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(S)),e.props.value):t.__}function fr(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function pr(){var t=Se(ae++,11);if(!t.__){for(var e=S.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function _o(){for(var t;t=or.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ft),t.__H.__h.forEach(Wt),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){S=null,sr&&sr(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),hr&&hr(t,e)},j.__r=function(t){ar&&ar(t),ae=0;var e=(S=t.__c).__H;e&&(Vt===S?(e.__h=[],S.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ft),e.__h.forEach(Wt),e.__h=[],ae=0)),Vt=S},j.diffed=function(t){lr&&lr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(or.push(e)!==1&&ir===j.requestAnimationFrame||((ir=j.requestAnimationFrame)||wo)(_o)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Vt=S=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ft),n.__h=n.__h.filter(function(r){return!r.__||Wt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),cr&&cr(t,e)},j.unmount=function(t){ur&&ur(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{ft(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var gr=typeof requestAnimationFrame=="function";function wo(t){var e,n=function(){clearTimeout(r),gr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);gr&&(e=requestAnimationFrame(n))}function ft(t){var e=S,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),S=e}function Wt(t){var e=S;t.__c=t.__(),S=e}function Jt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function mr(t,e){return typeof e=="function"?e(t):e}function xr(t,e){for(var n in e)t[n]=e[n];return t}function Kt(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var r in e)if(r!=="__source"&&t[r]!==e[r])return!0;return!1}function br(t,e){var n=e(),r=C({t:{__:n,u:e}}),i=r[0].t,o=r[1];return De(function(){i.__=n,i.u=e,Gt(i)&&o({t:i})},[t,n,e]),T(function(){return Gt(i)&&o({t:i}),t(function(){Gt(i)&&o({t:i})})},[t]),n}function Gt(t){var e,n,r=t.u,i=t.__;try{var o=r();return!((e=i)===(n=o)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function yr(t){t()}function vr(t){return t}function _r(){return[!1,yr]}var wr=De;function Zt(t,e){this.props=t,this.context=e}function ko(t,e){function n(i){var o=this.props.ref,s=o==i.ref;return!s&&o&&(o.call?o(null):o.current=null),e?!e(this.props,i)||!s:Kt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,Q(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Zt.prototype=new H).isPureReactComponent=!0,Zt.prototype.shouldComponentUpdate=function(t,e){return Kt(this.props,t)||Kt(this.state,e)};var kr=b.__b;b.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),kr&&kr(t)};var So=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function jo(t){function e(n){var r=xr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=So,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Sr=function(t,e){return t==null?null:Y(Y(t).map(e))},Co={map:Sr,forEach:Sr,count:function(t){return t?Y(t).length:0},only:function(t){var e=Y(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Y},To=b.__e;b.__e=function(t,e,n,r){if(t.then){for(var i,o=e;o=o.__;)if((i=o.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}To(t,e,n,r)};var jr=b.unmount;function Cr(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),t.__c.__H=null),(t=xr({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(r){return Cr(r,e,n)})),t}function Tr(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return Tr(r,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function pt(){this.__u=0,this.o=null,this.__b=null}function Rr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Ro(t){var e,n,r;function i(o){if(e||(e=t()).then(function(s){n=s.default||s},function(s){r=s}),r)throw r;if(!n)throw e;return Q(n,o)}return i.displayName="Lazy",i.__f=!0,i}function Ue(){this.i=null,this.l=null}b.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),jr&&jr(t)},(pt.prototype=new H).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=Rr(r.__v),o=!1,s=function(){o||(o=!0,n.__R=null,i?i(l):l())};n.__R=s;var l=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Tr(a,a.__c.__P,a.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(s,s)},pt.prototype.componentWillUnmount=function(){this.o=[]},pt.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Cr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&Q(B,null,t.fallback);return i&&(i.__u&=-33),[Q(B,null,e.__a?null:t.children),i]};var Ar=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function Ao(t){return this.getChildContext=function(){return t.context},t.children}function $o(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){fe(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var r=e.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},insertBefore:function(i,o){this.childNodes.push(i),e.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}fe(Q(Ao,{context:e.context},t.__v),e.v)}function Eo(t,e){var n=Q($o,{__v:t,h:e});return n.containerInfo=e,n}(Ue.prototype=new H).__a=function(t){var e=this,n=Rr(e.__v),r=e.l.get(t);return r[0]++,function(i){var o=function(){e.props.revealOrder?(r.push(i),Ar(e,t,r)):i()};n?n(o):o()}},Ue.prototype.render=function(t){this.i=null,this.l=new Map;var e=Y(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Ue.prototype.componentDidUpdate=Ue.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Ar(t,n,e)})};var $r=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Io=/^(?: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]/,Mo=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,qo=/[A-Z0-9]/g,Lo=typeof document<"u",Po=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function Oo(t,e,n){return e.__k==null&&(e.textContent=""),fe(t,e),typeof n=="function"&&n(),t?t.__c:null}function No(t,e,n){return rr(t,e),typeof n=="function"&&n(),t?t.__c:null}H.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(H.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Er=b.event;function zo(){}function Bo(){return this.cancelBubble}function Fo(){return this.defaultPrevented}b.event=function(t){return Er&&(t=Er(t)),t.persist=zo,t.isPropagationStopped=Bo,t.isDefaultPrevented=Fo,t.nativeEvent=t};var Yt,Qo={enumerable:!1,configurable:!0,get:function(){return this.class}},Ir=b.vnode;b.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},o=r.indexOf("-")===-1;for(var s in n){var l=n[s];if(!(s==="value"&&"defaultValue"in n&&l==null||Lo&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&l===!0?l="":a==="translate"&&l==="no"?l=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||Po(n.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":Mo.test(s)&&(s=a):a=s="oninput":o&&Io.test(s)?s=s.replace(qo,"-$&").toLowerCase():l===null&&(l=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=l}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=Y(n.children).forEach(function(u){u.props.selected=i.value.indexOf(u.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=Y(n.children).forEach(function(u){u.props.selected=i.multiple?i.defaultValue.indexOf(u.props.value)!=-1:i.defaultValue==u.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",Qo)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=$r,Ir&&Ir(t)};var Mr=b.__r;b.__r=function(t){Mr&&Mr(t),Yt=t.__c};var qr=b.diffed;b.diffed=function(t){qr&&qr(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Yt=null};var Do={ReactCurrentDispatcher:{current:{readContext:function(t){return Yt.__n[t.__c].props.value},useCallback:je,useContext:dt,useDebugValue:fr,useDeferredValue:vr,useEffect:T,useId:pr,useImperativeHandle:dr,useInsertionEffect:wr,useLayoutEffect:De,useMemo:W,useReducer:Ht,useRef:le,useState:C,useSyncExternalStore:br,useTransition:_r}}};function Uo(t){return Q.bind(null,t)}function gt(t){return!!t&&t.$$typeof===$r}function Vo(t){return gt(t)&&t.type===B}function Ho(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function Wo(t){return gt(t)?bo.apply(null,arguments):t}function Jo(t){return!!t.__k&&(fe(null,t),!0)}function Ko(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var Go=function(t,e){return t(e)},Zo=function(t,e){return t(e)},Yo=B,Xo=gt,Xt={useState:C,useId:pr,useReducer:Ht,useEffect:T,useLayoutEffect:De,useInsertionEffect:wr,useTransition:_r,useDeferredValue:vr,useSyncExternalStore:br,startTransition:yr,useRef:le,useImperativeHandle:dr,useMemo:W,useCallback:je,useContext:dt,useDebugValue:fr,version:"18.3.1",Children:Co,render:Oo,hydrate:No,unmountComponentAtNode:Jo,createPortal:Eo,createElement:Q,createContext:yo,createFactory:Uo,cloneElement:Wo,createRef:fo,Fragment:B,isValidElement:gt,isElement:Xo,isFragment:Vo,isMemo:Ho,findDOMNode:Ko,Component:H,PureComponent:Zt,memo:ko,forwardRef:jo,flushSync:Zo,unstable_batchedUpdates:Go,StrictMode:Yo,Suspense:pt,SuspenseList:Ue,lazy:Ro,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Do},X=[],D=[],es=Uint8Array,en="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ce=0,ts=en.length;Ce<ts;++Ce)X[Ce]=en[Ce],D[en.charCodeAt(Ce)]=Ce;D[45]=62,D[95]=63;function ns(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function rs(t,e,n){return(e+n)*3/4-n}function Ve(t){var e,n=ns(t),r=n[0],i=n[1],o=new es(rs(t,r,i)),s=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=D[t.charCodeAt(a)]<<18|D[t.charCodeAt(a+1)]<<12|D[t.charCodeAt(a+2)]<<6|D[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=D[t.charCodeAt(a)]<<2|D[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=D[t.charCodeAt(a)]<<10|D[t.charCodeAt(a+1)]<<4|D[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function is(t){return X[t>>18&63]+X[t>>12&63]+X[t>>6&63]+X[t&63]}function os(t,e,n){for(var r,i=[],o=e;o<n;o+=3)r=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(is(r));return i.join("")}function He(t){for(var e,n=t.length,r=n%3,i=[],o=16383,s=0,l=n-r;s<l;s+=o)i.push(os(t,s,s+o>l?l:s+o));return r===1?(e=t[n-1],i.push(X[e>>2]+X[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(X[e>>10]+X[e>>4&63]+X[e<<2&63]+"=")),i.join("")}function ie(t){if(t===void 0)return{};if(!Lr(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function ss(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function Lr(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const Pr=!0,Te=BigInt("-9223372036854775808"),tn=BigInt("9223372036854775807"),nn=BigInt("0"),as=BigInt("8"),ls=BigInt("256");function Or(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function cs(t){t<nn&&(t-=Te+Te);let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new Uint8Array(new ArrayBuffer(8));let r=0;for(const i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=as;return He(n)}function us(t){const e=Ve(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=nn,r=nn;for(const i of e)n+=BigInt(i)*ls**r,r++;return n>tn&&(n+=Te+Te),n}function hs(t){if(t<Te||tn<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);const e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),He(new Uint8Array(e))}function ds(t){const e=Ve(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}const fs=DataView.prototype.setBigInt64?hs:cs,ps=DataView.prototype.getBigInt64?ds:us,Nr=1024;function zr(t){if(t.length>Nr)throw new Error(`Field name ${t} exceeds maximum field name length ${Nr}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){const n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}function Re(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Re(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);const e=Object.entries(t);if(e.length===1){const r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return Ve(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return ps(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=Ve(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,Pr);if(!Or(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,i]of Object.entries(t))zr(r),n[r]=Re(i);return n}const Br=16384;function We(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Br){const n="[...truncated]";let r=Br-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function rn(t,e,n,r){if(t===void 0){const s=n&&` (present at path ${n} in original object ${We(e)})`;throw new Error(`undefined is not a valid Convex value${s}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<Te||tn<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:fs(t)}}if(typeof t=="number")if(Or(t)){const s=new ArrayBuffer(8);return new DataView(s).setFloat64(0,t,Pr),{$float:He(new Uint8Array(s))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:He(new Uint8Array(t))};if(Array.isArray(t))return t.map((s,l)=>rn(s,e,n+`[${l}]`));if(t instanceof Set)throw new Error(on(n,"Set",[...t],e));if(t instanceof Map)throw new Error(on(n,"Map",[...t],e));if(!Lr(t)){const s=t?.constructor?.name,l=s?`${s} `:"";throw new Error(on(n,l,t,e))}const i={},o=Object.entries(t);o.sort(([s,l],[a,u])=>s===a?0:s<a?-1:1);for(const[s,l]of o)l!==void 0&&(zr(s),i[s]=rn(l,e,n+`.${s}`));return i}function on(t,e,n,r){return t?`${e}${We(n)} is not a supported Convex type (present at path ${t} in original object ${We(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${We(n)} is not a supported Convex type.`}function ee(t){return rn(t,t,"")}var gs=Object.defineProperty,ms=(t,e,n)=>e in t?gs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sn=(t,e,n)=>ms(t,typeof e!="symbol"?e+"":e,n),Fr,Qr;const xs=Symbol.for("ConvexError");class mt extends(Qr=Error,Fr=xs,Qr){constructor(e){super(typeof e=="string"?e:We(e)),sn(this,"name","ConvexError"),sn(this,"data"),sn(this,Fr,!0),this.data=e}}const Dr=()=>Array.from({length:4},()=>0);Dr(),Dr();const Ur="1.39.1";var bs=Object.defineProperty,ys=(t,e,n)=>e in t?bs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vr=(t,e,n)=>ys(t,typeof e!="symbol"?e+"":e,n);const vs="color:rgb(0, 145, 255)";function Hr(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Wr{constructor(e){Vr(this,"_onLogLineFuncs"),Vr(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(const n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(const n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(const n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(const n of Object.values(this._onLogLineFuncs))n("error",...e)}}function Jr(t){const e=new Wr(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}function Kr(t){return new Wr(t)}function xt(t,e,n,r,i){const o=Hr(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const s=i.match(/^\[.*?\] /);if(s===null){t.error(`[CONVEX ${o}(${r})] Could not parse console.log`);return}const l=i.slice(1,s[0].length-2),a=i.slice(s[0].length);t.log(`%c[CONVEX ${o}(${r})] [${l}]`,vs,a)}else t.error(`[CONVEX ${o}(${r})] ${i}`)}function _s(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Ae(t,e,n){return`[CONVEX ${Hr(t)}(${e})] ${n.errorMessage}
2
+ Called by client`}function an(t,e){return e.data=t.errorData,e}function pe(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function ge(t,e){return JSON.stringify({udfPath:pe(t),args:ee(e)})}function Gr(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:pe(t),args:ee(e),options:ee({initialNumItems:r,id:i})})}var ws=Object.defineProperty,ks=(t,e,n)=>e in t?ws(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,te=(t,e,n)=>ks(t,typeof e!="symbol"?e+"":e,n);class Ss{constructor(){te(this,"nextQueryId"),te(this,"querySetVersion"),te(this,"querySet"),te(this,"queryIdToToken"),te(this,"identityVersion"),te(this,"auth"),te(this,"outstandingQueriesOlderThanRestart"),te(this,"outstandingAuthOlderThanRestart"),te(this,"paused"),te(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const o=pe(e),s=ge(o,n),l=this.querySet.get(s);if(l!==void 0)return l.numSubscribers+=1,{queryToken:s,modification:null,unsubscribe:()=>this.removeSubscriber(s)};{const a=this.nextQueryId++,u={id:a,canonicalizedUdfPath:o,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(s,u),this.queryIdToToken.set(a,s);const d=this.querySetVersion,h=this.querySetVersion+1,f={type:"Add",queryId:a,udfPath:o,args:[ee(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,f):this.querySetVersion=h,{queryToken:s,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:h,modifications:[f]},unsubscribe:()=>this.removeSubscriber(s)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=pe(e),i=ge(r,n),o=this.querySet.get(i);return o!==void 0?o.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const e=[];for(const i of this.querySet.values()){const o={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[ee(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(o),this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const n={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[n,void 0];this.outstandingAuthOlderThanRestart=!0;const r={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[n,r]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,o={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,o):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[o]}}}}var js=Object.defineProperty,Cs=(t,e,n)=>e in t?js(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,bt=(t,e,n)=>Cs(t,typeof e!="symbol"?e+"":e,n);class Ts{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,bt(this,"inflightRequests"),bt(this,"requestsOlderThanRestart"),bt(this,"inflightMutationsCount",0),bt(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const o=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:o,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const a of e.logLines)xt(this.logger,"info",r,i,a);const o=n.status;let s,l;if(e.success)s={success:!0,logLines:e.logLines,value:Re(e.result)},l=()=>o.onResult(s);else{const a=e.result,{errorData:u}=e;xt(this.logger,"error",r,i,a),s={success:!1,errorMessage:a,errorData:u!==void 0?Re(u):void 0,logLines:e.logLines},l=()=>o.onResult(s)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:s}):(n.status={status:"Completed",result:s,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const o=i.status;o.status==="Completed"&&o.ts.lessThanOrEqual(e)&&(o.onResolve(),n.set(r,o.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Je=Symbol.for("functionName"),Zr=Symbol.for("toReferencePath");function Rs(t){return t[Zr]??null}function As(t){return t.startsWith("function://")}function $s(t){let e;if(typeof t=="string")As(t)?e={functionHandle:t}:e={name:t};else if(t[Je])e={name:t[Je]};else{const n=Rs(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function P(t){const e=$s(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Je];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Yr(t){return{[Je]:t}}function Xr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Xr(i)}else if(r===Je){if(t.length<2){const s=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${s}\``)}const i=t.slice(0,-1).join("/"),o=t[t.length-1];return o==="default"?i:i+":"+o}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Es=Xr();var Is=Object.defineProperty,Ms=(t,e,n)=>e in t?Is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,yt=(t,e,n)=>Ms(t,typeof e!="symbol"?e+"":e,n);class Ke{constructor(e){yt(this,"queryResults"),yt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=ie(n[0]),i=P(e),o=this.queryResults.get(ge(i,r));if(o!==void 0)return Ke.queryValue(o.result)}getAllQueries(e){const n=[],r=P(e);for(const i of this.queryResults.values())i.udfPath===pe(r)&&n.push({args:i.args,value:Ke.queryValue(i.result)});return n}setQuery(e,n,r){const i=ie(n),o=P(e),s=ge(o,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:o,args:i,result:l};this.queryResults.set(s,a),this.modifiedQueries.push(s)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class qs{constructor(){yt(this,"queryResults"),yt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(s=>!n.has(s.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Ke(this.queryResults);for(const s of this.optimisticUpdates)s.update(i);const o=[];for(const[s,l]of this.queryResults){const a=r.get(s);(a===void 0||a.result!==l.result)&&o.push(s)}return o}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Ke(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){const n=this.queryResults.get(e);if(n!==void 0)return n.result}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?an(r,new mt(Ae("query",n.udfPath,r))):new Error(Ae("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var Ls=Object.defineProperty,Ps=(t,e,n)=>e in t?Ls(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ln=(t,e,n)=>Ps(t,typeof e!="symbol"?e+"":e,n);class O{constructor(e,n){ln(this,"low"),ln(this,"high"),ln(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new O(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?ei:e>=Os?Ns:new O(e%Ge|0,e/Ge|0)}toString(){return(BigInt(this.high)*BigInt(Ge)+BigInt(this.low)).toString()}equals(e){return O.isLong(e)||(e=O.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return O.isLong(e)||(e=O.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?O.fromNumber(e):new O(e.low,e.high)}}const ei=new O(0,0),ti=65536,Ge=ti*ti,Os=Ge*Ge,Ns=new O(-1,-1);var zs=Object.defineProperty,Bs=(t,e,n)=>e in t?zs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vt=(t,e,n)=>Bs(t,typeof e!="symbol"?e+"":e,n);class ni{constructor(e,n){vt(this,"version"),vt(this,"remoteQuerySet"),vt(this,"queryPath"),vt(this,"logger"),this.version={querySet:0,ts:O.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)xt(this.logger,"info","query",i,s);const o=Re(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:o,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)xt(this.logger,"info","query",i,s);const{errorData:o}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:o!==void 0?Re(o):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function cn(t){const e=Ve(t);return O.fromBytesLE(Array.from(e))}function Fs(t){const e=new Uint8Array(t.toBytesLE());return He(e)}function ri(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:cn(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:cn(t.startVersion.ts)},endVersion:{...t.endVersion,ts:cn(t.endVersion.ts)}}}}function Qs(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:Fs(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var Ds=Object.defineProperty,Us=(t,e,n)=>e in t?Ds(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,A=(t,e,n)=>Us(t,typeof e!="symbol"?e+"":e,n);const Vs=1e3,Hs=1001,Ws=1005,Js=4040;let _t;function $e(){return _t===void 0&&(_t=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(_t+performance.now())}function ii(){return`t=${Math.round(($e()-_t)/100)/10}s`}const oi={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Ks(t){if(t===void 0)return"Unknown";for(const e of Object.keys(oi))if(t.startsWith(e))return e;return"Unknown"}class Gs{constructor(e,n,r,i,o,s){this.markConnectionStateDirty=o,this.debug=s,A(this,"socket"),A(this,"connectionCount"),A(this,"_hasEverConnected",!1),A(this,"lastCloseReason"),A(this,"transitionChunkBuffer",null),A(this,"defaultInitialBackoff"),A(this,"maxBackoff"),A(this,"retries"),A(this,"serverInactivityThreshold"),A(this,"reconnectDueToServerInactivityTimeout"),A(this,"scheduledReconnect",null),A(this,"networkOnlineHandler",null),A(this,"pendingNetworkRecoveryInfo",null),A(this,"uri"),A(this,"onOpen"),A(this,"onResume"),A(this,"onMessage"),A(this,"webSocketConstructor"),A(this,"logger"),A(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=ri(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:$e()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",ii(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",ii())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){const{timeSavedMs:n}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:n}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(n/1e3)}s of waiting`)}},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let i=ri(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const s=this.assembleTransition(i);if(!s)return;i=s,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==Vs&&n.code!==Hs&&n.code!==Ws&&n.code!==Js){let i=`WebSocket closed with code ${n.code}`;n.reason&&(i+=`: ${n.reason}`),this.logger.log(i),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(i)}const r=Ks(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=Qs(e),i=JSON.stringify(r);let o=!1;try{this.socket.ws.send(i),o=!0}catch(s){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${s}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${o?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=$e(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},n);this.scheduledReconnect={timeout:i,scheduledAt:r,backoffMs:n}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){const n=$e()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-n),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(n)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=e!==null?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:$e()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:oi[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),o=i*(Math.random()-.5);return i+o}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=$e()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,o=`${Math.round(n/1e4)/100}MB`,s=n/(r/1e3),l=`${Math.round(s/1e4)/100}MB per second`;this._logVerbose(`received ${o} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${o}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${o} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function Zs(){return Ys()}function Ys(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class Ze extends Error{}Ze.prototype.name="InvalidTokenError";function Xs(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function ea(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Xs(e)}catch{return atob(e)}}function si(t,e){if(typeof t!="string")throw new Ze("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new Ze(`Invalid token specified: missing part #${n+1}`);let i;try{i=ea(r)}catch(o){throw new Ze(`Invalid token specified: invalid base64 for part #${n+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Ze(`Invalid token specified: invalid json for part #${n+1} (${o.message})`)}}var ta=Object.defineProperty,na=(t,e,n)=>e in t?ta(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,U=(t,e,n)=>na(t,typeof e!="symbol"?e+"":e,n);const ra=480*60*60*1e3,ai=2;class ia{constructor(e,n,r){U(this,"authState",{state:"noAuth"}),U(this,"configVersion",0),U(this,"syncState"),U(this,"authenticate"),U(this,"stopSocket"),U(this,"tryRestartSocket"),U(this,"pauseSocket"),U(this,"resumeSocket"),U(this,"clearAuth"),U(this,"logger"),U(this,"refreshTokenLeewaySeconds"),U(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=ai){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${ai-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const o=i-r;if(o<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let s=Math.min(ra,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},s);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return si(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const oa=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function sa(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function aa(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function la(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of oa){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(aa)}var ca=Object.defineProperty,ua=(t,e,n)=>e in t?ca(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$=(t,e,n)=>ua(t,typeof e!="symbol"?e+"":e,n);class ha{constructor(e,n,r){if($(this,"address"),$(this,"state"),$(this,"requestManager"),$(this,"webSocketManager"),$(this,"authenticationManager"),$(this,"remoteQuerySet"),$(this,"optimisticQueryResults"),$(this,"_transitionHandlerCounter",0),$(this,"_nextRequestId"),$(this,"_onTransitionFns",new Map),$(this,"_sessionId"),$(this,"firstMessageReceived",!1),$(this,"debug"),$(this,"logger"),$(this,"maxObservedTimestamp"),$(this,"connectionStateSubscribers",new Map),$(this,"nextConnectionStateSubscriberId",0),$(this,"_lastPublishedConnectionState"),$(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const p=this.connectionState();if(JSON.stringify(p)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=p;for(const g of this.connectionStateSubscribers.values())g(p)}})}),$(this,"mark",p=>{this.debug&&sa(p,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&ss(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let o=r.webSocketConstructor;if(!o&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");o=o||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Kr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Jr({verbose:r.verbose??!1});const s=e.search("://");if(s===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(s+3),a=e.substring(0,s);let u;if(a==="http")u="ws";else if(a==="https")u="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${u}://${l}/api/${Ur}/sync`;this.state=new Ss,this.remoteQuerySet=new ni(p=>this.state.queryPath(p),this.logger),this.requestManager=new Ts(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ia(this.state,{authenticate:p=>{const g=this.state.setAuth(p);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new qs,this.addOnTransitionHandler(p=>{n(p.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=Zs();const{unsavedChangesWarning:f}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(f===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else f!==!1&&window.addEventListener("beforeunload",p=>{if(this.requestManager.hasIncompleteRequests()){p.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(p||window.event).returnValue=g,g}});this.webSocketManager=new Gs(d,{onOpen:p=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...p,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new ni(x=>this.state.queryPath(x),this.logger);const[g,m]=this.state.restart();m&&this.webSocketManager.sendMessage(m),this.webSocketManager.sendMessage(g);for(const x of this.requestManager.restart())this.webSocketManager.sendMessage(x)},onResume:()=>{const[p,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),p&&this.webSocketManager.sendMessage(p);for(const m of this.requestManager.resume())this.webSocketManager.sendMessage(m)},onMessage:p=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),p.type){case"Transition":{this.observedTimestamp(p.endVersion.ts),this.authenticationManager.onTransition(p),this.remoteQuerySet.transition(p),this.state.transition(p);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{p.success&&this.observedTimestamp(p.ts);const g=this.requestManager.onResponse(p);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(p);break}case"AuthError":{this.authenticationManager.onAuthError(p);break}case"FatalError":{const g=_s(this.logger,p.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},o,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[o,s]of n){const l=this.state.queryToken(o);if(l!==null){const a={result:s,udfPath:this.state.queryPath(o),args:this.state.queryArgs(o)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(o=>{const s=this.optimisticQueryResults.rawQueryResult(o);return{token:o,modification:{kind:"Updated",result:s}}}),reflectedMutations:Array.from(e).map(([o,s])=>({requestId:o,result:s})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?si(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const i=ie(n),{modification:o,queryToken:s,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return o!==null&&this.webSocketManager.sendMessage(o),{queryToken:s,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=ie(n),i=ge(e,r);return this.optimisticQueryResults.queryResult(i)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=ie(n),i=ge(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=ie(n),i=ge(e,r);return this.state.queryJournal(i)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const i=await this.mutationInternal(e,n,r);if(!i.success)throw i.errorData!==void 0?an(i,new mt(Ae("mutation",e,i))):new Error(Ae("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:o}=this.enqueueMutation(e,n,r,i);return o}enqueueMutation(e,n,r,i){const o=ie(n);this.tryReportLongDisconnect();const s=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const h=g=>{d(g,o)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},p=this.optimisticQueryResults.applyOptimisticUpdate(h,s).map(g=>{const m=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:m===void 0?void 0:{success:!0,value:m,logLines:[]}}}});this.handleTransition({queries:p,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:s,udfPath:e,componentPath:i,args:[ee(o)]},a=this.webSocketManager.sendMessage(l),u=this.requestManager.request(l,a);return{requestId:s,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?an(r,new mt(Ae("action",e,r))):new Error(Ae("action",e,r));return r.value}async actionInternal(e,n,r){const i=ie(n),o=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const s={type:"Action",requestId:o,udfPath:e,componentPath:r,args:[ee(i)]},l=this.webSocketManager.sendMessage(s);return this.requestManager.request(s,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=la(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${Ur}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function un(t){if(typeof t!="object"||t===null||!Array.isArray(t.page)||typeof t.isDone!="boolean"||typeof t.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${t?.toString()}`);return t}var da=Object.defineProperty,fa=(t,e,n)=>e in t?da(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,li=(t,e,n)=>fa(t,typeof e!="symbol"?e+"":e,n);class pa{constructor(e,n){this.client=e,this.onTransition=n,li(this,"paginatedQuerySet",new Map),li(this,"lastTransitionTs"),this.lastTransitionTs=O.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=pe(e),o=Gr(i,n,r),s=()=>this.removePaginatedQuerySubscriber(o),l=this.paginatedQuerySet.get(o);return l?(l.numSubscribers+=1,{paginatedQueryToken:o,unsubscribe:s}):(this.paginatedQuerySet.set(o,{token:o,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(o,null,r.initialNumItems),{paginatedQueryToken:o,unsubscribe:s})}localQueryResult(e,n,r){const i=pe(e),o=Gr(i,n,r);return this.localQueryResultByToken(o)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)};let i=[],o=!1,s=!1;for(const a of r){const u=this.client.localQueryResultByToken(a);if(u===void 0){o=!0,s=!1;continue}const d=un(u);i=i.concat(d.page),s=!!d.isDone}let l;return o?l=i.length===0?"LoadingFirstPage":"LoadingMore":s?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(s=>s.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,s=>this.client.localQueryResultByToken(s)),i=r.map(s=>({token:s,modification:{kind:"Updated",result:this.localQueryResultByToken(s)}})));const o={...e,paginatedQueries:i};this.onTransition(o)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const o=un(i);if(o.isDone)return!1;this.addPageToPaginatedQuery(e,o.continueCursor,n);const s={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(s),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,o]of this.paginatedQuerySet)for(const s of this.allQueryTokens(o))if(r.has(s)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:o,pageKeyToQuery:s,pageKeys:l}=i;for(const[a,[u,d]]of o)n(s.get(u).queryToken)!==void 0&&n(s.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,u,d);for(const a of l){if(o.has(a))continue;const u=s.get(a).queryToken,d=n(u);if(!d)continue;const h=un(d);h.splitCursor&&(h.pageStatus==="SplitRecommended"||h.pageStatus==="SplitRequired"||h.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const o=e.nextPageKey++,s=e.nextPageKey++,l={cursor:i,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:null,endCursor:r}});e.pageKeyToQuery.set(o,a);const u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(s,u),e.ongoingSplits.set(n,[o,s])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),o=i.nextPageKey++,s={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:s},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(o),i.pageKeyToQuery.set(o,a),a}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const o=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const s=e.pageKeys.indexOf(n);e.pageKeys.splice(s,1,r,i),e.ongoingSplits.delete(n),o.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function ga({getCurrentValue:t,subscribe:e}){const[n,r]=C(()=>({getCurrentValue:t,subscribe:e,value:t()}));let i=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(i=t(),r({getCurrentValue:t,subscribe:e,value:i})),T(()=>{let o=!1;const s=()=>{o||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const u=t();return a.value===u?a:{...a,value:u}})},l=e(s);return s(),()=>{o=!0,l()}},[t,e]),i}var ma=Object.defineProperty,xa=(t,e,n)=>e in t?ma(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>xa(t,typeof e!="symbol"?e+"":e,n);const ba=5e3;if(typeof Xt>"u")throw new Error("Required dependency 'react' not found");function ci(t,e,n){function r(i){return wa(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(o){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${P(t)}`);return ci(t,e,o)},r}class ya{constructor(e,n){if(oe(this,"address"),oe(this,"cachedSync"),oe(this,"cachedPaginatedQueryClient"),oe(this,"listeners"),oe(this,"options"),oe(this,"closed",!1),oe(this,"_logger"),oe(this,"adminAuth"),oe(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?Kr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Jr({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new ha(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new pa(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,o=P(e);return{onUpdate:s=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(o,r,i),u=this.listeners.get(l);return u!==void 0?u.add(s):this.listeners.set(l,new Set([s])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(s),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(o,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(o,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(o,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??ba,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=P(e);return{onUpdate:o=>{const{paginatedQueryToken:s,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(s);return a!==void 0?a.add(o):this.listeners.set(s,new Set([o])),()=>{if(this.closed)return;const u=this.listeners.get(s);u.delete(o),u.size===0&&this.listeners.delete(s),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,o=P(e);return this.sync.mutation(o,r,i)}action(e,...n){const r=P(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((o,s)=>{const l=r.onUpdate(()=>{l();try{o(r.localQueryResult())}catch(a){s(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){const n=e.queries.map(i=>i.token),r=e.paginatedQueries.map(i=>i.token);this.transition([...n,...r])}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const i of r)i()}}}const hn=Xt.createContext(void 0);function va(){return dt(hn)}const _a=({client:t,children:e})=>Xt.createElement(hn.Provider,{value:t},e);function ui(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:ie(e[0]),i=typeof t=="string"?Yr(t):t,o=P(i),s=W(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(ee(r)),o,n]),a=Ca(s).query;if(a instanceof Error)throw a;return a}function wt(t){const e=typeof t=="string"?Yr(t):t,n=dt(hn);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return W(()=>ci(e,n),[n,P(e)])}function wa(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var ka=Object.defineProperty,Sa=(t,e,n)=>e in t?ka(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>Sa(t,typeof e!="symbol"?e+"":e,n);class ja{constructor(e){dn(this,"createWatch"),dn(this,"queries"),dn(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:o}=e[n];if(P(r),this.queries[n]===void 0)this.addQuery(n,r,i,o?{paginationOptions:o}:{});else{const s=this.queries[n];(P(r)!==P(s.query)||JSON.stringify(ee(i))!==JSON.stringify(ee(s.args))||JSON.stringify(o)!==JSON.stringify(s.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,o?{paginationOptions:o}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:o}=e[r],s=e[r].paginationOptions;P(i);const l=this.createWatch(i,o,s?{paginationOptions:s}:{});let a;try{a=l.localQueryResult()}catch(u){if(u instanceof Error)a=u;else throw u}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:o,paginationOptions:s}=this.queries[n],l="journal"in o?o.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...s?{paginationOptions:s}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:o}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const s=this.createWatch(n,r,{...o?{journal:o}:[],...i?{paginationOptions:i}:{}}),l=s.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:s,unsubscribe:l,...i?{paginationOptions:i}:{}}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function Ca(t){const e=va();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=W(()=>(r,i,{journal:o,paginationOptions:s})=>s?e.watchPaginatedQuery(r,i,s):e.watchQuery(r,i,o?{journal:o}:{}),[e]);return Ta(t,n)}function Ta(t,e){const[n]=C(()=>new ja(e));n.createWatch!==e&&n.setCreateWatch(e),T(()=>()=>n.destroy(),[n]);const r=W(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return ga(r)}var Ra=Symbol.for("preact-signals");function kt(){if(ce>1)ce--;else{for(var t,e=!1;Ye!==void 0;){var n=Ye;for(Ye=void 0,fn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&fi(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(fn=0,ce--,e)throw t}}function Aa(t){if(ce>0)return t();ce++;try{return t()}finally{kt()}}var w=void 0;function hi(t){var e=w;w=void 0;try{return t()}finally{w=e}}var Ye=void 0,ce=0,fn=0,St=0;function di(t){if(w!==void 0){var e=t.n;if(e===void 0||e.t!==w)return e={i:0,S:t,p:w.s,n:void 0,t:w,e:void 0,x:void 0,r:e},w.s!==void 0&&(w.s.n=e),w.s=e,t.n=e,32&w.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=w.s,e.n=void 0,w.s.n=e,w.s=e),e}}function q(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}q.prototype.brand=Ra,q.prototype.h=function(){return!0},q.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:hi(function(){var r;(r=e.W)==null||r.call(e)}))},q.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&hi(function(){var i;(i=e.Z)==null||i.call(e)}))}},q.prototype.subscribe=function(t){var e=this;return Xe(function(){var n=e.value,r=w;w=void 0;try{t(n)}finally{w=r}},{name:"sub"})},q.prototype.valueOf=function(){return this.value},q.prototype.toString=function(){return this.value+""},q.prototype.toJSON=function(){return this.value},q.prototype.peek=function(){var t=w;w=void 0;try{return this.value}finally{w=t}},Object.defineProperty(q.prototype,"value",{get:function(){var t=di(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(fn>100)throw new Error("Cycle detected");this.v=t,this.i++,St++,ce++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{kt()}}}});function E(t,e){return new q(t,e)}function fi(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function pi(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function gi(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function me(t,e){q.call(this,void 0),this.x=t,this.s=void 0,this.g=St-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}me.prototype=new q,me.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===St))return!0;if(this.g=St,this.f|=1,this.i>0&&!fi(this))return this.f&=-2,!0;var t=w;try{pi(this),w=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return w=t,gi(this),this.f&=-2,!0},me.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}q.prototype.S.call(this,t)},me.prototype.U=function(t){if(this.t!==void 0&&(q.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},me.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(me.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=di(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function pn(t,e){return new me(t,e)}function mi(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ce++;var n=w;w=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,gn(t),r}finally{w=n,kt()}}}function gn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,mi(t)}function $a(t){if(w!==this)throw new Error("Out-of-order effect");gi(this),w=t,this.f&=-2,8&this.f&&gn(this),kt()}function Ee(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ee.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ee.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,mi(this),pi(this),ce++;var t=w;return w=this,$a.bind(this,t)},Ee.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ye,Ye=this)},Ee.prototype.d=function(){this.f|=8,1&this.f||gn(this)},Ee.prototype.dispose=function(){this.d()};function Xe(t,e){var n=new Ee(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var xi,jt,Ea=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bi=[];Xe(function(){xi=this.N})();function Ie(t,e){b[t]=e.bind(null,b[t]||function(){})}function Ct(t){if(jt){var e=jt;jt=void 0,e()}jt=t&&t.S()}function yi(t){var e=this,n=t.data,r=et(n);r.value=n;var i=W(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var u=pn(function(){var p=r.value.value;return p===0?0:p===!0?"":p||""}),d=pn(function(){return!Array.isArray(u.value)&&!Qn(u.value)}),h=Xe(function(){if(this.N=vi,d.value){var p=u.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=p)}}),f=e.__$u.d;return e.__$u.d=function(){h(),f.call(this)},[d,u]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}yi.displayName="ReactiveTextNode",Object.defineProperties(q.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:yi},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Ie("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof q&&(n||(e.__np=n={}),n[i]=o,r[i]=o.peek())}}t(e)}),Ie("__r",function(t,e){if(t(e),e.type!==B){Ct();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Xe(function(){s=this},{name:o}),s.c=i,s})(function(){var i;Ea&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Ct(n)}}),Ie("__e",function(t,e,n,r){Ct(),t(e,n,r)}),Ie("diffed",function(t,e){Ct();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var o=n.U;if(o)for(var s in o){var l=o[s];l!==void 0&&!(s in r)&&(l.d(),o[s]=void 0)}else o={},n.U=o;for(var a in r){var u=o[a],d=r[a];u===void 0?(u=Ia(n,a,d,i),o[a]=u):u.o(d,i)}}}t(e)});function Ia(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,o=E(n);return{o:function(s,l){o.value=s,r=l},d:Xe(function(){this.N=vi;var s=o.value.value;r[e]!==s&&(r[e]=s,i?t[e]=s:s!=null&&(s!==!1||e[4]==="-")?t.setAttribute(e,s):t.removeAttribute(e))})}}Ie("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}}else{var s=e.__c;if(s){var l=s.__$u;l&&(s.__$u=void 0,l.d())}}t(e)}),Ie("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),H.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in t)if(s!=="__source"&&t[s]!==this.props[s])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function et(t,e){return W(function(){return E(t,e)},[])}var Ma=function(t){queueMicrotask(function(){queueMicrotask(t)})};function qa(){Aa(function(){for(var t;t=bi.shift();)xi.call(t)})}function vi(){bi.push(this)===1&&(b.requestAnimationFrame||Ma)(qa)}const I=E(!1),Tt=E(void 0),ue=E(void 0),_i=E(null);function La(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function mn(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function Pa(t,e){const n=t.title??e?.title??"Assistant";return{title:n,greeting:t.greeting??e?.welcomeMessage??`Hi! I'm ${n}. How can I help?`,locale:t.locale??e?.locale,position:t.position??e?.position,colorScheme:t.colorScheme??e?.colorScheme,hideBranding:t.hideBranding??e?.hideBranding??!1,triggerIcon:t.triggerIcon??e?.triggerIcon??"chat",triggerRadius:t.triggerRadius??e?.triggerRadius??"full",triggerLabel:t.triggerLabel??e?.triggerLabel??"Chatte mit uns",mode:t.mode??"floating",primaryColor:t.primaryColor??e?.primaryColor,accentColor:t.accentColor??e?.accentColor,fontFamily:t.fontFamily??e?.fontFamily,fontSize:t.fontSize??e?.fontSize,borderRadius:t.borderRadius??e?.borderRadius,windowWidth:t.windowWidth??e?.windowWidth,windowHeight:t.windowHeight??e?.windowHeight}}async function Oa(t,e,n,r){const i=new URL(`${t}/widget/config`);i.searchParams.set("orgSlug",e),r&&i.searchParams.set("projSlug",r);const o=await fetch(i.toString(),{signal:n});return o.ok?o.json():null}function Na(t,e,n){const[r,i]=C(null);return T(()=>{i(null);const o=n??"https://festive-mouse-978.eu-west-1.convex.cloud",s=o?mn(o):void 0;if(!s||!t)return;const l=new AbortController;async function a(u){try{const d=await Oa(u,t,l.signal,e);d&&i(d)}catch(d){if(d instanceof Error&&d.name==="AbortError")return}}return a(s),()=>{l.abort()}},[t,e,n]),r}async function xn(t,e,n){try{const r=await fetch(`${e}/widget/bootstrap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{orgSlug:t,projSlug:n}:{orgSlug:t}),credentials:"omit"});if(r.ok){const i=await r.json();return{ok:!0,token:i.token,excludePaths:i.excludePaths}}return r.status===403?{ok:!1,error:"unauthorized"}:r.status===404?{ok:!1,error:"not_found"}:r.status===429?{ok:!1,error:"rate_limited",retryAfterSec:Number(r.headers.get("Retry-After"))||60}:{ok:!1,error:"network"}}catch{return{ok:!1,error:"network"}}}function za(t,e,n,r){T(()=>{const i=r??"https://festive-mouse-978.eu-west-1.convex.cloud",o=i?mn(i):void 0;if(!o||!t||(_i.value={orgSlug:t,projSlug:e,siteUrl:o},n))return;let s=!1;return(async()=>{const l=await xn(t,o,e);if(!s)if(l.ok)ue.value=l.token;else{const a=e?`project '${t}/${e}'`:`org '${t}'`;l.error==="unauthorized"?console.error(`[JexityChat] This domain is not authorized for ${a}. Check the widget's domain rules.`):l.error==="not_found"?console.error(`[JexityChat] No active widget config found for ${a}.`):l.error==="rate_limited"?console.error(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${l.retryAfterSec??60}s.`):console.error(`[JexityChat] Bootstrap failed: ${l.error}`)}})(),()=>{s=!0}},[t,e,n,r])}const wi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",attachImagesAriaLabel:"Attach images",attachComingSoon:"File attachments — coming soon",removeAttachmentAriaLabel:"Remove attachment",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",errorRateLimited:"Too many messages. Try again in {seconds}s.",errorSessionNoToken:"Could not connect to chat. Check your connection and try again.",errorSessionUnauthorized:"This chat is not authorised on this page. Please reload.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resuming conversation…",startingConversation:"Starting conversation…",sessionNotFound:"Your previous session was not found. Starting a new conversation.",startNewConversation:"Start new conversation",chatWith:"Chat with {title}",haveReferenceNumber:"Have a reference number?",referencePlaceholder:"e.g. JEX-A3B7C2",resume:"Resume",howCanWeHelp:"How can we help?",getInstantHelp:"Get instant help",submitTicket:"Submit a ticket",replyByEmail:"We'll reply by email",ticketSubmitted:"Ticket submitted",yourReferenceNumber:"Your reference number:",sentToEmailHint:"We've sent it to your email. Use this number to follow up.",done:"Done",submittingTicket:"Submitting your ticket…",yourName:"Your name",yourEmail:"Your email",submit:"Submit",back:"Go back",escalationFormTitle:"Leave your details",escalationSubtitle:"Our team will get back to you by email so you don’t have to wait here.",escalationNameLabel:"Your name",escalationEmailLabel:"Your email",escalationSubmit:"Send to team",escalationSubmitting:"Sending…",escalationSubmitted:"Request submitted",escalationConsent:"We’ll only use your email to respond to this conversation.",escalationSkip:"Skip, I’ll wait here",escalationPromptTitle:"Talk to our team",escalationPromptSubtitle:"We can notify you by email when our team replies.",escalationPromptSubmit:"Leave details",escalationSubmitFailed:"Failed to submit. Please try again.",sessionNotFoundPrompt:"Session not found. Would you like to start a new conversation?",sessionLocked:"For your privacy, this conversation was closed after a period of inactivity. Enter your reference to resume, or start a new conversation.",sessionResolved:"This conversation has been resolved.",tryAgain:"Try again",goBack:"Go back",somethingWentWrong:"Something went wrong",fabLabel:"Chat with us",chatNoLongerAvailable:"This chat is no longer available.",talkToHuman:"Talk to human",talkToHumanAria:"Talk to a human agent",handoffPending:"Connecting you to a human agent…",handoffFailed:"Could not request a human agent. Try again.",handoffRateLimited:"You requested an agent recently. Please wait before trying again.",resumeListLabel:"Continue conversation",resumeListTimestamp:"{minutes}m ago",noticeAgentJoined:"{name} has joined the conversation.",noticeHumanRequested:"You requested to speak with a human agent.",noticeHumanRequestedForm:"You requested to speak with a human agent. Please share your contact details below.",noticeEscalationConfirmed:`Thank you {name}! A human agent will be available soon.
3
+ We will contact you at {email} when an agent is ready.
4
+
5
+ Your reference: **{ref}**
6
+ Use it to resume this conversation from any device.`,noticeMessageReceived:"Your message has been received. A team member will respond shortly.",noticeAgentHandling:"Your conversation is with a human agent who will respond shortly.",replyTo:"Reply to {name}",sourcesCountOne:"{count} source",sourcesCountOther:"{count} sources"},Ba={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",attachImagesAriaLabel:"Bilder anhängen",attachComingSoon:"Dateianhänge — bald verfügbar",removeAttachmentAriaLabel:"Anhang entfernen",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",errorRateLimited:"Zu viele Nachrichten. Bitte in {seconds} Sek. erneut versuchen.",errorSessionNoToken:"Verbindung zum Chat fehlgeschlagen. Bitte Internet prüfen und erneut versuchen.",errorSessionUnauthorized:"Dieser Chat ist auf dieser Seite nicht autorisiert. Bitte neu laden.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch wird fortgesetzt…",startingConversation:"Konversation wird gestartet…",sessionNotFound:"Ihre vorherige Sitzung wurde nicht gefunden. Ein neues Gespräch wird gestartet.",startNewConversation:"Neues Gespräch beginnen",chatWith:"Chatte mit {title}",haveReferenceNumber:"Hast du eine Referenznummer?",referencePlaceholder:"z.B. JEX-A3B7C2",resume:"Fortsetzen",howCanWeHelp:"Wie können wir helfen?",getInstantHelp:"Soforthilfe erhalten",submitTicket:"Ticket einreichen",replyByEmail:"Wir antworten per E-Mail",ticketSubmitted:"Ticket eingereicht",yourReferenceNumber:"Deine Referenznummer:",sentToEmailHint:"Wir haben sie an deine E-Mail gesendet. Verwende diese Nummer für Rückfragen.",done:"Fertig",submittingTicket:"Dein Ticket wird übermittelt…",yourName:"Dein Name",yourEmail:"Deine E-Mail",submit:"Absenden",back:"Zurück",escalationFormTitle:"Hinterlassen Sie Ihre Daten",escalationSubtitle:"Unser Team meldet sich per E-Mail bei Ihnen — Sie müssen nicht hier warten.",escalationNameLabel:"Ihr Name",escalationEmailLabel:"Ihre E-Mail",escalationSubmit:"An Team senden",escalationSubmitting:"Wird gesendet…",escalationSubmitted:"Anfrage gesendet",escalationConsent:"Wir verwenden Ihre E-Mail nur, um auf diese Unterhaltung zu antworten.",escalationSkip:"Überspringen, ich warte hier",escalationPromptTitle:"Sprechen Sie mit unserem Team",escalationPromptSubtitle:"Wir benachrichtigen Sie per E-Mail, wenn wir antworten.",escalationPromptSubmit:"Daten hinterlassen",escalationSubmitFailed:"Senden fehlgeschlagen. Bitte versuche es erneut.",sessionNotFoundPrompt:"Sitzung nicht gefunden. Möchten Sie ein neues Gespräch beginnen?",sessionLocked:"Aus Datenschutzgründen wurde dieses Gespräch nach einer Inaktivitätszeit geschlossen. Geben Sie Ihre Referenz ein, um fortzufahren, oder beginnen Sie ein neues Gespräch.",sessionResolved:"Diese Unterhaltung wurde abgeschlossen.",tryAgain:"Erneut versuchen",goBack:"Zurück",somethingWentWrong:"Etwas ist schiefgelaufen",fabLabel:"Chatte mit uns",chatNoLongerAvailable:"Dieser Chat ist nicht mehr verfügbar.",talkToHuman:"Mit Mitarbeiter sprechen",talkToHumanAria:"Mit einem menschlichen Mitarbeiter sprechen",handoffPending:"Sie werden mit einem Mitarbeiter verbunden…",handoffFailed:"Anfrage konnte nicht gesendet werden. Erneut versuchen.",handoffRateLimited:"Sie haben kürzlich einen Mitarbeiter angefragt. Bitte warten Sie.",resumeListLabel:"Unterhaltung fortsetzen",resumeListTimestamp:"vor {minutes} Min.",noticeAgentJoined:"{name} ist der Unterhaltung beigetreten.",noticeHumanRequested:"Sie haben darum gebeten, mit einem Mitarbeiter zu sprechen.",noticeHumanRequestedForm:"Sie haben darum gebeten, mit einem Mitarbeiter zu sprechen. Bitte teilen Sie unten Ihre Kontaktdaten mit.",noticeEscalationConfirmed:`Vielen Dank, {name}! Ein Mitarbeiter wird in Kürze verfügbar sein.
7
+ Wir kontaktieren Sie unter {email}, sobald ein Mitarbeiter bereit ist.
8
+
9
+ Ihre Referenz: **{ref}**
10
+ Verwenden Sie sie, um diese Unterhaltung auf jedem Gerät fortzusetzen.`,noticeMessageReceived:"Ihre Nachricht ist eingegangen. Ein Mitarbeiter wird in Kürze antworten.",noticeAgentHandling:"Ihre Unterhaltung wird von einem menschlichen Mitarbeiter betreut, der in Kürze antwortet.",replyTo:"Antworten an {name}",sourcesCountOne:"{count} Quelle",sourcesCountOther:"{count} Quellen"},Fa=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],Qa="de",Da="jex-locale",bn=E("de"),Ua={en:wi,de:Ba};function R(){return Ua[bn.value]??wi}function yn(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return Fa.some(r=>r.value===e)?e:null}function ki(t){const e=yn(t);if(e)return e;try{const n=yn(localStorage.getItem(Da));if(n)return n}catch{}if(typeof navigator<"u"){const n=yn(navigator.language);if(n)return n}return Qa}function Va(t){T(()=>{function e(n){const r=t??window.location.origin;if(n.origin!==r||n.data?.type!=="jexity:config")return;const{locale:i}=n.data.payload;i&&(bn.value=ki(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const Si="jex-session-history",ji=Si,Ci=900*1e3,N=E([]),xe=E(null),Ti=pn(()=>N.value.length>0),tt=E(null);function Ha(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function Wa(t){try{const e=sessionStorage.getItem(ji);if(!e)return[];const n=JSON.parse(e);return n.v!==1||!Array.isArray(n.entries)?[]:n.entries.filter(r=>t-r.lastActivityAt<=Ci)}catch{return[]}}function Rt(t){try{const e={v:1,entries:t};sessionStorage.setItem(ji,JSON.stringify(e))}catch{}}function Ja(){const t=Date.now(),e=Wa(t);N.value=e,Rt(e),xe.value=e.length>0?e[e.length-1].ref:null}function Ri(){const t=Ha(),e=Date.now(),n=[...N.value,{ref:t,startedAt:e,lastActivityAt:e}];return N.value=n,xe.value=t,Rt(n),t}function Ai(t){const e=Date.now(),n=N.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);N.value=n,xe.value=t,Rt(n)}function vn(t){if(!t)return;const e=Date.now(),n=N.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);N.value=n,Rt(n)}const z=E($i());function $i(){return Ti.value?[{id:"home"}]:[{id:"chat"}]}function Ka(){z.value=$i()}const Ga=E("screen");function be(t){z.value=[...z.value,t]}function At(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function _n(t){z.value=[...z.value.slice(0,-1),t]}const Za=6e4,nt=E(!1),wn=E(!1),kn=new Set;function Ya(t){return kn.add(t),()=>{kn.delete(t)}}function Xa(){const t=xe.value;return t?N.value.find(n=>n.ref===t)?.lastActivityAt??null:null}function el(t){const e=Xa();return e===null?!1:Date.now()-e>t}function Ei(){if(!(nt.value&&N.value.length===0)){N.value=[],xe.value=null;try{sessionStorage.removeItem(Si)}catch(t){console.warn("[JexityChat] Idle-lock storage clear failed:",t)}for(const t of kn)try{t()}catch(e){console.warn("[JexityChat] Lock reset callback threw:",e)}z.value=[{id:"home"}],nt.value=!0}}function Sn(){nt.value&&(nt.value=!1)}function tl(t=Ci){let e=null;const n=()=>{if(document.visibilityState==="hidden"){e=Date.now();return}e!==null&&Date.now()-e>t&&Ei(),e=null};document.addEventListener("visibilitychange",n);const r=setInterval(()=>{wn.value||el(t)&&Ei()},Za);return()=>{document.removeEventListener("visibilitychange",n),clearInterval(r),e=null}}function nl(t){const e={},{primaryColor:n,theme:r}=t;if(n&&(e["--jex-primary"]=n,e["--jex-bg-trigger"]=n,e["--jex-bg-header"]=n,e["--jex-bg-msg-user"]=n,e["--jex-bg-send-btn"]=n),t.accentColor&&(e["--jex-accent"]=t.accentColor),r?.bg){const i=r.bg;i.trigger&&(e["--jex-bg-trigger"]=i.trigger),i.header&&(e["--jex-bg-header"]=i.header),i.msgUser&&(e["--jex-bg-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-bg-msg-bot"]=i.msgBot),i.window&&(e["--jex-bg-window"]=i.window),i.sendBtn&&(e["--jex-bg-send-btn"]=i.sendBtn)}if(r?.text){const i=r.text;i.header&&(e["--jex-text-header"]=i.header),i.msgUser&&(e["--jex-text-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-text-msg-bot"]=i.msgBot),i.main&&(e["--jex-text-main"]=i.main),i.muted&&(e["--jex-text-muted"]=i.muted)}if(r?.border){const i=r.border;i.window&&(e["--jex-border-window"]=i.window),i.input&&(e["--jex-border-input"]=i.input)}return t.fontFamily&&(e["--jex-font-family"]=t.fontFamily),t.fontSize&&(e["--jex-font-size"]=`${t.fontSize}px`),t.borderRadius&&(e["--jex-radius"]=t.borderRadius),t.windowWidth&&(e["--jex-window-width"]=`${t.windowWidth}px`),t.windowHeight&&(e["--jex-window-height"]=`${t.windowHeight}px`),Object.keys(e).length>0?e:void 0}function jn({size:t=24}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M12 8V4H8"}),c("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),c("path",{d:"M2 14h2"}),c("path",{d:"M20 14h2"}),c("path",{d:"M15 13v2"}),c("path",{d:"M9 13v2"})]})}function rl(){const t=R();return z.value.length>1?c("button",{class:"jex-header-back",onClick:At,"aria-label":t.back||"Go back",children:c("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"m15 18-6-6 6-6"})})}):c(jn,{size:24})}function il({title:t}){const e=R();return c("div",{class:"jex-header-info",children:[c("h3",{children:t}),c("p",{children:e.statusOnline})]})}function Ii({size:t=28}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M18 6 6 18"}),c("path",{d:"m6 6 12 12"})]})}function ol(){const t=R();return c("button",{class:"jex-header-close",type:"button",onClick:()=>{I.value=!1},"aria-label":t.closeChatAriaLabel,title:t.closeChatAriaLabel,children:c(Ii,{size:18})})}function sl({action:t,showClose:e=!0}){return!t&&!e?null:c("div",{class:"jex-header-right",children:[t,e&&c(ol,{})]})}function Mi({title:t,rightAction:e,showClose:n=!0}){return c("header",{class:"jex-chat-header",children:[c(rl,{}),c(il,{title:t}),c(sl,{action:e,showClose:n})]})}function al({size:t=14}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"})})}function qi(){return c("div",{class:"jex-widget-footer",children:c("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[c(al,{size:14}),c("span",{children:["Powered by ",c("strong",{children:"Jexity"})]})]})})}function Li({size:t=28}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function ll({size:t=24,...e}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...e,children:c("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})})}const cl={chat:c(Li,{size:28}),bot:c(jn,{size:28}),sparkles:c(ll,{size:28})},ul={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function hl({radius:t="full",iconOption:e="chat",label:n}){const r=R(),i=n??r.fabLabel,o=i!=="";return c("button",{class:`jex-floating-button ${!I.value&&o?"jex-has-label":""}`,style:{borderRadius:ul[t]??"9999px"},onClick:()=>{I.value=!I.value},"aria-label":I.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:I.value?c(Ii,{size:28}):c("div",{class:"jex-fab-inner",children:[cl[e],o&&c("span",{class:"jex-fab-label",children:i})]})})}function dl({title:t,onStartFresh:e,onResetSession:n}){const r=R(),[i,o]=C("");function s(){Sn(),tt.value="fresh",n(),e(),be({id:"chat"})}function l(u){Sn(),tt.value="resume",n(),Ai(u),be({id:"chat"})}function a(u){u.preventDefault();const d=i.trim().toUpperCase();d&&(Sn(),tt.value="resume",n(),Ai(d),be({id:"chat"}))}return c("div",{class:"jex-home",children:[nt.value&&c("div",{class:"jex-session-prompt",role:"status",children:c("div",{class:"jex-session-prompt-text",children:r.sessionLocked})}),c("div",{class:"jex-home-hero",children:[c("div",{class:"jex-home-avatar",children:[c(Li,{size:24}),c("span",{class:"jex-home-status-dot"})]}),c("div",{class:"jex-home-hero-text",children:[c("h2",{class:"jex-home-title",children:t}),c("span",{class:"jex-home-status",children:r.statusOnline})]})]}),c("form",{class:"jex-home-lookup",onSubmit:a,children:[c("input",{class:"jex-home-lookup-input",type:"text",placeholder:r.referencePlaceholder,value:i,onInput:u=>{o(u.currentTarget.value)}}),c("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!i.trim(),children:r.resume})]}),c("div",{class:"jex-home-actions",children:[N.value.length>0&&c("div",{class:"jex-home-history",children:N.value.slice().reverse().map(u=>c("button",{class:"jex-home-resume-card",onClick:()=>{l(u.ref)},children:[c("div",{class:"jex-home-resume-top",children:[c("span",{class:"jex-home-resume-label",children:r.resumeListLabel}),c("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:c("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),c("span",{class:"jex-home-resume-ref",children:u.ref}),c("span",{class:"jex-home-resume-meta",children:r.resumeListTimestamp.replace("{minutes}",String(Math.max(1,Math.round((Date.now()-u.lastActivityAt)/6e4))))})]},u.ref))}),c("button",{class:"jex-home-new-btn",onClick:s,children:N.value.length>0?r.startNewConversation:r.chatWith.replace("{title}",t)})]})]})}function fl({title:t}){const e=R();return c("div",{class:"jex-selection",children:[c("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),c("div",{class:"jex-selection-options",children:[c("button",{class:"jex-selection-option",onClick:()=>be({id:"chat"}),children:[c("span",{class:"jex-selection-icon",children:"💬"}),c("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),c("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),c("button",{class:"jex-selection-option",onClick:()=>be({id:"form"}),children:[c("span",{class:"jex-selection-icon",children:"📝"}),c("span",{class:"jex-selection-label",children:e.submitTicket}),c("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}const pl=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const Pi=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const gl=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Oi=t=>{const e=gl(t);return e.charAt(0).toUpperCase()+e.slice(1)};var ml={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};const xl=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const bl=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,children:i,iconNode:o,class:s="",...l})=>Q("svg",{...ml,width:String(e),height:e,stroke:t,"stroke-width":r?Number(n)*24/Number(e):n,class:["lucide",s].join(" "),...!i&&!xl(l)&&{"aria-hidden":"true"},...l},[...o.map(([a,u])=>Q(a,u)),...Y(i)]);const yl=(t,e)=>{const n=({class:r="",className:i="",children:o,...s})=>Q(bl,{...s,iconNode:e,class:pl(`lucide-${Pi(Oi(t))}`,`lucide-${Pi(t)}`,r,i)},o);return n.displayName=Oi(t),n};const vl=yl("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]);function Cn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ye=Cn();function Ni(t){ye=t}var ve={exec:()=>null};function _(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(L.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,e)};return r}var _l=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),L={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},wl=/^(?:[ \t]*(?:\n|$))+/,kl=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,rt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,jl=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Tn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Bi=_(zi).replace(/bull/g,Tn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Cl=_(zi).replace(/bull/g,Tn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Rn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Tl=/^[^\n]+/,An=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Rl=_(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",An).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Al=_(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Tn).getRegex(),$t="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",$n=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,$l=_("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",$n).replace("tag",$t).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Fi=_(Rn).replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex(),El=_(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Fi).getRegex(),En={blockquote:El,code:kl,def:Rl,fences:Sl,heading:jl,hr:rt,html:$l,lheading:Bi,list:Al,newline:wl,paragraph:Fi,table:ve,text:Tl},Qi=_("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex(),Il={...En,lheading:Cl,table:Qi,paragraph:_(Rn).replace("hr",rt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Qi).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex()},Ml={...En,html:_(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",$n).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ve,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:_(Rn).replace("hr",rt).replace("heading",` *#{1,6} *[^
11
+ ]`).replace("lheading",Bi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},ql=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ll=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Di=/^( {2,}|\\)\n(?!\s*$)/,Pl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Me=/[\p{P}\p{S}]/u,Et=/[\s\p{P}\p{S}]/u,In=/[^\s\p{P}\p{S}]/u,Ol=_(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Et).getRegex(),Ui=/(?!~)[\p{P}\p{S}]/u,Nl=/(?!~)[\s\p{P}\p{S}]/u,zl=/(?:[^\s\p{P}\p{S}]|~)/u,Bl=_(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",_l?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Vi=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Fl=_(Vi,"u").replace(/punct/g,Me).getRegex(),Ql=_(Vi,"u").replace(/punct/g,Ui).getRegex(),Hi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Dl=_(Hi,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Me).getRegex(),Ul=_(Hi,"gu").replace(/notPunctSpace/g,zl).replace(/punctSpace/g,Nl).replace(/punct/g,Ui).getRegex(),Vl=_("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Me).getRegex(),Hl=_(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Me).getRegex(),Wl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Jl=_(Wl,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,Et).replace(/punct/g,Me).getRegex(),Kl=_(/\\(punct)/,"gu").replace(/punct/g,Me).getRegex(),Gl=_(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Zl=_($n).replace("(?:-->|$)","-->").getRegex(),Yl=_("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Zl).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),It=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Xl=_(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",It).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Wi=_(/^!?\[(label)\]\[(ref)\]/).replace("label",It).replace("ref",An).getRegex(),Ji=_(/^!?\[(ref)\](?:\[\])?/).replace("ref",An).getRegex(),ec=_("reflink|nolink(?!\\()","g").replace("reflink",Wi).replace("nolink",Ji).getRegex(),Ki=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mn={_backpedal:ve,anyPunctuation:Kl,autolink:Gl,blockSkip:Bl,br:Di,code:Ll,del:ve,delLDelim:ve,delRDelim:ve,emStrongLDelim:Fl,emStrongRDelimAst:Dl,emStrongRDelimUnd:Vl,escape:ql,link:Xl,nolink:Ji,punctuation:Ol,reflink:Wi,reflinkSearch:ec,tag:Yl,text:Pl,url:ve},tc={...Mn,link:_(/^!?\[(label)\]\((.*?)\)/).replace("label",It).getRegex(),reflink:_(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",It).getRegex()},qn={...Mn,emStrongRDelimAst:Ul,emStrongLDelim:Ql,delLDelim:Hl,delRDelim:Jl,url:_(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Ki).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:_(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Ki).getRegex()},nc={...qn,br:_(Di).replace("{2,}","*").getRegex(),text:_(qn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mt={normal:En,gfm:Il,pedantic:Ml},it={normal:Mn,gfm:qn,breaks:nc,pedantic:tc},rc={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Gi=t=>rc[t];function ne(t,e){if(e){if(L.escapeTest.test(t))return t.replace(L.escapeReplace,Gi)}else if(L.escapeTestNoEncode.test(t))return t.replace(L.escapeReplaceNoEncode,Gi);return t}function Zi(t){try{t=encodeURI(t).replace(L.percentDecode,"%")}catch{return null}return t}function Yi(t,e){let n=t.replace(L.findPipe,(o,s,l)=>{let a=!1,u=s;for(;--u>=0&&l[u]==="\\";)a=!a;return a?"|":" |"}),r=n.split(L.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(L.slashPipe,"|");return r}function ot(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r&&t.charAt(r-i-1)===e;)i++;return t.slice(0,r-i)}function ic(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function oc(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function Xi(t,e,n,r,i){let o=e.href,s=e.title||null,l=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function sc(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
4
12
  `).map(o=>{let s=o.match(n.other.beginningSpace);if(s===null)return o;let[l]=s;return l.length>=i.length?o.slice(i.length):o}).join(`
5
- `)}var Pt=class{options;rules;lexer;constructor(t){this.options=t||ye}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:ot(n,`
13
+ `)}var qt=class{options;rules;lexer;constructor(t){this.options=t||ye}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:ot(n,`
6
14
  `)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=sc(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=ot(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:ot(e[0],`
7
15
  `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=ot(e[0],`
8
16
  `).split(`
@@ -18,14 +26,14 @@ ${d}`:d;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
18
26
  `);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let o=this.rules.other.listItemRegex(n),s=!1;for(;t;){let a=!1,u="",d="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;u=e[0],t=t.substring(u.length);let h=oc(e[2].split(`
19
27
  `,1)[0],e[1].length),f=t.split(`
20
28
  `,1)[0],p=!h.trim(),g=0;if(this.options.pedantic?(g=2,d=h.trimStart()):p?g=e[1].length+1:(g=h.search(this.rules.other.nonSpaceChar),g=g>4?1:g,d=h.slice(g),g+=e[1].length),p&&this.rules.other.blankLine.test(f)&&(u+=f+`
21
- `,t=t.substring(f.length+1),a=!0),!a){let m=this.rules.other.nextBulletRegex(g),x=this.rules.other.hrRegex(g),v=this.rules.other.fencesBeginRegex(g),y=this.rules.other.headingBeginRegex(g),L=this.rules.other.htmlBeginRegex(g),V=this.rules.other.blockquoteBeginRegex(g);for(;t;){let K=t.split(`
22
- `,1)[0],F;if(f=K,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),F=f):F=f.replace(this.rules.other.tabCharGlobal," "),v.test(f)||y.test(f)||L.test(f)||V.test(f)||m.test(f)||x.test(f))break;if(F.search(this.rules.other.nonSpaceChar)>=g||!f.trim())d+=`
29
+ `,t=t.substring(f.length+1),a=!0),!a){let m=this.rules.other.nextBulletRegex(g),x=this.rules.other.hrRegex(g),v=this.rules.other.fencesBeginRegex(g),y=this.rules.other.headingBeginRegex(g),M=this.rules.other.htmlBeginRegex(g),V=this.rules.other.blockquoteBeginRegex(g);for(;t;){let G=t.split(`
30
+ `,1)[0],F;if(f=G,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),F=f):F=f.replace(this.rules.other.tabCharGlobal," "),v.test(f)||y.test(f)||M.test(f)||V.test(f)||m.test(f)||x.test(f))break;if(F.search(this.rules.other.nonSpaceChar)>=g||!f.trim())d+=`
23
31
  `+F.slice(g);else{if(p||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||v.test(h)||y.test(h)||x.test(h))break;d+=`
24
- `+f}p=!f.trim(),u+=K+`
25
- `,t=t.substring(K.length+1),h=F.slice(g)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(s=!0)),i.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),i.raw+=u}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let a of i.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(a.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};a.checked=d.checked,i.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}if(!i.loose){let u=a.tokens.filter(h=>h.type==="space"),d=u.length>0&&u.some(h=>this.rules.other.anyLine.test(h.raw));i.loose=d}}if(i.loose)for(let a of i.items){a.loose=!0;for(let u of a.tokens)u.type==="text"&&(u.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Yi(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
32
+ `+f}p=!f.trim(),u+=G+`
33
+ `,t=t.substring(G.length+1),h=F.slice(g)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(s=!0)),i.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),i.raw+=u}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let a of i.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let u=this.rules.other.listTaskCheckbox.exec(a.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};a.checked=d.checked,i.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}if(!i.loose){let u=a.tokens.filter(h=>h.type==="space"),d=u.length>0&&u.some(h=>this.rules.other.anyLine.test(h.raw));i.loose=d}}if(i.loose)for(let a of i.items){a.loose=!0;for(let u of a.tokens)u.type==="text"&&(u.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Yi(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
26
34
  `):[],o={type:"table",raw:e[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(Yi(s,o.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:o.align[a]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
27
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=ot(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ic(e[2],"()");if(o===-2)return;if(o>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Xi(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[r.toLowerCase()];if(!i){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return Xi(n,i,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,l=i,a=0,u=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,e=e.slice(-1*t.length+i);(r=u.exec(e))!=null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){l+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+s)%3)){a+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l+a);let d=[...r[0]][0].length,h=t.slice(0,i+r.index+d+s);if(Math.min(i,s)%2){let p=h.slice(1,-1);return{type:"em",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,l=i,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+i);(r=a.exec(e))!=null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))continue;if(r[3]||r[4]){l+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l);let u=[...r[0]][0].length,d=t.slice(0,i+r.index+u+s),h=d.slice(i,-i);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},J=class zn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ye,this.options.tokenizer=this.options.tokenizer||new Pt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:M,block:Lt.normal,inline:it.normal};this.options.pedantic?(n.block=Lt.pedantic,n.inline=it.pedantic):this.options.gfm&&(n.block=Lt.gfm,this.options.breaks?n.inline=it.breaks:n.inline=it.gfm),this.tokenizer.rules=n}static get rules(){return{block:Lt,inline:it}}static lex(e,n){return new zn(n).lex(e)}static lexInline(e,n){return new zn(n).inlineTokens(e)}lex(e){e=e.replace(M.carriageReturn,`
28
- `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(M.tabCharGlobal," ").replace(M.spaceLine,""));e;){let i;if(this.options.extensions?.block?.some(s=>(i=s.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let s=n.at(-1);i.raw.length===1&&s!==void 0?s.raw+=`
35
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=ot(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=ic(e[2],"()");if(o===-2)return;if(o>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Xi(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[r.toLowerCase()];if(!i){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return Xi(n,i,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,l=i,a=0,u=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,e=e.slice(-1*t.length+i);(r=u.exec(e))!=null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){l+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+s)%3)){a+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l+a);let d=[...r[0]][0].length,h=t.slice(0,i+r.index+d+s);if(Math.min(i,s)%2){let p=h.slice(1,-1);return{type:"em",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,l=i,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+i);(r=a.exec(e))!=null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))continue;if(r[3]||r[4]){l+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l);let u=[...r[0]][0].length,d=t.slice(0,i+r.index+u+s),h=d.slice(i,-i);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},J=class zn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ye,this.options.tokenizer=this.options.tokenizer||new qt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:L,block:Mt.normal,inline:it.normal};this.options.pedantic?(n.block=Mt.pedantic,n.inline=it.pedantic):this.options.gfm&&(n.block=Mt.gfm,this.options.breaks?n.inline=it.breaks:n.inline=it.gfm),this.tokenizer.rules=n}static get rules(){return{block:Mt,inline:it}}static lex(e,n){return new zn(n).lex(e)}static lexInline(e,n){return new zn(n).inlineTokens(e)}lex(e){e=e.replace(L.carriageReturn,`
36
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(L.tabCharGlobal," ").replace(L.spaceLine,""));e;){let i;if(this.options.extensions?.block?.some(s=>(i=s.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let s=n.at(-1);i.raw.length===1&&s!==void 0?s.raw+=`
29
37
  `:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let s=n.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
30
38
  `)?"":`
31
39
  `)+i.raw,s.text+=`
@@ -38,7 +46,7 @@ ${d}`:d;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
38
46
  `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(i),r=o.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let s=n.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
39
47
  `)?"":`
40
48
  `)+i.raw,s.text+=`
41
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(i);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,i=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)a.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,l="";for(;e;){s||(l=""),s=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=n.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let u=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(u)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),s=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},Mt=class{options;parser;constructor(t){this.options=t||ye}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(M.notSpaceStart)?.[0],i=t.replace(M.endingNewline,"")+`
49
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):n.push(i);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,i=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)a.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,l="";for(;e;){s||(l=""),s=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=n.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let u=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(u)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),s=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},Lt=class{options;parser;constructor(t){this.options=t||ye}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(L.notSpaceStart)?.[0],i=t.replace(L.endingNewline,"")+`
42
50
  `;return r?'<pre><code class="language-'+ne(r)+'">'+(n?i:ne(i,!0))+`</code></pre>
43
51
  `:"<pre><code>"+(n?i:ne(i,!0))+`</code></pre>
44
52
  `}blockquote({tokens:t}){return`<blockquote>
@@ -56,7 +64,7 @@ ${this.parser.parse(t)}</blockquote>
56
64
  `}tablerow({text:t}){return`<tr>
57
65
  ${t}</tr>
58
66
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
59
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${ne(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),i=Zi(t);if(i===null)return r;t=i;let o='<a href="'+t+'"';return e&&(o+=' title="'+ne(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Zi(t);if(i===null)return ne(n);t=i;let o=`<img src="${t}" alt="${ne(n)}"`;return e&&(o+=` title="${ne(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ne(t.text)}},Mn=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},G=class Bn{options;renderer;textRenderer;constructor(e){this.options=e||ye,this.options.renderer=this.options.renderer||new Mt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Mn}static parse(e,n){return new Bn(n).parse(e)}static parseInline(e,n){return new Bn(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=l||"";continue}}let o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let o=e[i];if(this.options.extensions?.renderers?.[o.type]){let l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=l||"";continue}}let s=o;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},st=class{options;block;constructor(t){this.options=t||ye}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?J.lex:J.lexInline}provideParser(){return this.block?G.parse:G.parseInline}},ac=class{defaults=Cn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=G;Renderer=Mt;TextRenderer=Mn;Lexer=J;Tokenizer=Pt;Hooks=st;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=e.renderers[i.name];o?e.renderers[i.name]=function(...s){let l=i.renderer.apply(this,s);return l===!1&&(l=o.apply(this,s)),l}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[i.level];o?o.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new Mt(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,l=n.renderer[s],a=i[s];i[s]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Pt(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,l=n.tokenizer[s],a=i[s];i[s]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new st;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,l=n.hooks[s],a=i[s];st.passThroughHooks.has(o)?i[s]=u=>{if(this.defaults.async&&st.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await l.call(i,u);return a.call(i,h)})();let d=l.call(i,u);return a.call(i,d)}:i[s]=(...u)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(i,u);return h===!1&&(h=await a.apply(i,u)),h})();let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let l=[];return l.push(o.call(this,s)),i&&(l=l.concat(i.call(this,s))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return J.lex(t,e??this.defaults)}parser(t,e){return G.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(e):e,l=await(i.hooks?await i.hooks.provideLexer():t?J.lex:J.lexInline)(s,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let u=await(i.hooks?await i.hooks.provideParser():t?G.parse:G.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(u):u})().catch(o);try{i.hooks&&(e=i.hooks.preprocess(e));let s=(i.hooks?i.hooks.provideLexer():t?J.lex:J.lexInline)(e,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():t?G.parse:G.parseInline)(s,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(s){return o(s)}}}onError(t,e){return n=>{if(n.message+=`
60
- Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+ne(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},_e=new ac;function k(t,e){return _e.parse(t,e)}k.options=k.setOptions=function(t){return _e.setOptions(t),k.defaults=_e.defaults,Ni(k.defaults),k},k.getDefaults=Cn,k.defaults=ye,k.use=function(...t){return _e.use(...t),k.defaults=_e.defaults,Ni(k.defaults),k},k.walkTokens=function(t,e){return _e.walkTokens(t,e)},k.parseInline=_e.parseInline,k.Parser=G,k.parser=G.parse,k.Renderer=Mt,k.TextRenderer=Mn,k.Lexer=J,k.lexer=J.lex,k.Tokenizer=Pt,k.Hooks=st,k.parse=k,k.options,k.setOptions,k.use,k.walkTokens,k.parseInline,G.parse,J.lex,k.setOptions({breaks:!0,gfm:!0});function lc({text:t}){const e=W(()=>{if(!t)return"";const n=k.parse(t);return typeof n=="string"?n:""},[t]);return c("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}const Pe=A("");function cc(t){if(!t)return;const e=t.trim().split(/\s+/)[0];if(!e)return;const n=`@${e} `,r=Pe.value;r.includes(n)||r.includes(`@${e}`)||(Pe.value=r.trimStart()?`${n}${r.trimStart()}`:n)}const at=A(null),eo=A(Date.now()),se=A([]),uc=4,hc=8*1024*1024;function dc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function fc(t){const e=Array.from(t).filter(i=>i.type.startsWith("image/")&&i.size<=hc);if(e.length===0)return;const n=uc-se.value.length;if(n<=0)return;const r=e.slice(0,n).map(i=>({id:dc(),file:i,previewUrl:URL.createObjectURL(i)}));se.value=[...se.value,...r]}function pc(t){const e=se.value.find(n=>n.id===t);e&&URL.revokeObjectURL(e.previewUrl),se.value=se.value.filter(n=>n.id!==t)}function gc(){for(const t of se.value)URL.revokeObjectURL(t.previewUrl);se.value=[]}function to(t,e){const n={get(r,i){if(typeof i=="string"){const o=[...e,i];return to(t,o)}else if(i===Zr){if(e.length<1){const o=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${o}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const mc=()=>to("components",[]),Me=Es;mc();function xc({sessionId:t,visitorId:e,ensureSession:n}){const r=wt(Me.functions.chat.public.conversations.send);return async function(o){const s=t&&e?{sessionId:t,visitorId:e}:await n();if(s){Pe.value="",gc();try{const l=await r({sessionId:s.sessionId,visitorId:s.visitorId,content:o});l.ok?vn(s.visitorId):l.reason==="rate_limited"&&(at.value=Date.now()+l.retryAfterMs)}catch(l){console.error("[jexity] Failed to send message:",l)}}}}function bc(){const t=at.value,e=eo.value;T(()=>{if(t===null)return;const i=setInterval(()=>{eo.value=Date.now()},1e3),o=setTimeout(()=>{at.value=null},Math.max(0,t-Date.now()));return()=>{clearInterval(i),clearTimeout(o)}},[t]);const n=t!==null,r=n?Math.max(0,Math.ceil((t-e)/1e3)):0;return{isActive:n,remainingSeconds:r}}function yc(){const t=E(),{isActive:e,remainingSeconds:n}=bc();return e?c("div",{class:"jex-rate-limit-notice",role:"status","aria-live":"polite",children:t.errorRateLimited.replace("{seconds}",String(n))}):null}const qe=A(null);function vc(){const t=E(),e=qe.value;if(e===null)return null;const n=e==="no-token"?t.errorSessionNoToken:e==="unauthorized"?t.errorSessionUnauthorized:e==="network"?t.errorNetwork:t.somethingWentWrong;return c("div",{class:"jex-session-error-notice",role:"alert","aria-live":"assertive",children:n})}function _c({size:t=18}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M22 2 11 13"}),c("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}const no=132;function wc({onSend:t}){const e=le(null),n=le(null);T(()=>{const l=e.current;if(!l)return;l.style.height="0";const a=Math.min(l.scrollHeight,no);l.style.height=`${a}px`,l.style.overflowY=l.scrollHeight>no?"auto":"hidden"},[Pe.value]);function r(l){l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),t())}function i(){n.current?.click()}function o(l){const a=l.currentTarget;a.files&&a.files.length>0&&fc(a.files),a.value=""}function s(l){const a=l.target;(a===l.currentTarget||!a.closest("button, textarea, img"))&&e.current?.focus()}return{textareaRef:e,fileInputRef:n,onKeyDown:r,onAttachClick:i,onFilesPicked:o,onCardClick:s}}function kc({isStreaming:t,disabled:e,inputDisabled:n,onSend:r}){const i=E(),o=Pe,s=se,{textareaRef:l,fileInputRef:a,onKeyDown:u,onAttachClick:d,onFilesPicked:h,onCardClick:f}=wc({onSend:r}),p=o.value.trim().length>0,g=s.value.length>0,m=(p||g)&&!e;return c("div",{class:"jex-composer-card",onClick:f,children:[g&&c("div",{class:"jex-composer-attachments",role:"list",children:s.value.map(x=>c("div",{class:"jex-attachment-chip",role:"listitem",children:[c("img",{src:x.previewUrl,alt:x.file.name,class:"jex-attachment-thumb"}),c("button",{type:"button",class:"jex-attachment-remove","aria-label":i.removeAttachmentAriaLabel,onClick:()=>{pc(x.id)},children:c("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},x.id))}),c("textarea",{ref:l,class:"jex-composer-textarea","aria-label":i.inputPlaceholder,placeholder:t?i.aiThinking:i.inputPlaceholder,value:o.value,rows:1,onInput:x=>{o.value=x.currentTarget.value},onKeyDown:u,disabled:n}),c("div",{class:"jex-composer-actions",children:[c("div",{class:"jex-composer-actions-left",children:[c("input",{ref:a,class:"jex-visually-hidden",type:"file",accept:"image/*",multiple:!0,onChange:h,tabIndex:-1,"aria-hidden":"true"}),c("button",{type:"button",class:"jex-attach-btn","aria-label":i.attachComingSoon,title:i.attachComingSoon,disabled:!0,onClick:d,children:c("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),c("button",{class:`jex-send-btn${m?" jex-send-btn-active":""}`,type:"button",onClick:r,"aria-label":i.sendAriaLabel,disabled:e||!p&&!g,children:c(_c,{size:16})})]})]})}function jc({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:o,onStartFresh:s}){const l=E(),a=Pe,u=xc({sessionId:t,visitorId:e,ensureSession:o}),d=at.value!==null&&at.value>Date.now(),h=n||r||d;if(i==="resolved")return c("div",{class:"jex-chat-input-resolved",children:[c("div",{class:"jex-resolved-notice",children:l.sessionResolved}),c("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{s()},children:l.startNewConversation})]});async function f(){const p=a.value.trim();!p||h||await u(p)}return c("div",{class:"jex-chat-input",children:[c(yc,{}),c(vc,{}),c(kc,{isStreaming:r,disabled:h,inputDisabled:n||r,onSend:f})]})}function Sc(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function Oe({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:o,botAvatarUrl:s}){const l=!!r,[a,u]=C(!1),d=Se(()=>u(!0),[]),h=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return c("div",{class:"jex-message-row bot",children:[c("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&o&&!a?c("img",{src:o,alt:i??"",class:"jex-avatar-img",onError:d}):l?c("span",{class:"jex-avatar-initials",children:Sc(i??"")}):s&&!a?c("img",{src:s,alt:"",class:"jex-avatar-img",onError:d}):c(Sn,{size:14})}),c("div",{class:"jex-message-content",children:[c("div",{class:h,children:[c(lc,{text:t}),e&&c("span",{class:"jex-streaming-cursor"})]}),l&&i&&c("div",{class:"jex-message-author-row",children:[c("span",{class:"jex-message-author",children:i}),c("button",{type:"button",class:"jex-reply-tag-btn","aria-label":`Reply to ${i}`,title:`Reply to ${i}`,onClick:()=>{cc(i)},children:c(vl,{size:12})})]})]})]})}function Cc({text:t}){return c("div",{class:"jex-message user",children:t})}function ro(){return wt(Me.functions.chat.public.helpdesk.submitEscalation)}function Tc({message:t,sessionId:e,visitorId:n}){const r=E();return t.formData?c("div",{class:"jex-inline-form-submitted",children:[c("span",{class:"jex-inline-form-check",children:"✓"}),c("div",{children:[c("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),c("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):c("div",{class:"jex-message-row bot",children:c(Rc,{messageId:t._id,sessionId:e,visitorId:n})})}function Rc({messageId:t,sessionId:e,visitorId:n}){const r=E(),[i,o]=C(""),[s,l]=C(""),[a,u]=C(!1),d=ro();async function h(f){if(f.preventDefault(),!a){u(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:s.trim()})}catch(p){console.error("[FormMessage] Submit failed:",p),u(!1)}}}return c("div",{class:"jex-inline-form",children:[c("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),c("form",{class:"jex-form",onSubmit:f=>{h(f)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:f=>{o(f.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:s,required:!0,disabled:a,onInput:f=>{l(f.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),c("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}const $c={crawl:"🌐",file:"📄",snippet:"💡",qa:"❓"};function Ac({sources:t}){const[e,n]=C(!1);return t.length===0?null:c("div",{class:"jex-sources-row",children:[c("button",{type:"button",class:"jex-sources-toggle",onClick:()=>{n(r=>!r)},"aria-expanded":e,children:[c("span",{class:"jex-sources-icon",children:"📖"}),c("span",{children:[t.length," ",t.length===1?"source":"sources"]}),c("span",{class:`jex-sources-chevron${e?" jex-sources-chevron--open":""}`,children:"▾"})]}),e?c("div",{class:"jex-sources-pills",children:t.map((r,i)=>{const o=r.sourceType==="crawl",s=Ec(r),l=o&&r.url?`${r.title}
61
- ${r.url}`:r.title,a=c(B,{children:[typeof r.id=="number"?c("span",{class:"jex-source-id",children:r.id}):null,c("span",{class:"jex-source-type",children:$c[r.sourceType]}),c("span",{class:"jex-source-label",children:s}),c("span",{class:"jex-source-score",children:["· ",r.score.toFixed(2)]})]});return o&&r.url?c("a",{class:"jex-source-pill",href:r.url,target:"_blank",rel:"noopener noreferrer",title:l,children:a},i):c("span",{class:"jex-source-pill",title:l,children:a},i)})}):null]})}function Ec(t){if(t.sourceType==="crawl"&&t.url)try{const e=new URL(t.url);return!e.pathname||e.pathname==="/"?e.hostname:e.pathname}catch{}return t.title}function Ic(){return c("div",{class:"jex-typing",children:[c("span",{}),c("span",{}),c("span",{})]})}const Lc=/\s?\[\d+\]/g;function io(t){return t.replace(Lc,"")}function Pc({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:o,visitorId:s}){const l=E(),a=le(null),[u,d]=C(null),h=le(null);return T(()=>{if(!s||!t||t.length===0)return;const f=t[t.length-1];f.role==="assistant"&&f.status!=="streaming"&&f._id!==h.current&&(h.current=f._id,vn(s))},[t,s]),T(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),c("div",{class:"jex-chat-messages",children:[c(Oe,{text:e}),n&&r&&i?c("div",{class:"jex-session-prompt",children:[c("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),c("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?c("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(f=>{if(f.contentType==="human-notice")return c(Oe,{text:f.content},f._id);if(f.contentType==="escalation-form"&&o&&s)return Ka.value==="screen"&&!f.formData?u===f._id?null:c("div",{class:"jex-inline-form jex-inline-form-card",children:[c("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),c("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),c("button",{class:"jex-form-submit",type:"button",onClick:()=>{be({id:"escalation-form",formMessageId:f._id,sessionId:o,visitorId:s})},children:l.escalationPromptSubmit}),c("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(f._id)},children:l.escalationSkip})]},f._id):c(Tc,{message:f,sessionId:o,visitorId:s},f._id);if(f.contentType==="escalation-confirm")return c(Oe,{text:f.content},f._id);if(f.role==="user")return c(Cc,{text:f.content},f._id);const p={authorId:f.authorId,authorName:f.authorName,authorImage:f.authorImage};return f.status==="streaming"&&f.content===""?c(Ic,{},f._id):f.status==="streaming"?c(Oe,{text:io(f.content),streaming:!0,...p},f._id):f.status==="error"?c(Oe,{text:f.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},f._id):c("div",{children:[c(Oe,{text:io(f.content),...p}),f.sources&&f.sources.length>0?c(Ac,{sources:f.sources}):null]},f._id)}),c("div",{ref:a})]})}function qn({message:t}){const[e,n]=C(!1);return T(()=>{const r=setTimeout(()=>{n(!0)},80);return()=>{clearTimeout(r)}},[]),e?c("div",{class:"jex-overlay jex-loading",children:[c("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&c("p",{class:"jex-loading-message",children:t})]}):null}function Mc({sessionId:t,visitorId:e}){const n=ui(Me.functions.chat.public.conversations.listBySession,t&&e?{sessionId:t,visitorId:e}:"skip"),r=ui(Me.functions.chat.public.sessions.getSessionStatus,t&&e?{sessionId:t,visitorId:e}:"skip"),i=t!==null&&n===void 0,o=n?.some(s=>s.status==="streaming")??!1;return{conversations:n,sessionStatus:r??null,isLoading:i,isStreaming:o}}function qc({greeting:t,orgSlug:e,projSlug:n,sessionId:r,visitorId:i,isLoading:o,sessionNotFound:s,resumeFailed:l,isOrgDeleted:a,ensureSession:u,startFresh:d}){const h=E(),{conversations:f,sessionStatus:p,isLoading:g,isStreaming:m}=Mc({sessionId:r,visitorId:i}),x=le((()=>{const L=tt.peek();return L!==null?L:Ti.peek()?"resume":"fresh"})()).current;if(T(()=>{tt.value=null},[]),T(()=>{u()},[u]),T(()=>{i&&vn(i)},[i]),a)return c("div",{class:"jex-chat-messages",children:c("div",{class:"jex-session-notice",children:h.chatNoLongerAvailable})});const v=x==="fresh"&&!r,y=x==="resume"&&(!r||g);return v?c(qn,{message:h.startingConversation}):y?c(qn,{message:h.resumeConversation}):c(B,{children:[c(Pc,{conversations:f,greeting:t,sessionNotFound:s,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),c(jc,{sessionId:r,visitorId:i,isLoading:o,isStreaming:m,sessionStatus:p,ensureSession:u,onStartFresh:d})]})}function Oc({formMessageId:t,sessionId:e,visitorId:n}){const r=E(),[i,o]=C(""),[s,l]=C(""),a=ro(),[u,d]=C(!1),[h,f]=C(null);async function p(g){g.preventDefault(),d(!0),f(null);try{await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:s.trim()}),$t()}catch(m){console.error("[EscalationFormScreen] Submit failed:",m),f(r.escalationSubmitFailed)}finally{d(!1)}}return c("div",{class:"jex-form-screen",children:[c("h2",{class:"jex-form-title",children:r.escalationFormTitle}),c("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h&&c("div",{class:"jex-form-error",role:"alert",children:h}),c("form",{class:"jex-form",onSubmit:g=>{p(g)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:g=>{o(g.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:s,required:!0,onInput:g=>{l(g.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",disabled:u,children:r.escalationSubmit})]}),c("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),c("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{$t()},children:r.escalationSkip})]})}function Nc(){return wt(Me.functions.chat.public.helpdesk.createEscalationRequest)}function oo({sessionId:t,visitorId:e}){const n=E(),[r,i]=C(!1),[o,s]=C(null),l=Nc();async function a(){if(!t||!e)return;const u=ue.value;if(u){i(!0),s(null);try{const d=await l({sessionId:t,visitorId:e,bootstrapToken:u});if(d.skipForm)return;be({id:"escalation-form",formMessageId:d.formMessageId,sessionId:t,visitorId:e})}catch(d){const h=d instanceof Error?d.message:String(d);s(/RATE_LIMITED|Too many/.test(h)?n.handoffRateLimited:n.handoffFailed)}finally{i(!1)}}}return c(B,{children:[c("button",{class:"jex-header-handoff",type:"button",onClick:()=>{a()},disabled:r||!t||!e,"aria-label":n.talkToHumanAria,title:n.talkToHuman,children:c("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M3 14v-3a9 9 0 0 1 18 0v3"}),c("path",{d:"M21 14a2 2 0 0 1-2 2h-1a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3z"}),c("path",{d:"M3 14a2 2 0 0 0 2 2h1a1 1 0 0 0 1-1v-4a1 1 0 0 0-1-1H3z"}),c("path",{d:"M21 14v3a4 4 0 0 1-4 4h-3"})]})}),o&&c("div",{class:"jex-handoff-error",role:"alert",children:o})]})}async function zc(){const t=_i.value;if(!t)return console.warn("[JexityChat] Bootstrap refresh skipped — inputs missing"),{ok:!1,reason:"no-inputs"};const e=await xn(t.orgSlug,t.siteUrl,t.projSlug);if(!e.ok)return console.warn("[JexityChat] Bootstrap refresh failed:",e.error),{ok:!1,reason:e.error};const n=e.token;return ue.value=n,{ok:!0,token:n}}function so(t){return ao(t)?"unauthorized":t instanceof Error&&/network|fetch|failed to fetch/i.test(t.message)?"network":"unknown"}function ao(t){return t instanceof mt?t.data?.code==="UNAUTHORIZED_ORIGIN":!1}function Bc(t=1e4){return ue.value?Promise.resolve(ue.value):new Promise(e=>{let n=!1;const r=s=>{n||(n=!0,clearTimeout(i),o(),e(s))},i=setTimeout(()=>{r(null)},t),o=ue.subscribe(s=>{s&&r(s)})})}function Fc(t,e){const n=le(null),r=et(!1),i=et(!1),o=et(!1),s=et(null),l=wt(Me.functions.chat.public.sessions.createOrResume),a=async p=>{const g=await Bc();if(!g)return console.warn("[JexityChat] No bootstrap token after 10s — session creation blocked."),qe.value="no-token",null;const m=y=>({orgSlug:t,...e?{projSlug:e}:{},visitorId:p,bootstrapToken:y,...Tt.value?{source:Tt.value}:{}});wn.value=!0;let x;try{try{x=await l(m(g))}catch(y){if(!ao(y))throw y;const L=await zc();if(!L.ok)return qe.value=L.reason==="rate_limited"?"network":"unauthorized",null;x=await l(m(L.token))}}finally{wn.value=!1}qe.value=null,s.value=x.status;const v={sessionId:x.sessionId,visitorId:p};return n.current=v,{session:v,result:x}},u=Se(async()=>{if(n.current)return n.current;if(o.value)return null;r.value=!0;const p=xe.value!==null,g=xe.value??Ri();try{const m=await a(g);return m?(p&&m.result.isNew&&(i.value=!0,o.value=!0),m.session):null}catch(m){return console.error("[JexityChat] Failed to create session:",m),qe.value=so(m),null}finally{r.value=!1}},[t,e,l,r,i,o]),d=Se(()=>{n.current=null,i.value=!1,o.value=!1},[i,o]);T(()=>Ya(d),[d]);const h=Se(async()=>{n.current=null,o.value=!1,i.value=!1;const p=Ri();r.value=!0;try{return(await a(p))?.session??null}catch(g){return console.error("[JexityChat] Failed to create fresh session:",g),qe.value=so(g),null}finally{r.value=!1}},[t,e,l,r,i,o,s]),f=n.current;return{sessionId:f?.sessionId??null,visitorId:f?.visitorId??null,isLoading:r.value,sessionNotFound:i.value,resumeFailed:o.value,sessionStatus:s.value,isOrgDeleted:s.value==="org_deleted",ensureSession:u,startFresh:h,resetSession:d}}function Qc(){const t=E(),[e,n]=C(""),[r,i]=C(""),[o,s]=C("");async function l(a){a.preventDefault(),_n({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();_n({id:"confirmation",ref:u})}return c("div",{class:"jex-form-screen",children:[c("h2",{class:"jex-form-title",children:t.submitTicket}),c("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),c("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:o,required:!0,onInput:a=>{s(a.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Dc({ticketRef:t}){const e=E();return c("div",{class:"jex-confirmation",children:[c("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),c("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),c("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),c("div",{class:"jex-confirmation-ref",children:t}),c("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),c("button",{class:"jex-confirmation-done",onClick:()=>{I.value=!1},children:e.done})]})}function Uc({message:t,onRetry:e,onBack:n}){const r=E();return c("div",{class:"jex-overlay jex-error",children:[c("p",{class:"jex-error-message",children:t}),c("div",{class:"jex-error-actions",children:[e&&c("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&c("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function lo({greeting:t,title:e,orgSlug:n,projSlug:r,sessionId:i,visitorId:o,isLoading:s,sessionNotFound:l,resumeFailed:a,isOrgDeleted:u,ensureSession:d,startFresh:h,resetSession:f}){const p=z.value,g=p[p.length-1],m=[...p].reverse().find(x=>x.id==="confirmation");return c("div",{class:"jex-screen-container",children:[g.id==="home"&&c(dl,{greeting:t,title:e,onStartFresh:h,onResetSession:f}),g.id==="selection"&&c(fl,{title:e}),g.id==="form"&&c(Qc,{}),g.id==="escalation-form"&&c(Oc,{formMessageId:g.formMessageId,sessionId:g.sessionId,visitorId:g.visitorId}),g.id==="confirmation"&&m&&c(Dc,{ticketRef:m.ref}),g.id==="chat"&&c(qc,{greeting:t,orgSlug:n,projSlug:r,sessionId:i,visitorId:o,isLoading:s,sessionNotFound:l,resumeFailed:a,isOrgDeleted:u,ensureSession:d,startFresh:h}),g.id==="loading"&&c(qn,{message:g.message}),g.id==="error"&&c(Uc,{message:g.message,onRetry:()=>_n({id:"loading"}),onBack:$t})]})}function Vc({options:t}){za(t.orgSlug,t.projSlug,t.bootstrapToken,t.convexUrl);const e=Na(t.orgSlug,t.projSlug,t.convexUrl);Va(t.parentOrigin),T(()=>{Ja(),Ga()},[]);const{sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}=Fc(t.orgSlug,t.projSlug),h=qa(t,e);T(()=>{bn.value=ki(h.locale)},[h.locale]),T(()=>{if(!I.value||h.mode==="embedded"||!window.matchMedia("(max-width: 480px), (pointer: coarse) and (max-width: 768px)").matches)return;const F=document.documentElement.style.overflow;return document.documentElement.style.overflow="hidden",()=>{document.documentElement.style.overflow=F}},[I.value,h.mode]),T(()=>{if(h.mode!=="embedded")try{return tl()}catch(K){console.warn("[JexityChat] Idle-lock watcher failed to start:",K);return}},[h.mode]);const f=h.position==="bottom-left",p=h.colorScheme==="dark"||h.colorScheme==="light"?h.colorScheme:"",g=nl({...t,primaryColor:h.primaryColor,accentColor:h.accentColor,fontFamily:h.fontFamily,fontSize:h.fontSize,borderRadius:h.borderRadius,windowWidth:h.windowWidth,windowHeight:h.windowHeight}),m=h.mode==="embedded",x=z.value,y=x[x.length-1]?.id==="chat",V=e!==null||m||!!t.parentOrigin?g:{...g,visibility:"hidden"};return c("div",{class:`jex-widget ${p}`.trim(),style:V,children:m?c("div",{class:"jex-embedded",children:[c(Li,{title:h.title,rightAction:y?c(oo,{sessionId:n,visitorId:r}):null,showClose:!m}),c(lo,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}),!h.hideBranding&&c(Pi,{})]}):c("div",{class:`jex-container${f?" jex-pos-left":""}`,children:[I.value&&c("div",{class:"jex-chat-window",children:[c(Li,{title:h.title,rightAction:y?c(oo,{sessionId:n,visitorId:r}):null}),c(lo,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}),!h.hideBranding&&c(Pi,{})]}),c(hl,{iconOption:h.triggerIcon,radius:h.triggerRadius,label:h.triggerLabel})]})})}const Hc='.jex-widget{--jex-primary: #115A62;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-radius: .75rem;--jex-font-family: "Inter", system-ui, -apple-system, sans-serif;--jex-font-size: 14px;--jex-window-width: 380px;--jex-window-height: 600px;--jex-shadow: 0 16px 48px -12px rgba(13, 127, 138, .25), 0 4px 16px rgba(0, 0, 0, .08);pointer-events:auto;--jex-bg-trigger: var(--jex-primary);--jex-bg-header: var(--jex-primary);--jex-bg-msg-user: var(--jex-primary);--jex-bg-send-btn: var(--jex-primary);--jex-bg-window: rgba(255, 255, 255, .95);--jex-bg-msg-bot: #f1f5f9;--jex-bg-input: rgba(247, 253, 253, .6);--jex-text-header: #ffffff;--jex-text-msg-user: #ffffff;--jex-text-msg-bot: #0f172a;--jex-text-main: #0f172a;--jex-text-muted: #64748b;--jex-bg-avatar-agent: #d1fae5;--jex-text-avatar-agent: #065f46;--jex-border-window: rgba(226, 232, 240, .8);--jex-border-input: rgba(203, 213, 225, .8);--jex-bg-glass: var(--jex-bg-window);--jex-border-glass: var(--jex-border-window);font-family:var(--jex-font-family);-webkit-font-smoothing:antialiased}.dark .jex-widget,.jex-widget.dark{--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-avatar-agent: #064e3b;--jex-text-avatar-agent: #6ee7b7;--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light){--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}}.jex-widget *{box-sizing:border-box;margin:0;padding:0}.jex-container{position:fixed;bottom:24px;right:24px;display:flex;flex-direction:column;align-items:flex-end;gap:16px;z-index:9999}.jex-container.jex-pos-left{right:auto;left:24px;align-items:flex-start}:host(.jex-mode-embedded){display:block;width:100%;height:100%}:host(.jex-mode-embedded) .jex-widget{width:100%;height:100%}.jex-embedded{display:flex;flex-direction:column;width:100%;height:100%;background:var(--jex-bg-window);border:1px solid var(--jex-border-window);overflow:hidden}.jex-embedded .jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-floating-button{height:56px;min-width:56px;padding:0;background:var(--jex-bg-trigger);color:var(--jex-text-header);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:var(--jex-shadow);transition:transform .3s cubic-bezier(.175,.885,.32,1.275),background .2s,width .3s ease,border-radius .3s ease}.jex-floating-button.jex-has-label{min-width:110px;padding:0 20px}.jex-fab-inner{display:flex;align-items:center;gap:12px}.jex-fab-label{font-size:15px;font-weight:600;white-space:nowrap}.jex-floating-button:hover{transform:scale(1.1);background:var(--jex-primary-hover)}.jex-floating-button:active{transform:scale(.95)}.jex-chat-window{width:var(--jex-window-width);height:var(--jex-window-height);max-height:calc(100vh - 120px);background:var(--jex-bg-window);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border:1px solid var(--jex-border-window);border-radius:calc(var(--jex-radius) * 2);box-shadow:var(--jex-shadow);display:flex;flex-direction:column;overflow:hidden;animation:jexSlideUp .4s cubic-bezier(.16,1,.3,1);transform-origin:bottom right;touch-action:manipulation}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) translateY(0)}}@media(max-width:480px),(pointer:coarse)and (max-width:768px){.jex-chat-window{position:fixed;inset:0;width:100vw;height:100vh;height:100dvh;max-height:none;border:none;border-radius:0;animation:jexSlideUpMobile .3s cubic-bezier(.16,1,.3,1);transform-origin:bottom center}.jex-container:has(.jex-chat-window) .jex-floating-button{display:none}}@keyframes jexSlideUpMobile{0%{opacity:0;transform:translateY(100%)}to{opacity:1;transform:translateY(0)}}.jex-chat-header{padding:20px;background:var(--jex-bg-header);color:var(--jex-text-header);display:flex;align-items:center;gap:12px;flex-shrink:0}.jex-header-info h3{font-size:16px;font-weight:600;color:var(--jex-text-header);margin:0}.jex-header-info p{font-size:12px;opacity:.8;color:var(--jex-text-header);margin:0}.jex-header-right{margin-left:auto;display:flex;align-items:center;gap:4px}.jex-header-handoff{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:transparent;border:1px solid color-mix(in srgb,currentColor 50%,transparent);border-radius:999px;padding:0;color:inherit;cursor:pointer;transition:background .15s ease,border-color .15s ease}.jex-header-handoff:hover:not(:disabled){background:color-mix(in srgb,currentColor 12%,transparent);border-color:currentColor}.jex-header-handoff:disabled{opacity:.5;cursor:not-allowed}.jex-header-close{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:transparent;border:none;border-radius:999px;padding:0;color:inherit;cursor:pointer;transition:background .15s ease}.jex-header-close:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.jex-handoff-error{position:absolute;top:100%;right:8px;background:#fee;color:#b00;padding:4px 8px;font-size:12px;border-radius:4px}.jex-header-back{background:none;border:none;color:var(--jex-text-header);cursor:pointer;padding:4px;display:flex;align-items:center;opacity:.8;transition:opacity .2s;flex-shrink:0}.jex-header-back:hover{opacity:1}.jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-home{flex:1;display:flex;flex-direction:column;padding:24px;gap:20px;overflow-y:auto}.jex-home-hero{display:flex;align-items:center;gap:14px;animation:jexFadeIn .4s ease both}.jex-home-avatar{position:relative;width:48px;height:48px;border-radius:14px;background:var(--jex-primary);color:var(--jex-text-header);display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 4px 12px color-mix(in srgb,var(--jex-primary) 30%,transparent)}.jex-home-status-dot{position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;border-radius:50%;background:#22c55e;border:2.5px solid var(--jex-bg-window);animation:jexPulse 2s ease-in-out infinite}@keyframes jexPulse{0%,to{box-shadow:0 0 #22c55e66}50%{box-shadow:0 0 0 6px #22c55e00}}.jex-home-hero-text{display:flex;flex-direction:column;gap:2px;min-width:0}.jex-home-title{font-size:17px;font-weight:700;color:var(--jex-text-main);margin:0;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.jex-home-status{font-size:12px;font-weight:500;color:#22c55e;letter-spacing:.02em}.jex-home-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:4px 16px 16px;padding:16px 18px;font-size:14px;line-height:1.55;color:var(--jex-text-main);animation:jexFadeIn .4s .1s ease both}.jex-home-greeting p{margin:0}@keyframes jexFadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.jex-home-actions{display:flex;flex-direction:column;gap:10px;animation:jexFadeIn .4s .2s ease both}.jex-home-start-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;padding:14px 20px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,transform .15s,box-shadow .2s;width:100%;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 25%,transparent)}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 35%,transparent)}.jex-home-start-btn:active{transform:translateY(0);box-shadow:0 1px 4px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card{display:flex;flex-direction:column;gap:8px;width:100%;text-align:left;padding:16px 18px;border-radius:14px;border:1.5px solid var(--jex-primary);background:color-mix(in srgb,var(--jex-primary) 6%,var(--jex-bg-window));cursor:pointer;font-family:inherit;transition:background .2s,border-color .2s,transform .15s,box-shadow .2s;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 12%,transparent)}.jex-home-resume-card:hover{background:color-mix(in srgb,var(--jex-primary) 10%,var(--jex-bg-window));transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card:active{transform:translateY(0)}.jex-home-resume-top{display:flex;align-items:center;justify-content:space-between}.jex-home-resume-label{font-size:14px;font-weight:600;color:var(--jex-primary)}.jex-home-resume-arrow{color:var(--jex-primary);opacity:.6;transition:opacity .2s,transform .2s}.jex-home-resume-card:hover .jex-home-resume-arrow{opacity:1;transform:translate(2px)}.jex-home-resume-ref{font-family:ui-monospace,Cascadia Code,Fira Code,monospace;font-size:13px;font-weight:600;letter-spacing:.06em;color:var(--jex-text-muted)}.jex-home-history{display:flex;flex-direction:column;gap:8px}.jex-home-resume-meta{font-size:11px;opacity:.7;margin-top:4px}.jex-home-new-btn{background:transparent;color:var(--jex-text-muted);border:1px solid var(--jex-border-input);border-radius:12px;padding:12px 20px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;transition:color .2s,border-color .2s,background .2s;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted);background:color-mix(in srgb,var(--jex-primary) 3%,transparent)}.jex-session-ref{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:8px;font-size:12px}.jex-session-ref-label{color:var(--jex-text-muted);font-weight:500}.jex-session-ref-code{color:var(--jex-primary);font-weight:700;font-family:ui-monospace,Cascadia Code,monospace;letter-spacing:.05em}.jex-chat-messages{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}.jex-message-row{display:flex;align-items:flex-end;gap:8px;max-width:85%}.jex-message-row.bot{align-self:flex-start}.jex-message-content{flex:1;min-width:0}.jex-avatar{width:24px;height:24px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:2px}.jex-avatar-bot{background:var(--jex-bg-msg-bot);color:var(--jex-primary)}.jex-avatar-agent{background:var(--jex-bg-avatar-agent)}.jex-avatar-img{width:100%;height:100%;border-radius:50%;object-fit:cover}.jex-avatar-initials{font-size:9px;font-weight:700;color:var(--jex-text-avatar-agent)}.jex-message-author-row{display:flex;align-items:center;gap:6px;margin-top:2px;padding-left:4px}.jex-message-author{font-size:10px;color:var(--jex-text-muted)}.jex-reply-tag-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;border-radius:4px;background:transparent;color:var(--jex-text-muted, #6b7280);cursor:pointer;transition:background .15s,color .15s}.jex-reply-tag-btn:hover{background:#0000000f;color:var(--jex-primary, #115A62)}.jex-reply-tag-btn:focus-visible{outline:2px solid var(--jex-primary, #115A62);outline-offset:1px}.jex-message{padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);color:var(--jex-text-msg-bot);border-bottom-left-radius:4px}.jex-message.user{align-self:flex-end;max-width:80%;background:var(--jex-bg-msg-user);color:var(--jex-text-msg-user);border-bottom-right-radius:4px}.jex-typing{align-self:flex-start;display:flex;gap:4px;padding:12px 16px}.jex-typing span{width:8px;height:8px;border-radius:50%;background:var(--jex-text-muted);animation:jexTypingDot 1.2s infinite ease-in-out}.jex-typing span:nth-child(2){animation-delay:.2s}.jex-typing span:nth-child(3){animation-delay:.4s}@keyframes jexTypingDot{0%,80%,to{transform:scale(.8);opacity:.4}40%{transform:scale(1);opacity:1}}.jex-md{word-break:break-word;overflow-wrap:anywhere}.jex-md p{margin:0 0 8px}.jex-md p:last-child{margin-bottom:0}.jex-md strong{font-weight:600}.jex-md em{font-style:italic}.jex-md ul,.jex-md ol{margin:0 0 8px;padding-left:20px}.jex-md ul:last-child,.jex-md ol:last-child{margin-bottom:0}.jex-md ul{list-style-type:disc}.jex-md ol{list-style-type:decimal}.jex-md li{margin-bottom:2px}.jex-md li:last-child{margin-bottom:0}.jex-md a{color:var(--jex-primary);text-decoration:underline;text-underline-offset:2px}.jex-md a:hover{opacity:.8}.jex-md code{background:#00000014;padding:1px 5px;border-radius:4px;font-size:.9em;font-family:ui-monospace,Cascadia Code,Fira Code,monospace}.jex-md pre{background:#0000000f;border-radius:8px;padding:10px 12px;margin:0 0 8px;overflow-x:auto;font-size:.85em}.jex-md pre:last-child{margin-bottom:0}.jex-md pre code{background:none;padding:0;border-radius:0;font-size:inherit}.jex-md h1,.jex-md h2,.jex-md h3,.jex-md h4{font-weight:600;margin:8px 0 4px}.jex-md h1:first-child,.jex-md h2:first-child,.jex-md h3:first-child,.jex-md h4:first-child{margin-top:0}.jex-md h3{font-size:1em}.jex-md h4{font-size:.95em}.jex-md hr{border:none;border-top:1px solid var(--jex-border-window);margin:8px 0}.jex-md blockquote{border-left:3px solid var(--jex-primary);margin:0 0 8px;padding:4px 12px;color:var(--jex-text-muted)}.jex-md blockquote:last-child{margin-bottom:0}.dark .jex-md code,.jex-widget.dark .jex-md code{background:#ffffff1a}.dark .jex-md pre,.jex-widget.dark .jex-md pre{background:#ffffff14}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-md code{background:#ffffff1a}:host:not(.light) .jex-widget:not(.light) .jex-md pre{background:#ffffff14}}.jex-streaming-cursor:after{content:"◊";margin-left:2px;animation:jexBlinkCursor .8s ease-in-out infinite}@keyframes jexBlinkCursor{0%,to{opacity:1}50%{opacity:0}}.jex-session-notice{align-self:center;text-align:center;padding:8px 16px;margin:8px 0;font-size:12px;color:var(--jex-text-muted);background:var(--jex-bg-input, #f1f5f9);border-radius:8px;line-height:1.4}.jex-message-error{background:var(--jex-bg-error, #fef2f2)!important;border-color:var(--jex-border-error, #fecaca)!important;color:var(--jex-text-error, #991b1b)!important}.jex-chat-input{padding:12px 16px;border-top:1px solid var(--jex-border-window);display:flex;flex-direction:column;gap:8px;flex-shrink:0}.jex-composer-card{display:flex;flex-direction:column;gap:6px;padding:10px 12px 8px;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:16px;cursor:text;transition:border-color .15s ease,background .15s ease,box-shadow .15s ease}.jex-composer-card:focus-within{border-color:var(--jex-primary);background:var(--jex-bg-window);box-shadow:0 0 0 3px color-mix(in srgb,var(--jex-primary, #115A62) 14%,transparent)}.jex-composer-attachments{display:flex;flex-wrap:wrap;gap:6px;padding:2px 2px 4px}.jex-attachment-chip{position:relative;width:44px;height:44px;border-radius:8px;overflow:hidden;background:var(--jex-bg-msg-bot, #f1f5f9);flex-shrink:0;box-shadow:0 1px 2px #0000000f}.jex-attachment-thumb{width:100%;height:100%;object-fit:cover;display:block;pointer-events:none}.jex-attachment-remove{position:absolute;top:2px;right:2px;width:16px;height:16px;padding:0;border:none;border-radius:50%;background:#0f172ac7;color:#fff;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;opacity:0;transition:opacity .12s ease,transform .12s ease}.jex-attachment-chip:hover .jex-attachment-remove,.jex-attachment-chip:focus-within .jex-attachment-remove{opacity:1}.jex-attachment-remove:hover{transform:scale(1.08)}.jex-composer-textarea{width:100%;min-height:22px;background:transparent;border:none;outline:none;resize:none;padding:2px 4px;color:var(--jex-text-main);font-family:inherit;font-size:16px;line-height:1.45;overflow-y:hidden}.jex-composer-textarea::placeholder{color:var(--jex-text-muted);opacity:.85}.jex-composer-textarea:disabled{cursor:not-allowed;opacity:.7}.jex-composer-actions{display:flex;align-items:center;justify-content:space-between;gap:8px}.jex-composer-actions-left{display:inline-flex;align-items:center;gap:4px}.jex-attach-btn{width:30px;height:30px;padding:0;border:none;border-radius:50%;background:transparent;color:var(--jex-text-muted);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:background .12s ease,color .12s ease,transform .12s ease}.jex-attach-btn:hover:not(:disabled){background:color-mix(in srgb,var(--jex-text-muted, #64748b) 12%,transparent);color:var(--jex-text-main)}.jex-attach-btn:active:not(:disabled){transform:scale(.92)}.jex-attach-btn:disabled{opacity:.4;cursor:not-allowed}.jex-visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.jex-rate-limit-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-muted, #64748b);font-size:12px;line-height:1.4;text-align:center}.jex-session-error-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-error, #fef2f2);border:1px solid var(--jex-border-error, #fecaca);color:var(--jex-text-error, #991b1b);font-size:12px;line-height:1.4;text-align:center}.jex-chat-input input{flex:1;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:12px;padding:10px 14px;color:var(--jex-text-main);outline:none;font-family:inherit;font-size:14px}.jex-chat-input input:focus{border-color:var(--jex-primary)}.jex-send-btn{background:color-mix(in srgb,var(--jex-text-muted, #64748b) 18%,transparent);color:var(--jex-text-muted);border:none;border-radius:999px;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:background .15s ease,color .15s ease,opacity .15s ease,transform .15s ease;flex-shrink:0}.jex-send-btn-active{background:var(--jex-bg-send-btn, var(--jex-primary));color:var(--jex-text-header, #fff)}.jex-send-btn-active:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-send-btn:active:not(:disabled){transform:scale(.9)}.jex-send-btn:disabled{opacity:.45;cursor:default}.jex-widget-footer{display:flex;align-items:center;justify-content:center;padding:8px 16px;border-top:1px solid var(--jex-border-glass);background:#00000005;flex-shrink:0}.jex-widget.dark .jex-widget-footer{background:#ffffff05}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-widget-footer{background:#ffffff05}}.jex-branding{display:flex;align-items:center;gap:6px;text-decoration:none;color:var(--jex-text-muted);font-size:11px;font-weight:500;transition:color .2s}.jex-branding:hover{color:var(--jex-text-main)}.jex-branding-icon{color:var(--jex-primary)}.jex-branding span strong{font-weight:700;color:var(--jex-text-main)}.jex-locale-select-wrapper{position:relative;display:flex;align-items:center}.jex-locale-select{appearance:none;-webkit-appearance:none;background:transparent;border:1px solid transparent;padding:4px 20px 4px 6px;border-radius:6px;font-family:inherit;font-size:11px;font-weight:600;color:var(--jex-text-muted);background-color:transparent;cursor:pointer;outline:none;transition:all .2s ease}.jex-locale-select option{background-color:#fff;color:#0f172a}.jex-locale-select:hover,.jex-locale-select:focus-visible{color:var(--jex-text-main);background:#0000000a}.jex-widget.dark .jex-locale-select:hover,.jex-widget.dark .jex-locale-select:focus-visible{background:#ffffff0d}.jex-widget.dark .jex-locale-select option{background-color:#0f172a;color:#f8fafc}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-locale-select:hover,:host:not(.light) .jex-widget:not(.light) .jex-locale-select:focus-visible{background:#ffffff0d}:host:not(.light) .jex-widget:not(.light) .jex-locale-select option{background-color:#0f172a;color:#f8fafc}}.jex-locale-select:focus-visible{border-color:var(--jex-primary)}.jex-locale-chevron{position:absolute;right:4px;pointer-events:none;color:var(--jex-text-muted);transition:color .2s ease}.jex-locale-select-wrapper:hover .jex-locale-chevron{color:var(--jex-text-main)}.jex-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:var(--jex-bg-window, #fff);z-index:10;padding:24px;text-align:center}.jex-loading-spinner{width:32px;height:32px;border:3px solid var(--jex-border-input, #e2e8f0);border-top-color:var(--jex-primary, #115A62);border-radius:50%;animation:jex-spin .7s linear infinite}@keyframes jex-spin{to{transform:rotate(360deg)}}.jex-loading-message{font-size:14px;color:var(--jex-text-muted, #64748b)}.jex-error-message{font-size:14px;color:var(--jex-text-main, #334155)}.jex-error-actions{display:flex;gap:8px}.jex-error-retry,.jex-error-back{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:none}.jex-error-retry{background:var(--jex-primary, #115A62);color:#fff}.jex-error-back{background:transparent;color:var(--jex-text-muted, #64748b);border:1px solid var(--jex-border-input, #e2e8f0)}.jex-selection{display:flex;flex-direction:column;gap:12px;padding:24px 16px;height:100%}.jex-selection-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 8px}.jex-selection-options{display:flex;flex-direction:column;gap:10px}.jex-selection-option{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:16px;border-radius:12px;border:1px solid var(--jex-border-window, #e2e8f0);background:transparent;cursor:pointer;text-align:left;transition:border-color .15s ease,background .15s ease}.jex-selection-option:hover{border-color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 5%,transparent)}.jex-selection-icon{font-size:20px}.jex-selection-label{font-size:14px;font-weight:600;color:var(--jex-text-main, #0f172a)}.jex-selection-sub{font-size:12px;color:var(--jex-text-muted, #64748b)}.jex-form-screen{display:flex;flex-direction:column;padding:20px 16px;height:100%;overflow-y:auto}.jex-form-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 16px}.jex-form{display:flex;flex-direction:column;gap:10px}.jex-form-input,.jex-form-textarea{padding:10px 12px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:14px;background:transparent;color:var(--jex-text-main, #0f172a);outline:none}@media(pointer:coarse){.jex-form-input,.jex-form-textarea{font-size:16px}}.jex-form-input:focus,.jex-form-textarea:focus{border-color:var(--jex-primary, #115A62)}.jex-form-textarea{min-height:80px;resize:vertical}.jex-form-submit{padding:10px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer;margin-top:4px}.jex-inline-form{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-title{font-weight:600;font-size:15px;color:var(--jex-text-main, #0f172a);margin:0}.jex-inline-form-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.4;margin:0 0 4px}.jex-inline-form-consent{font-size:11px;color:var(--jex-text-muted, #64748b);line-height:1.3;margin-top:4px;text-align:center}.jex-inline-form .jex-form-submit:disabled{opacity:.7;cursor:not-allowed}.jex-escalation-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.45;margin:0 0 8px}.jex-escalation-skip{padding:8px 12px;border:none;background:transparent;color:var(--jex-text-muted, #64748b);font-size:13px;cursor:pointer;text-decoration:underline;text-underline-offset:2px;text-align:center}.jex-escalation-skip:hover{color:var(--jex-text-main, #0f172a)}.jex-inline-form-card{position:relative;padding:14px;gap:8px}.jex-inline-form-dismiss{position:absolute;top:10px;right:10px;width:24px;height:24px;border-radius:50%;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-window, #fff);color:var(--jex-text-muted, #64748b);font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}.jex-inline-form-dismiss:hover{background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-check{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary) 15%,transparent);color:var(--jex-primary, #115A62);font-size:14px;font-weight:700;flex-shrink:0}.jex-inline-form-submitted-title{font-weight:600;font-size:var(--jex-font-size, 14px);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted-detail{font-size:12px;color:var(--jex-text-muted, #64748b);margin-top:2px}.jex-escalation-confirm{border-left:3px solid var(--jex-primary, #115A62);padding-left:8px}.jex-session-prompt{display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px 16px;margin:8px 0;text-align:center}.jex-session-prompt-text{font-size:13px;color:var(--jex-text-muted, #64748b)}.jex-session-prompt-btn{padding:8px 16px;border-radius:8px;border:1px solid var(--jex-primary, #115A62);background:transparent;color:var(--jex-primary, #115A62);font-size:13px;font-weight:600;cursor:pointer}.jex-session-prompt-btn:hover{background:color-mix(in srgb,var(--jex-primary) 10%,transparent)}.jex-chat-input-resolved{display:flex;flex-direction:column;align-items:center;gap:10px;padding:14px 16px;border-top:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-msg-bot, #f1f5f9);text-align:center}.jex-resolved-notice{font-size:13px;font-weight:500;color:var(--jex-text-muted, #64748b)}.jex-resolved-new-btn{padding:10px 20px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;width:100%}.jex-resolved-new-btn:hover{opacity:.9}.jex-confirmation{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 24px;height:100%;text-align:center}.jex-confirmation-icon{width:48px;height:48px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary, #115A62) 15%,transparent);color:var(--jex-primary, #115A62);font-size:22px;display:flex;align-items:center;justify-content:center}.jex-confirmation-title{font-size:18px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0}.jex-confirmation-body{font-size:13px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-ref{font-size:20px;font-weight:700;letter-spacing:.05em;color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 10%,transparent);padding:10px 20px;border-radius:10px}.jex-confirmation-hint{font-size:12px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-done{margin-top:8px;padding:10px 28px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer}.jex-home-lookup-link{background:none;border:none;font-size:12px;color:var(--jex-text-muted, #64748b);cursor:pointer;text-decoration:underline;padding:0;align-self:center}.jex-home-lookup{display:flex;gap:8px;width:100%;animation:jexFadeIn .4s .1s ease both}.jex-home-lookup-input{flex:1;padding:10px 14px;border-radius:10px;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-input);color:var(--jex-text-main);font-size:14px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}@media(pointer:coarse){.jex-home-lookup-input{font-size:16px}}.jex-home-lookup-input::placeholder{font-family:inherit;letter-spacing:.04em;color:var(--jex-text-muted);opacity:.7}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:10px 16px;border-radius:10px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,opacity .2s;flex-shrink:0}.jex-home-lookup-submit:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-home-lookup-submit:disabled{opacity:.4;cursor:default}.jex-sources-row{margin-top:6px;margin-left:32px;display:flex;flex-direction:column;gap:6px}.jex-sources-toggle{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;background:transparent;border:none;border-radius:6px;cursor:pointer;font-size:11px;color:var(--jex-text-muted, #6b7280);font-family:inherit;align-self:flex-start;transition:background .15s,color .15s}.jex-sources-toggle:hover{background:#0000000a;color:inherit}.jex-sources-icon{font-size:12px;line-height:1}.jex-sources-chevron{display:inline-block;font-size:10px;transition:transform .15s}.jex-sources-chevron--open{transform:rotate(180deg)}.jex-sources-pills{display:flex;flex-wrap:wrap;align-items:center;gap:6px}.jex-source-pill{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:2px 8px;border-radius:999px;border:1px solid rgba(0,0,0,.1);background:#0000000a;color:var(--jex-text-muted, #6b7280);font-size:11px;text-decoration:none;cursor:pointer;transition:background .15s,color .15s}.jex-source-pill:hover{background:#00000014;color:inherit}.jex-source-id{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 4px;border-radius:4px;background:var(--jex-primary, #115A62);color:#fff;font-size:10px;font-weight:600;line-height:1;flex-shrink:0;font-variant-numeric:tabular-nums}.jex-source-type{font-size:10px;flex-shrink:0}.jex-source-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}.jex-source-score{opacity:.6;flex-shrink:0;font-variant-numeric:tabular-nums}';function Wc(t){const e=document.createElement("style");e.textContent=Hc,t.appendChild(e)}const Jc="https://festive-mouse-978.eu-west-1.convex.cloud";let On=null;function Gc(t){const e=t??Jc;if(!e)throw new Error("[jexity] No Convex URL — set VITE_CONVEX_URL at build time or data-convex-url on the script tag");return On||(On=new ya(Ma(e))),On}function Kc(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Wc(n),Tt.value=e.source,ue.value=e.bootstrapToken,z.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),I.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),fe(c(_a,{client:Gc(e.convexUrl),children:c(Vc,{options:e})}),r),function(){fe(null,r),I.value=!1,Tt.value=void 0,ue.value=void 0,z.value=[{id:"home"}]}}function Zc(t,e,n){const r=Kc(t,e),i=new Set,o=I.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){o(),i.clear(),r(),n&&n()},open(){I.value=!0},close(){I.value=!1},toggle(){I.value=!I.value},get isOpen(){return I.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let lt=null;function Yc(t){lt&&lt.shutdown();let e;t.container?e=typeof t.container=="string"?document.querySelector(t.container):t.container:(e=document.createElement("div"),e.id="jexity-chat-widget",document.body.appendChild(e));const n=Zc(e,t,()=>{t.container||e.remove(),lt===n&&(lt=null)});return lt=n,n}function he(t,e){return t.getAttribute(e)??void 0}async function co(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const e=t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",n=t.getAttribute("data-proj-slug")??void 0,r=he(t,"data-convex-url")??"https://festive-mouse-978.eu-west-1.convex.cloud"??"",i=mn(r),o=await xn(e,i,n);if(!o.ok){const l=window.location.origin,a=n?`project '${e}/${n}'`:`org '${e}'`;o.error==="unauthorized"?console.warn(`[JexityChat] This domain is not authorized for ${a}. Add '${l}' under Allowed Domains in your Jexity dashboard.`):o.error==="not_found"?console.warn(`[JexityChat] No active widget config found for ${a}. Check that the org slug is correct and the widget is enabled.`):o.error==="rate_limited"?console.warn(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${o.retryAfterSec??60}s.`):console.warn(`[JexityChat] Bootstrap failed (network error). Check that the Convex deployment is reachable at ${i}.`);return}const s={orgSlug:e,projSlug:n,bootstrapToken:o.token,position:he(t,"data-position")??void 0,theme:he(t,"data-theme")??void 0,greeting:he(t,"data-greeting"),title:he(t,"data-title"),primaryColor:he(t,"data-primary-color"),locale:he(t,"data-locale"),convexUrl:he(t,"data-convex-url")};window.JexityChat=Yc(s)}document.readyState==="complete"?co():window.addEventListener("load",co)})();
67
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${ne(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),i=Zi(t);if(i===null)return r;t=i;let o='<a href="'+t+'"';return e&&(o+=' title="'+ne(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Zi(t);if(i===null)return ne(n);t=i;let o=`<img src="${t}" alt="${ne(n)}"`;return e&&(o+=` title="${ne(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ne(t.text)}},Ln=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},K=class Bn{options;renderer;textRenderer;constructor(e){this.options=e||ye,this.options.renderer=this.options.renderer||new Lt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ln}static parse(e,n){return new Bn(n).parse(e)}static parseInline(e,n){return new Bn(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=l||"";continue}}let o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let o=e[i];if(this.options.extensions?.renderers?.[o.type]){let l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=l||"";continue}}let s=o;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let l='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},st=class{options;block;constructor(t){this.options=t||ye}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?J.lex:J.lexInline}provideParser(){return this.block?K.parse:K.parseInline}},ac=class{defaults=Cn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=K;Renderer=Lt;TextRenderer=Ln;Lexer=J;Tokenizer=qt;Hooks=st;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=e.renderers[i.name];o?e.renderers[i.name]=function(...s){let l=i.renderer.apply(this,s);return l===!1&&(l=o.apply(this,s)),l}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[i.level];o?o.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new Lt(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,l=n.renderer[s],a=i[s];i[s]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new qt(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,l=n.tokenizer[s],a=i[s];i[s]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new st;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,l=n.hooks[s],a=i[s];st.passThroughHooks.has(o)?i[s]=u=>{if(this.defaults.async&&st.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await l.call(i,u);return a.call(i,h)})();let d=l.call(i,u);return a.call(i,d)}:i[s]=(...u)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(i,u);return h===!1&&(h=await a.apply(i,u)),h})();let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let l=[];return l.push(o.call(this,s)),i&&(l=l.concat(i.call(this,s))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return J.lex(t,e??this.defaults)}parser(t,e){return K.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(e):e,l=await(i.hooks?await i.hooks.provideLexer():t?J.lex:J.lexInline)(s,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let u=await(i.hooks?await i.hooks.provideParser():t?K.parse:K.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(u):u})().catch(o);try{i.hooks&&(e=i.hooks.preprocess(e));let s=(i.hooks?i.hooks.provideLexer():t?J.lex:J.lexInline)(e,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():t?K.parse:K.parseInline)(s,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(s){return o(s)}}}onError(t,e){return n=>{if(n.message+=`
68
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+ne(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},_e=new ac;function k(t,e){return _e.parse(t,e)}k.options=k.setOptions=function(t){return _e.setOptions(t),k.defaults=_e.defaults,Ni(k.defaults),k},k.getDefaults=Cn,k.defaults=ye,k.use=function(...t){return _e.use(...t),k.defaults=_e.defaults,Ni(k.defaults),k},k.walkTokens=function(t,e){return _e.walkTokens(t,e)},k.parseInline=_e.parseInline,k.Parser=K,k.parser=K.parse,k.Renderer=Lt,k.TextRenderer=Ln,k.Lexer=J,k.lexer=J.lex,k.Tokenizer=qt,k.Hooks=st,k.parse=k,k.options,k.setOptions,k.use,k.walkTokens,k.parseInline,K.parse,J.lex,k.setOptions({breaks:!0,gfm:!0});function lc({text:t}){const e=W(()=>{if(!t)return"";const n=k.parse(t);return typeof n=="string"?n:""},[t]);return c("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}const qe=E("");function cc(t){if(!t)return;const e=t.trim().split(/\s+/)[0];if(!e)return;const n=`@${e} `,r=qe.value;r.includes(n)||r.includes(`@${e}`)||(qe.value=r.trimStart()?`${n}${r.trimStart()}`:n)}const at=E(null),eo=E(Date.now()),se=E([]),uc=4,hc=8*1024*1024;function dc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}function fc(t){const e=Array.from(t).filter(i=>i.type.startsWith("image/")&&i.size<=hc);if(e.length===0)return;const n=uc-se.value.length;if(n<=0)return;const r=e.slice(0,n).map(i=>({id:dc(),file:i,previewUrl:URL.createObjectURL(i)}));se.value=[...se.value,...r]}function pc(t){const e=se.value.find(n=>n.id===t);e&&URL.revokeObjectURL(e.previewUrl),se.value=se.value.filter(n=>n.id!==t)}function gc(){for(const t of se.value)URL.revokeObjectURL(t.previewUrl);se.value=[]}function to(t,e){const n={get(r,i){if(typeof i=="string"){const o=[...e,i];return to(t,o)}else if(i===Zr){if(e.length<1){const o=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${o}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const mc=()=>to("components",[]),Le=Es;mc();function xc({sessionId:t,visitorId:e,ensureSession:n}){const r=wt(Le.functions.chat.public.conversations.send);return async function(o){const s=t&&e?{sessionId:t,visitorId:e}:await n();if(s){qe.value="",gc();try{const l=await r({sessionId:s.sessionId,visitorId:s.visitorId,content:o});l.ok?vn(s.visitorId):l.reason==="rate_limited"&&(at.value=Date.now()+l.retryAfterMs)}catch(l){console.error("[jexity] Failed to send message:",l)}}}}function bc(){const t=at.value,e=eo.value;T(()=>{if(t===null)return;const i=setInterval(()=>{eo.value=Date.now()},1e3),o=setTimeout(()=>{at.value=null},Math.max(0,t-Date.now()));return()=>{clearInterval(i),clearTimeout(o)}},[t]);const n=t!==null,r=n?Math.max(0,Math.ceil((t-e)/1e3)):0;return{isActive:n,remainingSeconds:r}}function yc(){const t=R(),{isActive:e,remainingSeconds:n}=bc();return e?c("div",{class:"jex-rate-limit-notice",role:"status","aria-live":"polite",children:t.errorRateLimited.replace("{seconds}",String(n))}):null}const Pe=E(null);function vc(){const t=R(),e=Pe.value;if(e===null)return null;const n=e==="no-token"?t.errorSessionNoToken:e==="unauthorized"?t.errorSessionUnauthorized:e==="network"?t.errorNetwork:t.somethingWentWrong;return c("div",{class:"jex-session-error-notice",role:"alert","aria-live":"assertive",children:n})}function _c({size:t=18}){return c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M22 2 11 13"}),c("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}const no=132;function wc({onSend:t}){const e=le(null),n=le(null);T(()=>{const l=e.current;if(!l)return;l.style.height="0";const a=Math.min(l.scrollHeight,no);l.style.height=`${a}px`,l.style.overflowY=l.scrollHeight>no?"auto":"hidden"},[qe.value]);function r(l){l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),t())}function i(){n.current?.click()}function o(l){const a=l.currentTarget;a.files&&a.files.length>0&&fc(a.files),a.value=""}function s(l){const a=l.target;(a===l.currentTarget||!a.closest("button, textarea, img"))&&e.current?.focus()}return{textareaRef:e,fileInputRef:n,onKeyDown:r,onAttachClick:i,onFilesPicked:o,onCardClick:s}}function kc({isStreaming:t,disabled:e,inputDisabled:n,onSend:r}){const i=R(),o=qe,s=se,{textareaRef:l,fileInputRef:a,onKeyDown:u,onAttachClick:d,onFilesPicked:h,onCardClick:f}=wc({onSend:r}),p=o.value.trim().length>0,g=s.value.length>0,m=(p||g)&&!e;return c("div",{class:"jex-composer-card",onClick:f,children:[g&&c("div",{class:"jex-composer-attachments",role:"list",children:s.value.map(x=>c("div",{class:"jex-attachment-chip",role:"listitem",children:[c("img",{src:x.previewUrl,alt:x.file.name,class:"jex-attachment-thumb"}),c("button",{type:"button",class:"jex-attachment-remove","aria-label":i.removeAttachmentAriaLabel,onClick:()=>{pc(x.id)},children:c("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},x.id))}),c("textarea",{ref:l,class:"jex-composer-textarea","aria-label":i.inputPlaceholder,placeholder:t?i.aiThinking:i.inputPlaceholder,value:o.value,rows:1,onInput:x=>{o.value=x.currentTarget.value},onKeyDown:u,disabled:n}),c("div",{class:"jex-composer-actions",children:[c("div",{class:"jex-composer-actions-left",children:[c("input",{ref:a,class:"jex-visually-hidden",type:"file",accept:"image/*",multiple:!0,onChange:h,tabIndex:-1,"aria-hidden":"true"}),c("button",{type:"button",class:"jex-attach-btn","aria-label":i.attachComingSoon,title:i.attachComingSoon,disabled:!0,onClick:d,children:c("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:c("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),c("button",{class:`jex-send-btn${m?" jex-send-btn-active":""}`,type:"button",onClick:r,"aria-label":i.sendAriaLabel,disabled:e||!p&&!g,children:c(_c,{size:16})})]})]})}function Sc({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:o,onStartFresh:s}){const l=R(),a=qe,u=xc({sessionId:t,visitorId:e,ensureSession:o}),d=at.value!==null&&at.value>Date.now(),h=n||r||d;if(i==="resolved")return c("div",{class:"jex-chat-input-resolved",children:[c("div",{class:"jex-resolved-notice",children:l.sessionResolved}),c("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{s()},children:l.startNewConversation})]});async function f(){const p=a.value.trim();!p||h||await u(p)}return c("div",{class:"jex-chat-input",children:[c(yc,{}),c(vc,{}),c(kc,{isStreaming:r,disabled:h,inputDisabled:n||r,onSend:f})]})}function jc(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function Oe({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:o,botAvatarUrl:s}){const l=R(),a=!!r,[u,d]=C(!1),h=je(()=>d(!0),[]),f=l.replyTo.replace("{name}",i??""),p=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return c("div",{class:"jex-message-row bot",children:[c("div",{class:`jex-avatar ${a?"jex-avatar-agent":"jex-avatar-bot"}`,children:a&&o&&!u?c("img",{src:o,alt:i??"",class:"jex-avatar-img",onError:h}):a?c("span",{class:"jex-avatar-initials",children:jc(i??"")}):s&&!u?c("img",{src:s,alt:"",class:"jex-avatar-img",onError:h}):c(jn,{size:14})}),c("div",{class:"jex-message-content",children:[c("div",{class:p,children:[c(lc,{text:t}),e&&c("span",{class:"jex-streaming-cursor"})]}),a&&i&&c("div",{class:"jex-message-author-row",children:[c("span",{class:"jex-message-author",children:i}),c("button",{type:"button",class:"jex-reply-tag-btn","aria-label":f,title:f,onClick:()=>{cc(i)},children:c(vl,{size:12})})]})]})]})}function Cc({text:t}){return c("div",{class:"jex-message user",children:t})}function ro(){return wt(Le.functions.chat.public.helpdesk.submitEscalation)}function Tc({message:t,sessionId:e,visitorId:n}){const r=R();return t.formData?c("div",{class:"jex-inline-form-submitted",children:[c("span",{class:"jex-inline-form-check",children:"✓"}),c("div",{children:[c("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),c("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):c("div",{class:"jex-message-row bot",children:c(Rc,{messageId:t._id,sessionId:e,visitorId:n})})}function Rc({messageId:t,sessionId:e,visitorId:n}){const r=R(),[i,o]=C(""),[s,l]=C(""),[a,u]=C(!1),d=ro();async function h(f){if(f.preventDefault(),!a){u(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:s.trim()})}catch(p){console.error("[FormMessage] Submit failed:",p),u(!1)}}}return c("div",{class:"jex-inline-form",children:[c("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),c("form",{class:"jex-form",onSubmit:f=>{h(f)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:f=>{o(f.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:s,required:!0,disabled:a,onInput:f=>{l(f.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),c("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}const Ac={crawl:"🌐",file:"📄",snippet:"💡",qa:"❓"};function $c({sources:t}){const e=R(),[n,r]=C(!1);return t.length===0?null:c("div",{class:"jex-sources-row",children:[c("button",{type:"button",class:"jex-sources-toggle",onClick:()=>{r(i=>!i)},"aria-expanded":n,children:[c("span",{class:"jex-sources-icon",children:"📖"}),c("span",{children:(t.length===1?e.sourcesCountOne:e.sourcesCountOther).replace("{count}",String(t.length))}),c("span",{class:`jex-sources-chevron${n?" jex-sources-chevron--open":""}`,children:"▾"})]}),n?c("div",{class:"jex-sources-pills",children:t.map((i,o)=>{const s=i.sourceType==="crawl",l=Ec(i),a=s&&i.url?`${i.title}
69
+ ${i.url}`:i.title,u=c(B,{children:[typeof i.id=="number"?c("span",{class:"jex-source-id",children:i.id}):null,c("span",{class:"jex-source-type",children:Ac[i.sourceType]}),c("span",{class:"jex-source-label",children:l}),c("span",{class:"jex-source-score",children:["· ",i.score.toFixed(2)]})]});return s&&i.url?c("a",{class:"jex-source-pill",href:i.url,target:"_blank",rel:"noopener noreferrer",title:a,children:u},o):c("span",{class:"jex-source-pill",title:a,children:u},o)})}):null]})}function Ec(t){if(t.sourceType==="crawl"&&t.url)try{const e=new URL(t.url);return!e.pathname||e.pathname==="/"?e.hostname:e.pathname}catch{}return t.title}function Ic(){return c("div",{class:"jex-typing",children:[c("span",{}),c("span",{}),c("span",{})]})}const Mc=/\s?\[\d+\]/g;function io(t){return t.replace(Mc,"")}function qc({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:o,visitorId:s}){const l=R(),a=le(null),[u,d]=C(null),h=le(null);return T(()=>{if(!s||!t||t.length===0)return;const f=t[t.length-1];f.role==="assistant"&&f.status!=="streaming"&&f._id!==h.current&&(h.current=f._id,vn(s))},[t,s]),T(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),c("div",{class:"jex-chat-messages",children:[c(Oe,{text:e}),n&&r&&i?c("div",{class:"jex-session-prompt",children:[c("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),c("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?c("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(f=>{if(f.contentType==="human-notice"){const g=f.noticeKind==="agent-joined"?l.noticeAgentJoined.replace("{name}",f.noticeData?.agentName??""):f.noticeKind==="human-requested"?l.noticeHumanRequested:f.noticeKind==="human-requested-form"?l.noticeHumanRequestedForm:f.noticeKind==="message-received"?l.noticeMessageReceived:f.noticeKind==="agent-handling"?l.noticeAgentHandling:f.content;return c(Oe,{text:g},f._id)}if(f.contentType==="escalation-form"&&o&&s)return Ga.value==="screen"&&!f.formData?u===f._id?null:c("div",{class:"jex-inline-form jex-inline-form-card",children:[c("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),c("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),c("button",{class:"jex-form-submit",type:"button",onClick:()=>{be({id:"escalation-form",formMessageId:f._id,sessionId:o,visitorId:s})},children:l.escalationPromptSubmit}),c("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(f._id)},children:l.escalationSkip})]},f._id):c(Tc,{message:f,sessionId:o,visitorId:s},f._id);if(f.contentType==="escalation-confirm"){const g=f.noticeKind==="escalation-confirmed"?l.noticeEscalationConfirmed.replace("{name}",f.noticeData?.visitorName??"").replace("{email}",f.noticeData?.visitorEmail??"").replace("{ref}",f.noticeData?.visitorId??""):f.content;return c(Oe,{text:g},f._id)}if(f.role==="user")return c(Cc,{text:f.content},f._id);const p={authorId:f.authorId,authorName:f.authorName,authorImage:f.authorImage};return f.status==="streaming"&&f.content===""?c(Ic,{},f._id):f.status==="streaming"?c(Oe,{text:io(f.content),streaming:!0,...p},f._id):f.status==="error"?c(Oe,{text:f.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},f._id):c("div",{children:[c(Oe,{text:io(f.content),...p}),f.sources&&f.sources.length>0?c($c,{sources:f.sources}):null]},f._id)}),c("div",{ref:a})]})}function Pn({message:t}){const[e,n]=C(!1);return T(()=>{const r=setTimeout(()=>{n(!0)},80);return()=>{clearTimeout(r)}},[]),e?c("div",{class:"jex-overlay jex-loading",children:[c("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&c("p",{class:"jex-loading-message",children:t})]}):null}function Lc({sessionId:t,visitorId:e}){const n=ui(Le.functions.chat.public.conversations.listBySession,t&&e?{sessionId:t,visitorId:e}:"skip"),r=ui(Le.functions.chat.public.sessions.getSessionStatus,t&&e?{sessionId:t,visitorId:e}:"skip"),i=t!==null&&n===void 0,o=n?.some(s=>s.status==="streaming")??!1;return{conversations:n,sessionStatus:r??null,isLoading:i,isStreaming:o}}function Pc({greeting:t,orgSlug:e,projSlug:n,sessionId:r,visitorId:i,isLoading:o,sessionNotFound:s,resumeFailed:l,isOrgDeleted:a,ensureSession:u,startFresh:d}){const h=R(),{conversations:f,sessionStatus:p,isLoading:g,isStreaming:m}=Lc({sessionId:r,visitorId:i}),x=le((()=>{const M=tt.peek();return M!==null?M:Ti.peek()?"resume":"fresh"})()).current;if(T(()=>{tt.value=null},[]),T(()=>{u()},[u]),T(()=>{i&&vn(i)},[i]),a)return c("div",{class:"jex-chat-messages",children:c("div",{class:"jex-session-notice",children:h.chatNoLongerAvailable})});const v=x==="fresh"&&!r,y=x==="resume"&&(!r||g);return v?c(Pn,{message:h.startingConversation}):y?c(Pn,{message:h.resumeConversation}):c(B,{children:[c(qc,{conversations:f,greeting:t,sessionNotFound:s,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),c(Sc,{sessionId:r,visitorId:i,isLoading:o,isStreaming:m,sessionStatus:p,ensureSession:u,onStartFresh:d})]})}function Oc({formMessageId:t,sessionId:e,visitorId:n}){const r=R(),[i,o]=C(""),[s,l]=C(""),a=ro(),[u,d]=C(!1),[h,f]=C(null);async function p(g){g.preventDefault(),d(!0),f(null);try{await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:s.trim()}),At()}catch(m){console.error("[EscalationFormScreen] Submit failed:",m),f(r.escalationSubmitFailed)}finally{d(!1)}}return c("div",{class:"jex-form-screen",children:[c("h2",{class:"jex-form-title",children:r.escalationFormTitle}),c("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h&&c("div",{class:"jex-form-error",role:"alert",children:h}),c("form",{class:"jex-form",onSubmit:g=>{p(g)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:g=>{o(g.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:s,required:!0,onInput:g=>{l(g.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",disabled:u,children:r.escalationSubmit})]}),c("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),c("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{At()},children:r.escalationSkip})]})}function Nc(){return wt(Le.functions.chat.public.helpdesk.createEscalationRequest)}function oo({sessionId:t,visitorId:e}){const n=R(),[r,i]=C(!1),[o,s]=C(null),l=Nc();async function a(){if(!t||!e)return;const u=ue.value;if(u){i(!0),s(null);try{const d=await l({sessionId:t,visitorId:e,bootstrapToken:u});if(d.skipForm)return;be({id:"escalation-form",formMessageId:d.formMessageId,sessionId:t,visitorId:e})}catch(d){const h=d instanceof Error?d.message:String(d);s(/RATE_LIMITED|Too many/.test(h)?n.handoffRateLimited:n.handoffFailed)}finally{i(!1)}}}return c(B,{children:[c("button",{class:"jex-header-handoff",type:"button",onClick:()=>{a()},disabled:r||!t||!e,"aria-label":n.talkToHumanAria,title:n.talkToHuman,children:c("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[c("path",{d:"M3 14v-3a9 9 0 0 1 18 0v3"}),c("path",{d:"M21 14a2 2 0 0 1-2 2h-1a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3z"}),c("path",{d:"M3 14a2 2 0 0 0 2 2h1a1 1 0 0 0 1-1v-4a1 1 0 0 0-1-1H3z"}),c("path",{d:"M21 14v3a4 4 0 0 1-4 4h-3"})]})}),o&&c("div",{class:"jex-handoff-error",role:"alert",children:o})]})}async function zc(){const t=_i.value;if(!t)return console.warn("[JexityChat] Bootstrap refresh skipped — inputs missing"),{ok:!1,reason:"no-inputs"};const e=await xn(t.orgSlug,t.siteUrl,t.projSlug);if(!e.ok)return console.warn("[JexityChat] Bootstrap refresh failed:",e.error),{ok:!1,reason:e.error};const n=e.token;return ue.value=n,{ok:!0,token:n}}function so(t){return ao(t)?"unauthorized":t instanceof Error&&/network|fetch|failed to fetch/i.test(t.message)?"network":"unknown"}function ao(t){return t instanceof mt?t.data?.code==="UNAUTHORIZED_ORIGIN":!1}function Bc(t=1e4){return ue.value?Promise.resolve(ue.value):new Promise(e=>{let n=!1;const r=s=>{n||(n=!0,clearTimeout(i),o(),e(s))},i=setTimeout(()=>{r(null)},t),o=ue.subscribe(s=>{s&&r(s)})})}function Fc(t,e){const n=le(null),r=et(!1),i=et(!1),o=et(!1),s=et(null),l=wt(Le.functions.chat.public.sessions.createOrResume),a=async p=>{const g=await Bc();if(!g)return console.warn("[JexityChat] No bootstrap token after 10s — session creation blocked."),Pe.value="no-token",null;const m=y=>({orgSlug:t,...e?{projSlug:e}:{},visitorId:p,bootstrapToken:y,...Tt.value?{source:Tt.value}:{}});wn.value=!0;let x;try{try{x=await l(m(g))}catch(y){if(!ao(y))throw y;const M=await zc();if(!M.ok)return Pe.value=M.reason==="rate_limited"?"network":"unauthorized",null;x=await l(m(M.token))}}finally{wn.value=!1}Pe.value=null,s.value=x.status;const v={sessionId:x.sessionId,visitorId:p};return n.current=v,{session:v,result:x}},u=je(async()=>{if(n.current)return n.current;if(o.value)return null;r.value=!0;const p=xe.value!==null,g=xe.value??Ri();try{const m=await a(g);return m?(p&&m.result.isNew&&(i.value=!0,o.value=!0),m.session):null}catch(m){return console.error("[JexityChat] Failed to create session:",m),Pe.value=so(m),null}finally{r.value=!1}},[t,e,l,r,i,o]),d=je(()=>{n.current=null,i.value=!1,o.value=!1},[i,o]);T(()=>Ya(d),[d]);const h=je(async()=>{n.current=null,o.value=!1,i.value=!1;const p=Ri();r.value=!0;try{return(await a(p))?.session??null}catch(g){return console.error("[JexityChat] Failed to create fresh session:",g),Pe.value=so(g),null}finally{r.value=!1}},[t,e,l,r,i,o,s]),f=n.current;return{sessionId:f?.sessionId??null,visitorId:f?.visitorId??null,isLoading:r.value,sessionNotFound:i.value,resumeFailed:o.value,sessionStatus:s.value,isOrgDeleted:s.value==="org_deleted",ensureSession:u,startFresh:h,resetSession:d}}function Qc(){const t=R(),[e,n]=C(""),[r,i]=C(""),[o,s]=C("");async function l(a){a.preventDefault(),_n({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();_n({id:"confirmation",ref:u})}return c("div",{class:"jex-form-screen",children:[c("h2",{class:"jex-form-title",children:t.submitTicket}),c("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[c("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),c("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),c("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:o,required:!0,onInput:a=>{s(a.currentTarget.value)}}),c("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Dc({ticketRef:t}){const e=R();return c("div",{class:"jex-confirmation",children:[c("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),c("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),c("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),c("div",{class:"jex-confirmation-ref",children:t}),c("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),c("button",{class:"jex-confirmation-done",onClick:()=>{I.value=!1},children:e.done})]})}function Uc({message:t,onRetry:e,onBack:n}){const r=R();return c("div",{class:"jex-overlay jex-error",children:[c("p",{class:"jex-error-message",children:t}),c("div",{class:"jex-error-actions",children:[e&&c("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&c("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function lo({greeting:t,title:e,orgSlug:n,projSlug:r,sessionId:i,visitorId:o,isLoading:s,sessionNotFound:l,resumeFailed:a,isOrgDeleted:u,ensureSession:d,startFresh:h,resetSession:f}){const p=z.value,g=p[p.length-1],m=[...p].reverse().find(x=>x.id==="confirmation");return c("div",{class:"jex-screen-container",children:[g.id==="home"&&c(dl,{greeting:t,title:e,onStartFresh:h,onResetSession:f}),g.id==="selection"&&c(fl,{title:e}),g.id==="form"&&c(Qc,{}),g.id==="escalation-form"&&c(Oc,{formMessageId:g.formMessageId,sessionId:g.sessionId,visitorId:g.visitorId}),g.id==="confirmation"&&m&&c(Dc,{ticketRef:m.ref}),g.id==="chat"&&c(Pc,{greeting:t,orgSlug:n,projSlug:r,sessionId:i,visitorId:o,isLoading:s,sessionNotFound:l,resumeFailed:a,isOrgDeleted:u,ensureSession:d,startFresh:h}),g.id==="loading"&&c(Pn,{message:g.message}),g.id==="error"&&c(Uc,{message:g.message,onRetry:()=>_n({id:"loading"}),onBack:At})]})}function Vc({options:t}){za(t.orgSlug,t.projSlug,t.bootstrapToken,t.convexUrl);const e=Na(t.orgSlug,t.projSlug,t.convexUrl);Va(t.parentOrigin),T(()=>{Ja(),Ka()},[]);const{sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}=Fc(t.orgSlug,t.projSlug),h=Pa(t,e);T(()=>{bn.value=ki(h.locale)},[h.locale]),T(()=>{if(!I.value||h.mode==="embedded"||!window.matchMedia("(max-width: 480px), (pointer: coarse) and (max-width: 768px)").matches)return;const F=document.documentElement.style.overflow;return document.documentElement.style.overflow="hidden",()=>{document.documentElement.style.overflow=F}},[I.value,h.mode]),T(()=>{if(h.mode!=="embedded")try{return tl()}catch(G){console.warn("[JexityChat] Idle-lock watcher failed to start:",G);return}},[h.mode]);const f=h.position==="bottom-left",p=h.colorScheme==="dark"||h.colorScheme==="light"?h.colorScheme:"",g=nl({...t,primaryColor:h.primaryColor,accentColor:h.accentColor,fontFamily:h.fontFamily,fontSize:h.fontSize,borderRadius:h.borderRadius,windowWidth:h.windowWidth,windowHeight:h.windowHeight}),m=h.mode==="embedded",x=z.value,y=x[x.length-1]?.id==="chat",V=e!==null||m||!!t.parentOrigin?g:{...g,visibility:"hidden"};return c("div",{class:`jex-widget ${p}`.trim(),style:V,children:m?c("div",{class:"jex-embedded",children:[c(Mi,{title:h.title,rightAction:y?c(oo,{sessionId:n,visitorId:r}):null,showClose:!m}),c(lo,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}),!h.hideBranding&&c(qi,{})]}):c("div",{class:`jex-container${f?" jex-pos-left":""}`,children:[I.value&&c("div",{class:"jex-chat-window",children:[c(Mi,{title:h.title,rightAction:y?c(oo,{sessionId:n,visitorId:r}):null}),c(lo,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:o,resumeFailed:s,isOrgDeleted:l,ensureSession:a,startFresh:u,resetSession:d}),!h.hideBranding&&c(qi,{})]}),c(hl,{iconOption:h.triggerIcon,radius:h.triggerRadius,label:h.triggerLabel})]})})}const Hc='.jex-widget{--jex-primary: #115A62;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-radius: .75rem;--jex-font-family: "Inter", system-ui, -apple-system, sans-serif;--jex-font-size: 14px;--jex-window-width: 380px;--jex-window-height: 600px;--jex-shadow: 0 16px 48px -12px rgba(13, 127, 138, .25), 0 4px 16px rgba(0, 0, 0, .08);pointer-events:auto;--jex-bg-trigger: var(--jex-primary);--jex-bg-header: var(--jex-primary);--jex-bg-msg-user: var(--jex-primary);--jex-bg-send-btn: var(--jex-primary);--jex-bg-window: rgba(255, 255, 255, .95);--jex-bg-msg-bot: #f1f5f9;--jex-bg-input: rgba(247, 253, 253, .6);--jex-text-header: #ffffff;--jex-text-msg-user: #ffffff;--jex-text-msg-bot: #0f172a;--jex-text-main: #0f172a;--jex-text-muted: #64748b;--jex-bg-avatar-agent: #d1fae5;--jex-text-avatar-agent: #065f46;--jex-border-window: rgba(226, 232, 240, .8);--jex-border-input: rgba(203, 213, 225, .8);--jex-bg-glass: var(--jex-bg-window);--jex-border-glass: var(--jex-border-window);font-family:var(--jex-font-family);-webkit-font-smoothing:antialiased}.dark .jex-widget,.jex-widget.dark{--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-avatar-agent: #064e3b;--jex-text-avatar-agent: #6ee7b7;--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light){--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}}.jex-widget *{box-sizing:border-box;margin:0;padding:0}.jex-container{position:fixed;bottom:24px;right:24px;display:flex;flex-direction:column;align-items:flex-end;gap:16px;z-index:9999}.jex-container.jex-pos-left{right:auto;left:24px;align-items:flex-start}:host(.jex-mode-embedded){display:block;width:100%;height:100%}:host(.jex-mode-embedded) .jex-widget{width:100%;height:100%}.jex-embedded{display:flex;flex-direction:column;width:100%;height:100%;background:var(--jex-bg-window);border:1px solid var(--jex-border-window);overflow:hidden}.jex-embedded .jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-floating-button{height:56px;min-width:56px;padding:0;background:var(--jex-bg-trigger);color:var(--jex-text-header);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:var(--jex-shadow);transition:transform .3s cubic-bezier(.175,.885,.32,1.275),background .2s,width .3s ease,border-radius .3s ease}.jex-floating-button.jex-has-label{min-width:110px;padding:0 20px}.jex-fab-inner{display:flex;align-items:center;gap:12px}.jex-fab-label{font-size:15px;font-weight:600;white-space:nowrap}.jex-floating-button:hover{transform:scale(1.1);background:var(--jex-primary-hover)}.jex-floating-button:active{transform:scale(.95)}.jex-chat-window{width:var(--jex-window-width);height:var(--jex-window-height);max-height:calc(100vh - 120px);background:var(--jex-bg-window);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border:1px solid var(--jex-border-window);border-radius:calc(var(--jex-radius) * 2);box-shadow:var(--jex-shadow);display:flex;flex-direction:column;overflow:hidden;animation:jexSlideUp .4s cubic-bezier(.16,1,.3,1);transform-origin:bottom right;touch-action:manipulation}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) translateY(0)}}@media(max-width:480px),(pointer:coarse)and (max-width:768px){.jex-chat-window{position:fixed;inset:0;width:100vw;height:100vh;height:100dvh;max-height:none;border:none;border-radius:0;animation:jexSlideUpMobile .3s cubic-bezier(.16,1,.3,1);transform-origin:bottom center}.jex-container:has(.jex-chat-window) .jex-floating-button{display:none}}@keyframes jexSlideUpMobile{0%{opacity:0;transform:translateY(100%)}to{opacity:1;transform:translateY(0)}}.jex-chat-header{padding:20px;background:var(--jex-bg-header);color:var(--jex-text-header);display:flex;align-items:center;gap:12px;flex-shrink:0}.jex-header-info h3{font-size:16px;font-weight:600;color:var(--jex-text-header);margin:0}.jex-header-info p{font-size:12px;opacity:.8;color:var(--jex-text-header);margin:0}.jex-header-right{margin-left:auto;display:flex;align-items:center;gap:4px}.jex-header-handoff{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:transparent;border:1px solid color-mix(in srgb,currentColor 50%,transparent);border-radius:999px;padding:0;color:inherit;cursor:pointer;transition:background .15s ease,border-color .15s ease}.jex-header-handoff:hover:not(:disabled){background:color-mix(in srgb,currentColor 12%,transparent);border-color:currentColor}.jex-header-handoff:disabled{opacity:.5;cursor:not-allowed}.jex-header-close{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:transparent;border:none;border-radius:999px;padding:0;color:inherit;cursor:pointer;transition:background .15s ease}.jex-header-close:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.jex-handoff-error{position:absolute;top:100%;right:8px;background:#fee;color:#b00;padding:4px 8px;font-size:12px;border-radius:4px}.jex-header-back{background:none;border:none;color:var(--jex-text-header);cursor:pointer;padding:4px;display:flex;align-items:center;opacity:.8;transition:opacity .2s;flex-shrink:0}.jex-header-back:hover{opacity:1}.jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-home{flex:1;display:flex;flex-direction:column;padding:24px;gap:20px;overflow-y:auto}.jex-home-hero{display:flex;align-items:center;gap:14px;animation:jexFadeIn .4s ease both}.jex-home-avatar{position:relative;width:48px;height:48px;border-radius:14px;background:var(--jex-primary);color:var(--jex-text-header);display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 4px 12px color-mix(in srgb,var(--jex-primary) 30%,transparent)}.jex-home-status-dot{position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;border-radius:50%;background:#22c55e;border:2.5px solid var(--jex-bg-window);animation:jexPulse 2s ease-in-out infinite}@keyframes jexPulse{0%,to{box-shadow:0 0 #22c55e66}50%{box-shadow:0 0 0 6px #22c55e00}}.jex-home-hero-text{display:flex;flex-direction:column;gap:2px;min-width:0}.jex-home-title{font-size:17px;font-weight:700;color:var(--jex-text-main);margin:0;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.jex-home-status{font-size:12px;font-weight:500;color:#22c55e;letter-spacing:.02em}.jex-home-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:4px 16px 16px;padding:16px 18px;font-size:14px;line-height:1.55;color:var(--jex-text-main);animation:jexFadeIn .4s .1s ease both}.jex-home-greeting p{margin:0}@keyframes jexFadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.jex-home-actions{display:flex;flex-direction:column;gap:10px;animation:jexFadeIn .4s .2s ease both}.jex-home-start-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;padding:14px 20px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,transform .15s,box-shadow .2s;width:100%;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 25%,transparent)}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 35%,transparent)}.jex-home-start-btn:active{transform:translateY(0);box-shadow:0 1px 4px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card{display:flex;flex-direction:column;gap:8px;width:100%;text-align:left;padding:16px 18px;border-radius:14px;border:1.5px solid var(--jex-primary);background:color-mix(in srgb,var(--jex-primary) 6%,var(--jex-bg-window));cursor:pointer;font-family:inherit;transition:background .2s,border-color .2s,transform .15s,box-shadow .2s;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 12%,transparent)}.jex-home-resume-card:hover{background:color-mix(in srgb,var(--jex-primary) 10%,var(--jex-bg-window));transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card:active{transform:translateY(0)}.jex-home-resume-top{display:flex;align-items:center;justify-content:space-between}.jex-home-resume-label{font-size:14px;font-weight:600;color:var(--jex-primary)}.jex-home-resume-arrow{color:var(--jex-primary);opacity:.6;transition:opacity .2s,transform .2s}.jex-home-resume-card:hover .jex-home-resume-arrow{opacity:1;transform:translate(2px)}.jex-home-resume-ref{font-family:ui-monospace,Cascadia Code,Fira Code,monospace;font-size:13px;font-weight:600;letter-spacing:.06em;color:var(--jex-text-muted)}.jex-home-history{display:flex;flex-direction:column;gap:8px}.jex-home-resume-meta{font-size:11px;opacity:.7;margin-top:4px}.jex-home-new-btn{background:transparent;color:var(--jex-text-muted);border:1px solid var(--jex-border-input);border-radius:12px;padding:12px 20px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;transition:color .2s,border-color .2s,background .2s;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted);background:color-mix(in srgb,var(--jex-primary) 3%,transparent)}.jex-session-ref{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:8px;font-size:12px}.jex-session-ref-label{color:var(--jex-text-muted);font-weight:500}.jex-session-ref-code{color:var(--jex-primary);font-weight:700;font-family:ui-monospace,Cascadia Code,monospace;letter-spacing:.05em}.jex-chat-messages{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}.jex-message-row{display:flex;align-items:flex-end;gap:8px;max-width:85%}.jex-message-row.bot{align-self:flex-start}.jex-message-content{flex:1;min-width:0}.jex-avatar{width:24px;height:24px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:2px}.jex-avatar-bot{background:var(--jex-bg-msg-bot);color:var(--jex-primary)}.jex-avatar-agent{background:var(--jex-bg-avatar-agent)}.jex-avatar-img{width:100%;height:100%;border-radius:50%;object-fit:cover}.jex-avatar-initials{font-size:9px;font-weight:700;color:var(--jex-text-avatar-agent)}.jex-message-author-row{display:flex;align-items:center;gap:6px;margin-top:2px;padding-left:4px}.jex-message-author{font-size:10px;color:var(--jex-text-muted)}.jex-reply-tag-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;border-radius:4px;background:transparent;color:var(--jex-text-muted, #6b7280);cursor:pointer;transition:background .15s,color .15s}.jex-reply-tag-btn:hover{background:#0000000f;color:var(--jex-primary, #115A62)}.jex-reply-tag-btn:focus-visible{outline:2px solid var(--jex-primary, #115A62);outline-offset:1px}.jex-message{padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);color:var(--jex-text-msg-bot);border-bottom-left-radius:4px}.jex-message.user{align-self:flex-end;max-width:80%;background:var(--jex-bg-msg-user);color:var(--jex-text-msg-user);border-bottom-right-radius:4px}.jex-typing{align-self:flex-start;display:flex;gap:4px;padding:12px 16px}.jex-typing span{width:8px;height:8px;border-radius:50%;background:var(--jex-text-muted);animation:jexTypingDot 1.2s infinite ease-in-out}.jex-typing span:nth-child(2){animation-delay:.2s}.jex-typing span:nth-child(3){animation-delay:.4s}@keyframes jexTypingDot{0%,80%,to{transform:scale(.8);opacity:.4}40%{transform:scale(1);opacity:1}}.jex-md{word-break:break-word;overflow-wrap:anywhere}.jex-md p{margin:0 0 8px}.jex-md p:last-child{margin-bottom:0}.jex-md strong{font-weight:600}.jex-md em{font-style:italic}.jex-md ul,.jex-md ol{margin:0 0 8px;padding-left:20px}.jex-md ul:last-child,.jex-md ol:last-child{margin-bottom:0}.jex-md ul{list-style-type:disc}.jex-md ol{list-style-type:decimal}.jex-md li{margin-bottom:2px}.jex-md li:last-child{margin-bottom:0}.jex-md a{color:var(--jex-primary);text-decoration:underline;text-underline-offset:2px}.jex-md a:hover{opacity:.8}.jex-md code{background:#00000014;padding:1px 5px;border-radius:4px;font-size:.9em;font-family:ui-monospace,Cascadia Code,Fira Code,monospace}.jex-md pre{background:#0000000f;border-radius:8px;padding:10px 12px;margin:0 0 8px;overflow-x:auto;font-size:.85em}.jex-md pre:last-child{margin-bottom:0}.jex-md pre code{background:none;padding:0;border-radius:0;font-size:inherit}.jex-md h1,.jex-md h2,.jex-md h3,.jex-md h4{font-weight:600;margin:8px 0 4px}.jex-md h1:first-child,.jex-md h2:first-child,.jex-md h3:first-child,.jex-md h4:first-child{margin-top:0}.jex-md h3{font-size:1em}.jex-md h4{font-size:.95em}.jex-md hr{border:none;border-top:1px solid var(--jex-border-window);margin:8px 0}.jex-md blockquote{border-left:3px solid var(--jex-primary);margin:0 0 8px;padding:4px 12px;color:var(--jex-text-muted)}.jex-md blockquote:last-child{margin-bottom:0}.dark .jex-md code,.jex-widget.dark .jex-md code{background:#ffffff1a}.dark .jex-md pre,.jex-widget.dark .jex-md pre{background:#ffffff14}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-md code{background:#ffffff1a}:host:not(.light) .jex-widget:not(.light) .jex-md pre{background:#ffffff14}}.jex-streaming-cursor:after{content:"◊";margin-left:2px;animation:jexBlinkCursor .8s ease-in-out infinite}@keyframes jexBlinkCursor{0%,to{opacity:1}50%{opacity:0}}.jex-session-notice{align-self:center;text-align:center;padding:8px 16px;margin:8px 0;font-size:12px;color:var(--jex-text-muted);background:var(--jex-bg-input, #f1f5f9);border-radius:8px;line-height:1.4}.jex-message-error{background:var(--jex-bg-error, #fef2f2)!important;border-color:var(--jex-border-error, #fecaca)!important;color:var(--jex-text-error, #991b1b)!important}.jex-chat-input{padding:12px 16px;border-top:1px solid var(--jex-border-window);display:flex;flex-direction:column;gap:8px;flex-shrink:0}.jex-composer-card{display:flex;flex-direction:column;gap:6px;padding:10px 12px 8px;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:16px;cursor:text;transition:border-color .15s ease,background .15s ease,box-shadow .15s ease}.jex-composer-card:focus-within{border-color:var(--jex-primary);background:var(--jex-bg-window);box-shadow:0 0 0 3px color-mix(in srgb,var(--jex-primary, #115A62) 14%,transparent)}.jex-composer-attachments{display:flex;flex-wrap:wrap;gap:6px;padding:2px 2px 4px}.jex-attachment-chip{position:relative;width:44px;height:44px;border-radius:8px;overflow:hidden;background:var(--jex-bg-msg-bot, #f1f5f9);flex-shrink:0;box-shadow:0 1px 2px #0000000f}.jex-attachment-thumb{width:100%;height:100%;object-fit:cover;display:block;pointer-events:none}.jex-attachment-remove{position:absolute;top:2px;right:2px;width:16px;height:16px;padding:0;border:none;border-radius:50%;background:#0f172ac7;color:#fff;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;opacity:0;transition:opacity .12s ease,transform .12s ease}.jex-attachment-chip:hover .jex-attachment-remove,.jex-attachment-chip:focus-within .jex-attachment-remove{opacity:1}.jex-attachment-remove:hover{transform:scale(1.08)}.jex-composer-textarea{width:100%;min-height:22px;background:transparent;border:none;outline:none;resize:none;padding:2px 4px;color:var(--jex-text-main);font-family:inherit;font-size:16px;line-height:1.45;overflow-y:hidden}.jex-composer-textarea::placeholder{color:var(--jex-text-muted);opacity:.85}.jex-composer-textarea:disabled{cursor:not-allowed;opacity:.7}.jex-composer-actions{display:flex;align-items:center;justify-content:space-between;gap:8px}.jex-composer-actions-left{display:inline-flex;align-items:center;gap:4px}.jex-attach-btn{width:30px;height:30px;padding:0;border:none;border-radius:50%;background:transparent;color:var(--jex-text-muted);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:background .12s ease,color .12s ease,transform .12s ease}.jex-attach-btn:hover:not(:disabled){background:color-mix(in srgb,var(--jex-text-muted, #64748b) 12%,transparent);color:var(--jex-text-main)}.jex-attach-btn:active:not(:disabled){transform:scale(.92)}.jex-attach-btn:disabled{opacity:.4;cursor:not-allowed}.jex-visually-hidden{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.jex-rate-limit-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-muted, #64748b);font-size:12px;line-height:1.4;text-align:center}.jex-session-error-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-error, #fef2f2);border:1px solid var(--jex-border-error, #fecaca);color:var(--jex-text-error, #991b1b);font-size:12px;line-height:1.4;text-align:center}.jex-chat-input input{flex:1;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:12px;padding:10px 14px;color:var(--jex-text-main);outline:none;font-family:inherit;font-size:14px}.jex-chat-input input:focus{border-color:var(--jex-primary)}.jex-send-btn{background:color-mix(in srgb,var(--jex-text-muted, #64748b) 18%,transparent);color:var(--jex-text-muted);border:none;border-radius:999px;width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:background .15s ease,color .15s ease,opacity .15s ease,transform .15s ease;flex-shrink:0}.jex-send-btn-active{background:var(--jex-bg-send-btn, var(--jex-primary));color:var(--jex-text-header, #fff)}.jex-send-btn-active:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-send-btn:active:not(:disabled){transform:scale(.9)}.jex-send-btn:disabled{opacity:.45;cursor:default}.jex-widget-footer{display:flex;align-items:center;justify-content:center;padding:8px 16px;border-top:1px solid var(--jex-border-glass);background:#00000005;flex-shrink:0}.jex-widget.dark .jex-widget-footer{background:#ffffff05}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-widget-footer{background:#ffffff05}}.jex-branding{display:flex;align-items:center;gap:6px;text-decoration:none;color:var(--jex-text-muted);font-size:11px;font-weight:500;transition:color .2s}.jex-branding:hover{color:var(--jex-text-main)}.jex-branding-icon{color:var(--jex-primary)}.jex-branding span strong{font-weight:700;color:var(--jex-text-main)}.jex-locale-select-wrapper{position:relative;display:flex;align-items:center}.jex-locale-select{appearance:none;-webkit-appearance:none;background:transparent;border:1px solid transparent;padding:4px 20px 4px 6px;border-radius:6px;font-family:inherit;font-size:11px;font-weight:600;color:var(--jex-text-muted);background-color:transparent;cursor:pointer;outline:none;transition:all .2s ease}.jex-locale-select option{background-color:#fff;color:#0f172a}.jex-locale-select:hover,.jex-locale-select:focus-visible{color:var(--jex-text-main);background:#0000000a}.jex-widget.dark .jex-locale-select:hover,.jex-widget.dark .jex-locale-select:focus-visible{background:#ffffff0d}.jex-widget.dark .jex-locale-select option{background-color:#0f172a;color:#f8fafc}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-locale-select:hover,:host:not(.light) .jex-widget:not(.light) .jex-locale-select:focus-visible{background:#ffffff0d}:host:not(.light) .jex-widget:not(.light) .jex-locale-select option{background-color:#0f172a;color:#f8fafc}}.jex-locale-select:focus-visible{border-color:var(--jex-primary)}.jex-locale-chevron{position:absolute;right:4px;pointer-events:none;color:var(--jex-text-muted);transition:color .2s ease}.jex-locale-select-wrapper:hover .jex-locale-chevron{color:var(--jex-text-main)}.jex-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:var(--jex-bg-window, #fff);z-index:10;padding:24px;text-align:center}.jex-loading-spinner{width:32px;height:32px;border:3px solid var(--jex-border-input, #e2e8f0);border-top-color:var(--jex-primary, #115A62);border-radius:50%;animation:jex-spin .7s linear infinite}@keyframes jex-spin{to{transform:rotate(360deg)}}.jex-loading-message{font-size:14px;color:var(--jex-text-muted, #64748b)}.jex-error-message{font-size:14px;color:var(--jex-text-main, #334155)}.jex-error-actions{display:flex;gap:8px}.jex-error-retry,.jex-error-back{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:none}.jex-error-retry{background:var(--jex-primary, #115A62);color:#fff}.jex-error-back{background:transparent;color:var(--jex-text-muted, #64748b);border:1px solid var(--jex-border-input, #e2e8f0)}.jex-selection{display:flex;flex-direction:column;gap:12px;padding:24px 16px;height:100%}.jex-selection-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 8px}.jex-selection-options{display:flex;flex-direction:column;gap:10px}.jex-selection-option{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:16px;border-radius:12px;border:1px solid var(--jex-border-window, #e2e8f0);background:transparent;cursor:pointer;text-align:left;transition:border-color .15s ease,background .15s ease}.jex-selection-option:hover{border-color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 5%,transparent)}.jex-selection-icon{font-size:20px}.jex-selection-label{font-size:14px;font-weight:600;color:var(--jex-text-main, #0f172a)}.jex-selection-sub{font-size:12px;color:var(--jex-text-muted, #64748b)}.jex-form-screen{display:flex;flex-direction:column;padding:20px 16px;height:100%;overflow-y:auto}.jex-form-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 16px}.jex-form{display:flex;flex-direction:column;gap:10px}.jex-form-input,.jex-form-textarea{padding:10px 12px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:14px;background:transparent;color:var(--jex-text-main, #0f172a);outline:none}@media(pointer:coarse){.jex-form-input,.jex-form-textarea{font-size:16px}}.jex-form-input:focus,.jex-form-textarea:focus{border-color:var(--jex-primary, #115A62)}.jex-form-textarea{min-height:80px;resize:vertical}.jex-form-submit{padding:10px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer;margin-top:4px}.jex-inline-form{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-title{font-weight:600;font-size:15px;color:var(--jex-text-main, #0f172a);margin:0}.jex-inline-form-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.4;margin:0 0 4px}.jex-inline-form-consent{font-size:11px;color:var(--jex-text-muted, #64748b);line-height:1.3;margin-top:4px;text-align:center}.jex-inline-form .jex-form-submit:disabled{opacity:.7;cursor:not-allowed}.jex-escalation-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.45;margin:0 0 8px}.jex-escalation-skip{padding:8px 12px;border:none;background:transparent;color:var(--jex-text-muted, #64748b);font-size:13px;cursor:pointer;text-decoration:underline;text-underline-offset:2px;text-align:center}.jex-escalation-skip:hover{color:var(--jex-text-main, #0f172a)}.jex-inline-form-card{position:relative;padding:14px;gap:8px}.jex-inline-form-dismiss{position:absolute;top:10px;right:10px;width:24px;height:24px;border-radius:50%;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-window, #fff);color:var(--jex-text-muted, #64748b);font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}.jex-inline-form-dismiss:hover{background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-check{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary) 15%,transparent);color:var(--jex-primary, #115A62);font-size:14px;font-weight:700;flex-shrink:0}.jex-inline-form-submitted-title{font-weight:600;font-size:var(--jex-font-size, 14px);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted-detail{font-size:12px;color:var(--jex-text-muted, #64748b);margin-top:2px}.jex-escalation-confirm{border-left:3px solid var(--jex-primary, #115A62);padding-left:8px}.jex-session-prompt{display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px 16px;margin:8px 0;text-align:center}.jex-session-prompt-text{font-size:13px;color:var(--jex-text-muted, #64748b)}.jex-session-prompt-btn{padding:8px 16px;border-radius:8px;border:1px solid var(--jex-primary, #115A62);background:transparent;color:var(--jex-primary, #115A62);font-size:13px;font-weight:600;cursor:pointer}.jex-session-prompt-btn:hover{background:color-mix(in srgb,var(--jex-primary) 10%,transparent)}.jex-chat-input-resolved{display:flex;flex-direction:column;align-items:center;gap:10px;padding:14px 16px;border-top:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-msg-bot, #f1f5f9);text-align:center}.jex-resolved-notice{font-size:13px;font-weight:500;color:var(--jex-text-muted, #64748b)}.jex-resolved-new-btn{padding:10px 20px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;width:100%}.jex-resolved-new-btn:hover{opacity:.9}.jex-confirmation{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 24px;height:100%;text-align:center}.jex-confirmation-icon{width:48px;height:48px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary, #115A62) 15%,transparent);color:var(--jex-primary, #115A62);font-size:22px;display:flex;align-items:center;justify-content:center}.jex-confirmation-title{font-size:18px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0}.jex-confirmation-body{font-size:13px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-ref{font-size:20px;font-weight:700;letter-spacing:.05em;color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 10%,transparent);padding:10px 20px;border-radius:10px}.jex-confirmation-hint{font-size:12px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-done{margin-top:8px;padding:10px 28px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer}.jex-home-lookup-link{background:none;border:none;font-size:12px;color:var(--jex-text-muted, #64748b);cursor:pointer;text-decoration:underline;padding:0;align-self:center}.jex-home-lookup{display:flex;gap:8px;width:100%;animation:jexFadeIn .4s .1s ease both}.jex-home-lookup-input{flex:1;padding:10px 14px;border-radius:10px;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-input);color:var(--jex-text-main);font-size:14px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}@media(pointer:coarse){.jex-home-lookup-input{font-size:16px}}.jex-home-lookup-input::placeholder{font-family:inherit;letter-spacing:.04em;color:var(--jex-text-muted);opacity:.7}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:10px 16px;border-radius:10px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,opacity .2s;flex-shrink:0}.jex-home-lookup-submit:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-home-lookup-submit:disabled{opacity:.4;cursor:default}.jex-sources-row{margin-top:6px;margin-left:32px;display:flex;flex-direction:column;gap:6px}.jex-sources-toggle{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;background:transparent;border:none;border-radius:6px;cursor:pointer;font-size:11px;color:var(--jex-text-muted, #6b7280);font-family:inherit;align-self:flex-start;transition:background .15s,color .15s}.jex-sources-toggle:hover{background:#0000000a;color:inherit}.jex-sources-icon{font-size:12px;line-height:1}.jex-sources-chevron{display:inline-block;font-size:10px;transition:transform .15s}.jex-sources-chevron--open{transform:rotate(180deg)}.jex-sources-pills{display:flex;flex-wrap:wrap;align-items:center;gap:6px}.jex-source-pill{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:2px 8px;border-radius:999px;border:1px solid rgba(0,0,0,.1);background:#0000000a;color:var(--jex-text-muted, #6b7280);font-size:11px;text-decoration:none;cursor:pointer;transition:background .15s,color .15s}.jex-source-pill:hover{background:#00000014;color:inherit}.jex-source-id{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 4px;border-radius:4px;background:var(--jex-primary, #115A62);color:#fff;font-size:10px;font-weight:600;line-height:1;flex-shrink:0;font-variant-numeric:tabular-nums}.jex-source-type{font-size:10px;flex-shrink:0}.jex-source-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}.jex-source-score{opacity:.6;flex-shrink:0;font-variant-numeric:tabular-nums}';function Wc(t){const e=document.createElement("style");e.textContent=Hc,t.appendChild(e)}const Jc="https://festive-mouse-978.eu-west-1.convex.cloud";let On=null;function Kc(t){const e=t??Jc;if(!e)throw new Error("[jexity] No Convex URL — set VITE_CONVEX_URL at build time or data-convex-url on the script tag");return On||(On=new ya(La(e))),On}function Gc(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Wc(n),Tt.value=e.source,ue.value=e.bootstrapToken,z.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),I.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),fe(c(_a,{client:Kc(e.convexUrl),children:c(Vc,{options:e})}),r),function(){fe(null,r),I.value=!1,Tt.value=void 0,ue.value=void 0,z.value=[{id:"home"}]}}function Zc(t,e,n){const r=Gc(t,e),i=new Set,o=I.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){o(),i.clear(),r(),n&&n()},open(){I.value=!0},close(){I.value=!1},toggle(){I.value=!I.value},get isOpen(){return I.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let lt=null;function Yc(t){lt&&lt.shutdown();let e;t.container?e=typeof t.container=="string"?document.querySelector(t.container):t.container:(e=document.createElement("div"),e.id="jexity-chat-widget",document.body.appendChild(e));const n=Zc(e,t,()=>{t.container||e.remove(),lt===n&&(lt=null)});return lt=n,n}function he(t,e){return t.getAttribute(e)??void 0}async function co(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const e=t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",n=t.getAttribute("data-proj-slug")??void 0,r=he(t,"data-convex-url")??"https://festive-mouse-978.eu-west-1.convex.cloud"??"",i=mn(r),o=await xn(e,i,n);if(!o.ok){const l=window.location.origin,a=n?`project '${e}/${n}'`:`org '${e}'`;o.error==="unauthorized"?console.warn(`[JexityChat] This domain is not authorized for ${a}. Add '${l}' under Allowed Domains in your Jexity dashboard.`):o.error==="not_found"?console.warn(`[JexityChat] No active widget config found for ${a}. Check that the org slug is correct and the widget is enabled.`):o.error==="rate_limited"?console.warn(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${o.retryAfterSec??60}s.`):console.warn(`[JexityChat] Bootstrap failed (network error). Check that the Convex deployment is reachable at ${i}.`);return}const s={orgSlug:e,projSlug:n,bootstrapToken:o.token,position:he(t,"data-position")??void 0,theme:he(t,"data-theme")??void 0,greeting:he(t,"data-greeting"),title:he(t,"data-title"),primaryColor:he(t,"data-primary-color"),locale:he(t,"data-locale"),convexUrl:he(t,"data-convex-url")};window.JexityChat=Yc(s)}document.readyState==="complete"?co():window.addEventListener("load",co)})();
62
70
  //# sourceMappingURL=widget.js.map