@evelan/jexity-widget 0.7.0-canary.13 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/widget.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function(){"use strict";var Ae,m,jn,Cn,le,Rn,Tn,$n,An,Ct,Rt,Tt,In,Ie={},En=[],Pi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ee=Array.isArray;function D(t,e){for(var n in e)t[n]=e[n];return t}function $t(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function X(t,e,n){var r,i,s,o={};for(s in e)s=="key"?r=e[s]:s=="ref"?i=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?Ae.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return qe(t,o,r,i,null)}function qe(t,e,n,r,i){var s={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++jn,__i:-1,__u:0};return i==null&&m.vnode!=null&&m.vnode(s),s}function Mi(){return{current:null}}function M(t){return t.children}function L(t,e){this.props=t,this.context=e}function ye(t,e){if(e==null)return t.__?ye(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"?ye(t):null}function qn(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 qn(t)}}function At(t){(!t.__d&&(t.__d=!0)&&le.push(t)&&!Xe.__r++||Rn!=m.debounceRendering)&&((Rn=m.debounceRendering)||Tn)(Xe)}function Xe(){for(var t,e,n,r,i,s,o,l=1;le.length;)le.length>l&&le.sort($n),t=le.shift(),l=le.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,s=[],o=[],e.__P&&((n=D({},r)).__v=r.__v+1,m.vnode&&m.vnode(n),It(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,s,i??ye(r),!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Nn(s,n,o),r.__e=r.__=null,n.__e!=i&&qn(n)));Xe.__r=0}function Pn(t,e,n,r,i,s,o,l,a,c,d){var u,p,f,g,_,S,v,w=r&&r.__k||En,J=e.length;for(a=Li(n,e,w,a,J),u=0;u<J;u++)(f=n.__k[u])!=null&&(p=f.__i==-1?Ie:w[f.__i]||Ie,f.__i=u,S=It(t,f,p,i,s,o,l,a,c,d),g=f.__e,f.ref&&p.ref!=f.ref&&(p.ref&&qt(p.ref,null,f),d.push(f.ref,f.__c||g,f)),_==null&&g!=null&&(_=g),(v=!!(4&f.__u))||p.__k===f.__k?a=Mn(f,a,t,v):typeof f.type=="function"&&S!==void 0?a=S:g&&(a=g.nextSibling),f.__u&=-7);return n.__e=_,a}function Li(t,e,n,r,i){var s,o,l,a,c,d=n.length,u=d,p=0;for(t.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(a=s+p,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?qe(null,o,null,null,null):Ee(o)?qe(M,{children:o},null,null,null):o.constructor==null&&o.__b>0?qe(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,l=null,(c=o.__i=Oi(o,n,a,u))!=-1&&(u--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(i>d?p--:i<d&&p++),typeof o.type!="function"&&(o.__u|=4)):c!=a&&(c==a-1?p--:c==a+1?p++:(c>a?p--:p++,o.__u|=4))):t.__k[s]=null;if(u)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=ye(l)),Bn(l,l));return r}function Mn(t,e,n,r){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Mn(i[s],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=ye(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"||(Ee(t)?t.some(function(n){Y(n,e)}):e.push(t)),e}function Oi(t,e,n,r){var i,s,o,l=t.key,a=t.type,c=e[n],d=c!=null&&(2&c.__u)==0;if(c===null&&t.key==null||d&&l==c.key&&a==c.type)return n;if(r>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<e.length;)if((c=e[o=i>=0?i--:s++])!=null&&(2&c.__u)==0&&l==c.key&&a==c.type)return o}return-1}function Ln(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Pi.test(e)?n:n+"px"}function Ye(t,e,n,r,i){var s,o;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||Ln(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Ln(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(An,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?r?n.u=r.u:(n.u=Ct,t.addEventListener(e,s?Tt:Rt,s)):t.removeEventListener(e,s?Tt:Rt,s);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 On(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Ct++;else if(e.t<n.u)return;return n(m.event?m.event(e):e)}}}function It(t,e,n,r,i,s,o,l,a,c){var d,u,p,f,g,_,S,v,w,J,K,ae,U,qi,jt,Ze,wn,Z=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),s=[l=e.__e=n.__e]),(d=m.__b)&&d(e);e:if(typeof Z=="function")try{if(v=e.props,w="prototype"in Z&&Z.prototype.render,J=(d=Z.contextType)&&r[d.__c],K=d?J?J.props.value:d.__:r,n.__c?S=(u=e.__c=n.__c).__=u.__E:(w?e.__c=u=new Z(v,K):(e.__c=u=new L(v,K),u.constructor=Z,u.render=Qi),J&&J.sub(u),u.props=v,u.state||(u.state={}),u.context=K,u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),w&&u.__s==null&&(u.__s=u.state),w&&Z.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=D({},u.__s)),D(u.__s,Z.getDerivedStateFromProps(v,u.__s))),f=u.props,g=u.state,u.__v=e,p)w&&Z.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),w&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(w&&Z.getDerivedStateFromProps==null&&v!==f&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(v,K),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(v,u.__s,K)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=v,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function($e){$e&&($e.__=e)}),ae=0;ae<u._sb.length;ae++)u.__h.push(u._sb[ae]);u._sb=[],u.__h.length&&o.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(v,u.__s,K),w&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(f,g,_)})}if(u.context=K,u.props=v,u.__P=t,u.__e=!1,U=m.__r,qi=0,w){for(u.state=u.__s,u.__d=!1,U&&U(e),d=u.render(u.props,u.state,u.context),jt=0;jt<u._sb.length;jt++)u.__h.push(u._sb[jt]);u._sb=[]}else do u.__d=!1,U&&U(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++qi<25);u.state=u.__s,u.getChildContext!=null&&(r=D(D({},r),u.getChildContext())),w&&!p&&u.getSnapshotBeforeUpdate!=null&&(_=u.getSnapshotBeforeUpdate(f,g)),Ze=d,d!=null&&d.type===M&&d.key==null&&(Ze=Qn(d.props.children)),l=Pn(t,Ee(Ze)?Ze:[Ze],e,n,r,i,s,o,l,a,c),u.base=e.__e,e.__u&=-161,u.__h.length&&o.push(u),S&&(u.__E=u.__=null)}catch($e){if(e.__v=null,a||s!=null)if($e.then){for(e.__u|=a?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,e.__e=l}else{for(wn=s.length;wn--;)$t(s[wn]);Et(e)}else e.__e=n.__e,e.__k=n.__k,$e.then||Et(e);m.__e($e,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Ni(n.__e,e,n,r,i,s,o,a,c);return(d=m.diffed)&&d(e),128&e.__u?void 0:l}function Et(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Et)}function Nn(t,e,n){for(var r=0;r<n.length;r++)qt(n[r],n[++r],n[++r]);m.__c&&m.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(s){s.call(i)})}catch(s){m.__e(s,i.__v)}})}function Qn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ee(t)?t.map(Qn):D({},t)}function Ni(t,e,n,r,i,s,o,l,a){var c,d,u,p,f,g,_,S=n.props,v=e.props,w=e.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((f=s[c])&&"setAttribute"in f==!!w&&(w?f.localName==w:f.nodeType==3)){t=f,s[c]=null;break}}if(t==null){if(w==null)return document.createTextNode(v);t=document.createElementNS(i,w,v.is&&v),l&&(m.__m&&m.__m(e,s),l=!1),s=null}if(w==null)S===v||l&&t.data==v||(t.data=v);else{if(s=s&&Ae.call(t.childNodes),S=n.props||Ie,!l&&s!=null)for(S={},c=0;c<t.attributes.length;c++)S[(f=t.attributes[c]).name]=f.value;for(c in S)if(f=S[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=f;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;Ye(t,c,null,f,i)}}for(c in v)f=v[c],c=="children"?p=f:c=="dangerouslySetInnerHTML"?d=f:c=="value"?g=f:c=="checked"?_=f:l&&typeof f!="function"||S[c]===f||Ye(t,c,f,S[c],i);if(d)l||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),Pn(e.type=="template"?t.content:t,Ee(p)?p:[p],e,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:n.__k&&ye(n,0),l,a),s!=null)for(c=s.length;c--;)$t(s[c]);l||(c="value",w=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[c]||w=="progress"&&!g||w=="option"&&g!=S[c])&&Ye(t,c,g,S[c],i),c="checked",_!=null&&_!=t[c]&&Ye(t,c,_,S[c],i))}return t}function qt(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){m.__e(i,n)}}function Bn(t,e,n){var r,i;if(m.unmount&&m.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||qt(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(s){m.__e(s,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&Bn(r[i],e,n||typeof t.type!="function");n||$t(t.__e),t.__c=t.__=t.__e=void 0}function Qi(t,e,n){return this.constructor(t,n)}function ce(t,e,n){var r,i,s,o;e==document&&(e=document.documentElement),m.__&&m.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],It(e,t=(!r&&n||e).__k=X(M,null,[t]),i||Ie,Ie,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?Ae.call(e.childNodes):null,s,!r&&n?n:i?i.__e:e.firstChild,r,o),Nn(s,t,o)}function zn(t,e){ce(t,e,zn)}function Bi(t,e,n){var r,i,s,o,l=D({},t.props);for(s in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)s=="key"?r=e[s]:s=="ref"?i=e[s]:l[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?Ae.call(arguments,2):n),qe(t.type,l,r||t.key,i||t.ref,null)}function zi(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(s){this.props.value!=s.value&&r.forEach(function(o){o.__e=!0,At(o)})},this.sub=function(s){r.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){r&&r.delete(s),o&&o.call(s)}}),n.children}return e.__c="__cC"+In++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}Ae=En.slice,m={__e:function(t,e,n,r){for(var i,s,o;e=e.__;)if((i=e.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(t)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),o=i.__d),o)return i.__E=i}catch(l){t=l}throw t}},jn=0,Cn=function(t){return t!=null&&t.constructor==null},L.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=D({},this.state),typeof t=="function"&&(t=t(D({},n),this.props)),t&&D(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),At(this))},L.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),At(this))},L.prototype.render=M,le=[],Tn=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,$n=function(t,e){return t.__v.__b-e.__v.__b},Xe.__r=0,An=/(PointerCapture)$|Capture$/i,Ct=0,Rt=On(!1),Tt=On(!0),In=0;var Fi=0;function h(t,e,n,r,i,s){e||(e={});var o,l,a=e;if("ref"in a)for(l in a={},e)l=="ref"?o=e[l]:a[l]=e[l];var c={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Fi,__i:-1,__u:0,__source:i,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)a[l]===void 0&&(a[l]=o[l]);return m.vnode&&m.vnode(c),c}var re,k,Pt,Fn,be=0,Un=[],j=m,Dn=j.__b,Vn=j.__r,Wn=j.diffed,Hn=j.__c,Gn=j.unmount,Jn=j.__;function _e(t,e){j.__h&&j.__h(k,t,be||e),be=0;var n=k.__H||(k.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function O(t){return be=1,Mt(er,t)}function Mt(t,e,n){var r=_e(re++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):er(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,l);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=k,!k.__f)){var i=function(l,a,c){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(p){return!!p.__c});if(d.every(function(p){return!p.__N}))return!s||s.call(this,l,a,c);var u=r.__c.props!==l;return d.forEach(function(p){if(p.__N){var f=p.__[0];p.__=p.__N,p.__N=void 0,f!==p.__[0]&&(u=!0)}}),s&&s.call(this,l,a,c)||u};k.__f=!0;var s=k.shouldComponentUpdate,o=k.componentWillUpdate;k.componentWillUpdate=function(l,a,c){if(this.__e){var d=s;s=void 0,i(l,a,c),s=d}o&&o.call(this,l,a,c)},k.shouldComponentUpdate=i}return r.__N||r.__}function N(t,e){var n=_e(re++,3);!j.__s&&Ot(n.__H,e)&&(n.__=t,n.u=e,k.__H.__h.push(n))}function Pe(t,e){var n=_e(re++,4);!j.__s&&Ot(n.__H,e)&&(n.__=t,n.u=e,k.__h.push(n))}function et(t){return be=5,Q(function(){return{current:t}},[])}function Kn(t,e,n){be=6,Pe(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 Q(t,e){var n=_e(re++,7);return Ot(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function tt(t,e){return be=8,Q(function(){return t},e)}function nt(t){var e=k.context[t.__c],n=_e(re++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(k)),e.props.value):t.__}function Zn(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function Xn(){var t=_e(re++,11);if(!t.__){for(var e=k.__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 Ui(){for(var t;t=Un.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(rt),t.__H.__h.forEach(Lt),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){k=null,Dn&&Dn(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Jn&&Jn(t,e)},j.__r=function(t){Vn&&Vn(t),re=0;var e=(k=t.__c).__H;e&&(Pt===k?(e.__h=[],k.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(rt),e.__h.forEach(Lt),e.__h=[],re=0)),Pt=k},j.diffed=function(t){Wn&&Wn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Un.push(e)!==1&&Fn===j.requestAnimationFrame||((Fn=j.requestAnimationFrame)||Di)(Ui)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Pt=k=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(rt),n.__h=n.__h.filter(function(r){return!r.__||Lt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),Hn&&Hn(t,e)},j.unmount=function(t){Gn&&Gn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{rt(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var Yn=typeof requestAnimationFrame=="function";function Di(t){var e,n=function(){clearTimeout(r),Yn&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);Yn&&(e=requestAnimationFrame(n))}function rt(t){var e=k,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),k=e}function Lt(t){var e=k;t.__c=t.__(),k=e}function Ot(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function er(t,e){return typeof e=="function"?e(t):e}function tr(t,e){for(var n in e)t[n]=e[n];return t}function Nt(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 nr(t,e){var n=e(),r=O({t:{__:n,u:e}}),i=r[0].t,s=r[1];return Pe(function(){i.__=n,i.u=e,Qt(i)&&s({t:i})},[t,n,e]),N(function(){return Qt(i)&&s({t:i}),t(function(){Qt(i)&&s({t:i})})},[t]),n}function Qt(t){var e,n,r=t.u,i=t.__;try{var s=r();return!((e=i)===(n=s)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function rr(t){t()}function ir(t){return t}function sr(){return[!1,rr]}var or=Pe;function Bt(t,e){this.props=t,this.context=e}function Vi(t,e){function n(i){var s=this.props.ref,o=s==i.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,i)||!o:Nt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,X(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Bt.prototype=new L).isPureReactComponent=!0,Bt.prototype.shouldComponentUpdate=function(t,e){return Nt(this.props,t)||Nt(this.state,e)};var ar=m.__b;m.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ar&&ar(t)};var Wi=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Hi(t){function e(n){var r=tr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=Wi,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var lr=function(t,e){return t==null?null:Y(Y(t).map(e))},Gi={map:lr,forEach:lr,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},Ji=m.__e;m.__e=function(t,e,n,r){if(t.then){for(var i,s=e;s=s.__;)if((i=s.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}Ji(t,e,n,r)};var cr=m.unmount;function ur(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=tr({},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 ur(r,e,n)})),t}function hr(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return hr(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 it(){this.__u=0,this.o=null,this.__b=null}function dr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Ki(t){var e,n,r;function i(s){if(e||(e=t()).then(function(o){n=o.default||o},function(o){r=o}),r)throw r;if(!n)throw e;return X(n,s)}return i.displayName="Lazy",i.__f=!0,i}function Me(){this.i=null,this.l=null}m.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),cr&&cr(t)},(it.prototype=new L).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=dr(r.__v),s=!1,o=function(){s||(s=!0,n.__R=null,i?i(l):l())};n.__R=o;var l=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=hr(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(o,o)},it.prototype.componentWillUnmount=function(){this.o=[]},it.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]=ur(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&X(M,null,t.fallback);return i&&(i.__u&=-33),[X(M,null,e.__a?null:t.children),i]};var fr=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 Zi(t){return this.getChildContext=function(){return t.context},t.children}function Xi(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){ce(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,s){this.childNodes.push(i),e.h.insertBefore(i,s)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}ce(X(Zi,{context:e.context},t.__v),e.v)}function Yi(t,e){var n=X(Xi,{__v:t,h:e});return n.containerInfo=e,n}(Me.prototype=new L).__a=function(t){var e=this,n=dr(e.__v),r=e.l.get(t);return r[0]++,function(i){var s=function(){e.props.revealOrder?(r.push(i),fr(e,t,r)):i()};n?n(s):s()}},Me.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},Me.prototype.componentDidUpdate=Me.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){fr(t,n,e)})};var pr=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,es=/^(?: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]/,ts=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ns=/[A-Z0-9]/g,rs=typeof document<"u",is=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function ss(t,e,n){return e.__k==null&&(e.textContent=""),ce(t,e),typeof n=="function"&&n(),t?t.__c:null}function os(t,e,n){return zn(t,e),typeof n=="function"&&n(),t?t.__c:null}L.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(L.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var gr=m.event;function as(){}function ls(){return this.cancelBubble}function cs(){return this.defaultPrevented}m.event=function(t){return gr&&(t=gr(t)),t.persist=as,t.isPropagationStopped=ls,t.isDefaultPrevented=cs,t.nativeEvent=t};var zt,us={enumerable:!1,configurable:!0,get:function(){return this.class}},mr=m.vnode;m.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},s=r.indexOf("-")===-1;for(var o in n){var l=n[o];if(!(o==="value"&&"defaultValue"in n&&l==null||rs&&o==="children"&&r==="noscript"||o==="class"||o==="className")){var a=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&l===!0?l="":a==="translate"&&l==="no"?l=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?o="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||is(n.type)?a==="onfocus"?o="onfocusin":a==="onblur"?o="onfocusout":ts.test(o)&&(o=a):a=o="oninput":s&&es.test(o)?o=o.replace(ns,"-$&").toLowerCase():l===null&&(l=void 0),a==="oninput"&&i[o=a]&&(o="oninputCapture"),i[o]=l}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=Y(n.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=Y(n.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",us)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=pr,mr&&mr(t)};var xr=m.__r;m.__r=function(t){xr&&xr(t),zt=t.__c};var yr=m.diffed;m.diffed=function(t){yr&&yr(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),zt=null};var hs={ReactCurrentDispatcher:{current:{readContext:function(t){return zt.__n[t.__c].props.value},useCallback:tt,useContext:nt,useDebugValue:Zn,useDeferredValue:ir,useEffect:N,useId:Xn,useImperativeHandle:Kn,useInsertionEffect:or,useLayoutEffect:Pe,useMemo:Q,useReducer:Mt,useRef:et,useState:O,useSyncExternalStore:nr,useTransition:sr}}};function ds(t){return X.bind(null,t)}function st(t){return!!t&&t.$$typeof===pr}function fs(t){return st(t)&&t.type===M}function ps(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function gs(t){return st(t)?Bi.apply(null,arguments):t}function ms(t){return!!t.__k&&(ce(null,t),!0)}function xs(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var ys=function(t,e){return t(e)},bs=function(t,e){return t(e)},_s=M,vs=st,Ft={useState:O,useId:Xn,useReducer:Mt,useEffect:N,useLayoutEffect:Pe,useInsertionEffect:or,useTransition:sr,useDeferredValue:ir,useSyncExternalStore:nr,startTransition:rr,useRef:et,useImperativeHandle:Kn,useMemo:Q,useCallback:tt,useContext:nt,useDebugValue:Zn,version:"18.3.1",Children:Gi,render:ss,hydrate:os,unmountComponentAtNode:ms,createPortal:Yi,createElement:X,createContext:zi,createFactory:ds,cloneElement:gs,createRef:Mi,Fragment:M,isValidElement:st,isElement:vs,isFragment:fs,isMemo:ps,findDOMNode:xs,Component:L,PureComponent:Bt,memo:Vi,forwardRef:Hi,flushSync:bs,unstable_batchedUpdates:ys,StrictMode:_s,Suspense:it,SuspenseList:Me,lazy:Ki,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hs},V=[],q=[],ws=Uint8Array,Ut="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ve=0,ks=Ut.length;ve<ks;++ve)V[ve]=Ut[ve],q[Ut.charCodeAt(ve)]=ve;q[45]=62,q[95]=63;function Ss(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 js(t,e,n){return(e+n)*3/4-n}function Le(t){var e,n=Ss(t),r=n[0],i=n[1],s=new ws(js(t,r,i)),o=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=q[t.charCodeAt(a)]<<18|q[t.charCodeAt(a+1)]<<12|q[t.charCodeAt(a+2)]<<6|q[t.charCodeAt(a+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=q[t.charCodeAt(a)]<<2|q[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=q[t.charCodeAt(a)]<<10|q[t.charCodeAt(a+1)]<<4|q[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Cs(t){return V[t>>18&63]+V[t>>12&63]+V[t>>6&63]+V[t&63]}function Rs(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Cs(r));return i.join("")}function Oe(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,l=n-r;o<l;o+=s)i.push(Rs(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(V[e>>2]+V[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(V[e>>10]+V[e>>4&63]+V[e<<2&63]+"=")),i.join("")}function ee(t){if(t===void 0)return{};if(!br(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function Ts(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 br(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const _r=!0,we=BigInt("-9223372036854775808"),Dt=BigInt("9223372036854775807"),Vt=BigInt("0"),$s=BigInt("8"),As=BigInt("256");function vr(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Is(t){t<Vt&&(t-=we+we);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>>=$s;return Oe(n)}function Es(t){const e=Le(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Vt,r=Vt;for(const i of e)n+=BigInt(i)*As**r,r++;return n>Dt&&(n+=we+we),n}function qs(t){if(t<we||Dt<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),Oe(new Uint8Array(e))}function Ps(t){const e=Le(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 Ms=DataView.prototype.setBigInt64?qs:Is,Ls=DataView.prototype.getBigInt64?Ps:Es,wr=1024;function kr(t){if(t.length>wr)throw new Error(`Field name ${t} exceeds maximum field name length ${wr}.`);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 ke(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>ke(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 Le(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return Ls(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=Le(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const o=new DataView(i.buffer).getFloat64(0,_r);if(!vr(o))throw new Error(`Float ${o} should be encoded as a number`);return o}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))kr(r),n[r]=ke(i);return n}const Sr=16384;function Ne(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Sr){const n="[...truncated]";let r=Sr-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function Wt(t,e,n,r){if(t===void 0){const o=n&&` (present at path ${n} in original object ${Ne(e)})`;throw new Error(`undefined is not a valid Convex value${o}. 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<we||Dt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Ms(t)}}if(typeof t=="number")if(vr(t)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,t,_r),{$float:Oe(new Uint8Array(o))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:Oe(new Uint8Array(t))};if(Array.isArray(t))return t.map((o,l)=>Wt(o,e,n+`[${l}]`));if(t instanceof Set)throw new Error(Ht(n,"Set",[...t],e));if(t instanceof Map)throw new Error(Ht(n,"Map",[...t],e));if(!br(t)){const o=t?.constructor?.name,l=o?`${o} `:"";throw new Error(Ht(n,l,t,e))}const i={},s=Object.entries(t);s.sort(([o,l],[a,c])=>o===a?0:o<a?-1:1);for(const[o,l]of s)l!==void 0&&(kr(o),i[o]=Wt(l,e,n+`.${o}`));return i}function Ht(t,e,n,r){return t?`${e}${Ne(n)} is not a supported Convex type (present at path ${t} in original object ${Ne(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${Ne(n)} is not a supported Convex type.`}function W(t){return Wt(t,t,"")}var Os=Object.defineProperty,Ns=(t,e,n)=>e in t?Os(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gt=(t,e,n)=>Ns(t,typeof e!="symbol"?e+"":e,n),jr,Cr;const Qs=Symbol.for("ConvexError");class Jt extends(Cr=Error,jr=Qs,Cr){constructor(e){super(typeof e=="string"?e:Ne(e)),Gt(this,"name","ConvexError"),Gt(this,"data"),Gt(this,jr,!0),this.data=e}}const Rr=()=>Array.from({length:4},()=>0);Rr(),Rr();const Tr="1.34.1";var Bs=Object.defineProperty,zs=(t,e,n)=>e in t?Bs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$r=(t,e,n)=>zs(t,typeof e!="symbol"?e+"":e,n);const Fs="color:rgb(0, 145, 255)";function Ar(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Ir{constructor(e){$r(this,"_onLogLineFuncs"),$r(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 Er(t){const e=new Ir(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 qr(t){return new Ir(t)}function ot(t,e,n,r,i){const s=Ar(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const o=i.match(/^\[.*?\] /);if(o===null){t.error(`[CONVEX ${s}(${r})] Could not parse console.log`);return}const l=i.slice(1,o[0].length-2),a=i.slice(o[0].length);t.log(`%c[CONVEX ${s}(${r})] [${l}]`,Fs,a)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}function Us(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Se(t,e,n){return`[CONVEX ${Ar(t)}(${e})] ${n.errorMessage}
2
- Called by client`}function Kt(t,e){return e.data=t.errorData,e}function ue(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 he(t,e){return JSON.stringify({udfPath:ue(t),args:W(e)})}function Pr(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:ue(t),args:W(e),options:W({initialNumItems:r,id:i})})}var Ds=Object.defineProperty,Vs=(t,e,n)=>e in t?Ds(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,H=(t,e,n)=>Vs(t,typeof e!="symbol"?e+"":e,n);class Ws{constructor(){H(this,"nextQueryId"),H(this,"querySetVersion"),H(this,"querySet"),H(this,"queryIdToToken"),H(this,"identityVersion"),H(this,"auth"),H(this,"outstandingQueriesOlderThanRestart"),H(this,"outstandingAuthOlderThanRestart"),H(this,"paused"),H(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 s=ue(e),o=he(s,n),l=this.querySet.get(o);if(l!==void 0)return l.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{const a=this.nextQueryId++,c={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,c),this.queryIdToToken.set(a,o);const d=this.querySetVersion,u=this.querySetVersion+1,p={type:"Add",queryId:a,udfPath:s,args:[W(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,p):this.querySetVersion=u,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:u,modifications:[p]},unsubscribe:()=>this.removeSubscriber(o)}}}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=ue(e),i=he(r,n),s=this.querySet.get(i);return s!==void 0?s.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 s={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[W(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(s),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,s={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,s):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[s]}}}}var Hs=Object.defineProperty,Gs=(t,e,n)=>e in t?Hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,at=(t,e,n)=>Gs(t,typeof e!="symbol"?e+"":e,n);class Js{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,at(this,"inflightRequests"),at(this,"requestsOlderThanRestart"),at(this,"inflightMutationsCount",0),at(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const s=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:s,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)ot(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:ke(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:c}=e;ot(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:c!==void 0?ke(c):void 0,logLines:e.logLines},l=()=>s.onResult(o)}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:o}):(n.status={status:"Completed",result:o,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const s=i.status;s.status==="Completed"&&s.ts.lessThanOrEqual(e)&&(s.onResolve(),n.set(r,s.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 Qe=Symbol.for("functionName"),Mr=Symbol.for("toReferencePath");function Ks(t){return t[Mr]??null}function Zs(t){return t.startsWith("function://")}function Xs(t){let e;if(typeof t=="string")Zs(t)?e={functionHandle:t}:e={name:t};else if(t[Qe])e={name:t[Qe]};else{const n=Ks(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function I(t){const e=Xs(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[Qe];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Lr(t){return{[Qe]:t}}function Or(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Or(i)}else if(r===Qe){if(t.length<2){const o=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${o}\``)}const i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Ys=Or();var eo=Object.defineProperty,to=(t,e,n)=>e in t?eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lt=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n);class Be{constructor(e){lt(this,"queryResults"),lt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=ee(n[0]),i=I(e),s=this.queryResults.get(he(i,r));if(s!==void 0)return Be.queryValue(s.result)}getAllQueries(e){const n=[],r=I(e);for(const i of this.queryResults.values())i.udfPath===ue(r)&&n.push({args:i.args,value:Be.queryValue(i.result)});return n}setQuery(e,n,r){const i=ee(n),s=I(e),o=he(s,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:s,args:i,result:l};this.queryResults.set(o,a),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class no{constructor(){lt(this,"queryResults"),lt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(o=>!n.has(o.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Be(this.queryResults);for(const o of this.optimisticUpdates)o.update(i);const s=[];for(const[o,l]of this.queryResults){const a=r.get(o);(a===void 0||a.result!==l.result)&&s.push(o)}return s}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Be(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?Kt(r,new Jt(Se("query",n.udfPath,r))):new Error(Se("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var ro=Object.defineProperty,io=(t,e,n)=>e in t?ro(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zt=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);class E{constructor(e,n){Zt(this,"low"),Zt(this,"high"),Zt(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 E(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?Nr:e>=so?oo:new E(e%ze|0,e/ze|0)}toString(){return(BigInt(this.high)*BigInt(ze)+BigInt(this.low)).toString()}equals(e){return E.isLong(e)||(e=E.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 E.isLong(e)||(e=E.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"?E.fromNumber(e):new E(e.low,e.high)}}const Nr=new E(0,0),Qr=65536,ze=Qr*Qr,so=ze*ze,oo=new E(-1,-1);var ao=Object.defineProperty,lo=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ct=(t,e,n)=>lo(t,typeof e!="symbol"?e+"":e,n);class Br{constructor(e,n){ct(this,"version"),ct(this,"remoteQuerySet"),ct(this,"queryPath"),ct(this,"logger"),this.version={querySet:0,ts:E.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 o of r.logLines)ot(this.logger,"info","query",i,o);const s=ke(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:s,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ot(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?ke(s):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 Xt(t){const e=Le(t);return E.fromBytesLE(Array.from(e))}function co(t){const e=new Uint8Array(t.toBytesLE());return Oe(e)}function zr(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:Xt(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:Xt(t.startVersion.ts)},endVersion:{...t.endVersion,ts:Xt(t.endVersion.ts)}}}}function uo(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:co(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var ho=Object.defineProperty,fo=(t,e,n)=>e in t?ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C=(t,e,n)=>fo(t,typeof e!="symbol"?e+"":e,n);const po=1e3,go=1001,mo=1005,xo=4040;let ut;function je(){return ut===void 0&&(ut=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(ut+performance.now())}function Fr(){return`t=${Math.round((je()-ut)/100)/10}s`}const Ur={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 yo(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Ur))if(t.startsWith(e))return e;return"Unknown"}class bo{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,C(this,"socket"),C(this,"connectionCount"),C(this,"_hasEverConnected",!1),C(this,"lastCloseReason"),C(this,"transitionChunkBuffer",null),C(this,"defaultInitialBackoff"),C(this,"maxBackoff"),C(this,"retries"),C(this,"serverInactivityThreshold"),C(this,"reconnectDueToServerInactivityTimeout"),C(this,"scheduledReconnect",null),C(this,"networkOnlineHandler",null),C(this,"pendingNetworkRecoveryInfo",null),C(this,"uri"),C(this,"onOpen"),C(this,"onResume"),C(this,"onMessage"),C(this,"webSocketConstructor"),C(this,"logger"),C(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=zr(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:je()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Fr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Fr())),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=zr(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const o=this.assembleTransition(i);if(!o)return;i=o,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!==po&&n.code!==go&&n.code!==mo&&n.code!==xo){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=yo(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=uo(e),i=JSON.stringify(r);let s=!1;try{this.socket.ws.send(i),s=!0}catch(o){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${o}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${s?"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=je(),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=je()-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.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:je()})):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:Ur[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),s=i*(Math.random()-.5);return i+s}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=je()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,s=`${Math.round(n/1e4)/100}MB`,o=n/(r/1e3),l=`${Math.round(o/1e4)/100}MB per second`;this._logVerbose(`received ${s} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${s}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${s} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function _o(){return vo()}function vo(){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 Fe extends Error{}Fe.prototype.name="InvalidTokenError";function wo(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 ko(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 wo(e)}catch{return atob(e)}}function Dr(t,e){if(typeof t!="string")throw new Fe("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 Fe(`Invalid token specified: missing part #${n+1}`);let i;try{i=ko(r)}catch(s){throw new Fe(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new Fe(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var So=Object.defineProperty,jo=(t,e,n)=>e in t?So(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,P=(t,e,n)=>jo(t,typeof e!="symbol"?e+"":e,n);const Co=480*60*60*1e3,Vr=2;class Ro{constructor(e,n,r){P(this,"authState",{state:"noAuth"}),P(this,"configVersion",0),P(this,"syncState"),P(this,"authenticate"),P(this,"stopSocket"),P(this,"tryRestartSocket"),P(this,"pauseSocket"),P(this,"resumeSocket"),P(this,"clearAuth"),P(this,"logger"),P(this,"refreshTokenLeewaySeconds"),P(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>=Vr){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, ${Vr-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 s=i-r;if(s<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let o=Math.min(Co,(s-this.refreshTokenLeewaySeconds)*1e3);o<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${s}s`),o=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},o);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${o}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 Dr(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 To=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function $o(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function Ao(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Io(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of To){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(Ao)}var Eo=Object.defineProperty,qo=(t,e,n)=>e in t?Eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,R=(t,e,n)=>qo(t,typeof e!="symbol"?e+"":e,n);class Po{constructor(e,n,r){if(R(this,"address"),R(this,"state"),R(this,"requestManager"),R(this,"webSocketManager"),R(this,"authenticationManager"),R(this,"remoteQuerySet"),R(this,"optimisticQueryResults"),R(this,"_transitionHandlerCounter",0),R(this,"_nextRequestId"),R(this,"_onTransitionFns",new Map),R(this,"_sessionId"),R(this,"firstMessageReceived",!1),R(this,"debug"),R(this,"logger"),R(this,"maxObservedTimestamp"),R(this,"connectionStateSubscribers",new Map),R(this,"nextConnectionStateSubscriberId",0),R(this,"_lastPublishedConnectionState"),R(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const f=this.connectionState();if(JSON.stringify(f)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=f;for(const g of this.connectionStateSubscribers.values())g(f)}})}),R(this,"mark",f=>{this.debug&&$o(f,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&&Ts(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let s=r.webSocketConstructor;if(!s&&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");s=s||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?qr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Er({verbose:r.verbose??!1});const o=e.search("://");if(o===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(o+3),a=e.substring(0,o);let c;if(a==="http")c="ws";else if(a==="https")c="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${c}://${l}/api/${Tr}/sync`;this.state=new Ws,this.remoteQuerySet=new Br(f=>this.state.queryPath(f),this.logger),this.requestManager=new Js(this.logger,this.markConnectionStateDirty);const u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ro(this.state,{authenticate:f=>{const g=this.state.setAuth(f);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new no,this.addOnTransitionHandler(f=>{n(f.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=_o();const{unsavedChangesWarning:p}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(p===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else p!==!1&&window.addEventListener("beforeunload",f=>{if(this.requestManager.hasIncompleteRequests()){f.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(f||window.event).returnValue=g,g}});this.webSocketManager=new bo(d,{onOpen:f=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...f,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Br(S=>this.state.queryPath(S),this.logger);const[g,_]=this.state.restart();_&&this.webSocketManager.sendMessage(_),this.webSocketManager.sendMessage(g);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[f,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),f&&this.webSocketManager.sendMessage(f);for(const _ of this.requestManager.resume())this.webSocketManager.sendMessage(_)},onMessage:f=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),f.type){case"Transition":{this.observedTimestamp(f.endVersion.ts),this.authenticationManager.onTransition(f),this.remoteQuerySet.transition(f),this.state.transition(f);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{f.success&&this.observedTimestamp(f.ts);const g=this.requestManager.onResponse(f);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(f);break}case"AuthError":{this.authenticationManager.onAuthError(f);break}case"FatalError":{const g=Us(this.logger,f.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},s,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&u()}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[s,o]of n){const l=this.state.queryToken(s);if(l!==null){const a={result:o,udfPath:this.state.queryPath(s),args:this.state.queryArgs(s)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(s=>{const o=this.optimisticQueryResults.rawQueryResult(s);return{token:s,modification:{kind:"Updated",result:o}}}),reflectedMutations:Array.from(e).map(([s,o])=>({requestId:s,result:o})),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?Dr(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=ee(n),{modification:s,queryToken:o,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return s!==null&&this.webSocketManager.sendMessage(s),{queryToken:o,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=ee(n),i=he(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=ee(n),i=he(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=ee(n),i=he(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?Kt(i,new Jt(Se("mutation",e,i))):new Error(Se("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:s}=this.enqueueMutation(e,n,r,i);return s}enqueueMutation(e,n,r,i){const s=ee(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const u=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},f=this.optimisticQueryResults.applyOptimisticUpdate(u,o).map(g=>{const _=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:_===void 0?void 0:{success:!0,value:_,logLines:[]}}}});this.handleTransition({queries:f,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[W(s)]},a=this.webSocketManager.sendMessage(l),c=this.requestManager.request(l,a);return{requestId:o,mutationPromise:c}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?Kt(r,new Jt(Se("action",e,r))):new Error(Se("action",e,r));return r.value}async actionInternal(e,n,r){const i=ee(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[W(i)]},l=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,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=Io(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-${Tr}`},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 Yt(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 Mo=Object.defineProperty,Lo=(t,e,n)=>e in t?Mo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Wr=(t,e,n)=>Lo(t,typeof e!="symbol"?e+"":e,n);class Oo{constructor(e,n){this.client=e,this.onTransition=n,Wr(this,"paginatedQuerySet",new Map),Wr(this,"lastTransitionTs"),this.lastTransitionTs=E.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=ue(e),s=Pr(i,n,r),o=()=>this.removePaginatedQuerySubscriber(s),l=this.paginatedQuerySet.get(s);return l?(l.numSubscribers+=1,{paginatedQueryToken:s,unsubscribe:o}):(this.paginatedQuerySet.set(s,{token:s,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(s,null,r.initialNumItems),{paginatedQueryToken:s,unsubscribe:o})}localQueryResult(e,n,r){const i=ue(e),s=Pr(i,n,r);return this.localQueryResultByToken(s)}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=[],s=!1,o=!1;for(const a of r){const c=this.client.localQueryResultByToken(a);if(c===void 0){s=!0,o=!1;continue}const d=Yt(c);i=i.concat(d.page),o=!!d.isDone}let l;return s?l=i.length===0?"LoadingFirstPage":"LoadingMore":o?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(o=>o.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,o=>this.client.localQueryResultByToken(o)),i=r.map(o=>({token:o,modification:{kind:"Updated",result:this.localQueryResultByToken(o)}})));const s={...e,paginatedQueries:i};this.onTransition(s)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const s=Yt(i);if(s.isDone)return!1;this.addPageToPaginatedQuery(e,s.continueCursor,n);const o={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(o),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,s]of this.paginatedQuerySet)for(const o of this.allQueryTokens(s))if(r.has(o)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:s,pageKeyToQuery:o,pageKeys:l}=i;for(const[a,[c,d]]of s)n(o.get(c).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,c,d);for(const a of l){if(s.has(a))continue;const c=o.get(a).queryToken,d=n(c);if(!d)continue;const u=Yt(d);u.splitCursor&&(u.pageStatus==="SplitRecommended"||u.pageStatus==="SplitRequired"||u.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,u.splitCursor,u.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const s=e.nextPageKey++,o=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(s,a);const c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,c),e.ongoingSplits.set(n,[s,o])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),s=i.nextPageKey++,o={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:o},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(s),i.pageKeyToQuery.set(s,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 s=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const o=e.pageKeys.indexOf(n);e.pageKeys.splice(o,1,r,i),e.ongoingSplits.delete(n),s.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 No({getCurrentValue:t,subscribe:e}){const[n,r]=O(()=>({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})),N(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const c=t();return a.value===c?a:{...a,value:c}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var Qo=Object.defineProperty,Bo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,te=(t,e,n)=>Bo(t,typeof e!="symbol"?e+"":e,n);const zo=5e3;if(typeof Ft>"u")throw new Error("Required dependency 'react' not found");function Hr(t,e,n){function r(i){return Wo(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(s){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${I(t)}`);return Hr(t,e,s)},r}class Fo{constructor(e,n){if(te(this,"address"),te(this,"cachedSync"),te(this,"cachedPaginatedQueryClient"),te(this,"listeners"),te(this,"options"),te(this,"closed",!1),te(this,"_logger"),te(this,"adminAuth"),te(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?qr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Er({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 Po(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new Oo(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,s=I(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),c=this.listeners.get(l);return c!==void 0?c.add(o):this.listeners.set(l,new Set([o])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(o),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(s,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(s,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(s,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??zo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=I(e);return{onUpdate:s=>{const{paginatedQueryToken:o,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(o);return a!==void 0?a.add(s):this.listeners.set(o,new Set([s])),()=>{if(this.closed)return;const c=this.listeners.get(o);c.delete(s),c.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=I(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=I(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((s,o)=>{const l=r.onUpdate(()=>{l();try{s(r.localQueryResult())}catch(a){o(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 en=Ft.createContext(void 0);function Uo(){return nt(en)}const Do=({client:t,children:e})=>Ft.createElement(en.Provider,{value:t},e);function Vo(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:ee(e[0]),i=typeof t=="string"?Lr(t):t,s=I(i),o=Q(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(W(r)),s,n]),a=Ko(o).query;if(a instanceof Error)throw a;return a}function Gr(t){const e=typeof t=="string"?Lr(t):t,n=nt(en);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 Q(()=>Hr(e,n),[n,I(e)])}function Wo(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 Ho=Object.defineProperty,Go=(t,e,n)=>e in t?Ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tn=(t,e,n)=>Go(t,typeof e!="symbol"?e+"":e,n);class Jo{constructor(e){tn(this,"createWatch"),tn(this,"queries"),tn(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:s}=e[n];if(I(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(I(r)!==I(o.query)||JSON.stringify(W(i))!==JSON.stringify(W(o.args))||JSON.stringify(s)!==JSON.stringify(o.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,s?{paginationOptions:s}:{}))}}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:s}=e[r],o=e[r].paginationOptions;I(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(c){if(c instanceof Error)a=c;else throw c}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:s,paginationOptions:o}=this.queries[n],l="journal"in s?s.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...o?{paginationOptions:o}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:s}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const o=this.createWatch(n,r,{...s?{journal:s}:[],...i?{paginationOptions:i}:{}}),l=o.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:o,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 Ko(t){const e=Uo();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=Q(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return Zo(t,n)}function Zo(t,e){const[n]=O(()=>new Jo(e));n.createWatch!==e&&n.setCreateWatch(e),N(()=>()=>n.destroy(),[n]);const r=Q(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return No(r)}var Xo=Symbol.for("preact-signals");function ht(){if(ie>1)ie--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,nn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&Zr(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(nn=0,ie--,e)throw t}}function Yo(t){if(ie>0)return t();ie++;try{return t()}finally{ht()}}var y=void 0;function Jr(t){var e=y;y=void 0;try{return t()}finally{y=e}}var Ue=void 0,ie=0,nn=0,dt=0;function Kr(t){if(y!==void 0){var e=t.n;if(e===void 0||e.t!==y)return e={i:0,S:t,p:y.s,n:void 0,t:y,e:void 0,x:void 0,r:e},y.s!==void 0&&(y.s.n=e),y.s=e,t.n=e,32&y.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=y.s,e.n=void 0,y.s.n=e,y.s=e),e}}function T(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}T.prototype.brand=Xo,T.prototype.h=function(){return!0},T.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:Jr(function(){var r;(r=e.W)==null||r.call(e)}))},T.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&&Jr(function(){var i;(i=e.Z)==null||i.call(e)}))}},T.prototype.subscribe=function(t){var e=this;return De(function(){var n=e.value,r=y;y=void 0;try{t(n)}finally{y=r}},{name:"sub"})},T.prototype.valueOf=function(){return this.value},T.prototype.toString=function(){return this.value+""},T.prototype.toJSON=function(){return this.value},T.prototype.peek=function(){var t=y;y=void 0;try{return this.value}finally{y=t}},Object.defineProperty(T.prototype,"value",{get:function(){var t=Kr(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(nn>100)throw new Error("Cycle detected");this.v=t,this.i++,dt++,ie++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{ht()}}}});function se(t,e){return new T(t,e)}function Zr(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 Xr(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 Yr(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 de(t,e){T.call(this,void 0),this.x=t,this.s=void 0,this.g=dt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}de.prototype=new T,de.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===dt))return!0;if(this.g=dt,this.f|=1,this.i>0&&!Zr(this))return this.f&=-2,!0;var t=y;try{Xr(this),y=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 y=t,Yr(this),this.f&=-2,!0},de.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)}T.prototype.S.call(this,t)},de.prototype.U=function(t){if(this.t!==void 0&&(T.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)}},de.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(de.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Kr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ei(t,e){return new de(t,e)}function ti(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ie++;var n=y;y=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,rn(t),r}finally{y=n,ht()}}}function rn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ti(t)}function ea(t){if(y!==this)throw new Error("Out-of-order effect");Yr(this),y=t,this.f&=-2,8&this.f&&rn(this),ht()}function Ce(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ce.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()}},Ce.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ti(this),Xr(this),ie++;var t=y;return y=this,ea.bind(this,t)},Ce.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ce.prototype.d=function(){this.f|=8,1&this.f||rn(this)},Ce.prototype.dispose=function(){this.d()};function De(t,e){var n=new Ce(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var ni,ft,ta=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ri=[];De(function(){ni=this.N})();function Re(t,e){m[t]=e.bind(null,m[t]||function(){})}function pt(t){if(ft){var e=ft;ft=void 0,e()}ft=t&&t.S()}function ii(t){var e=this,n=t.data,r=gt(n);r.value=n;var i=Q(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var c=ei(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),d=ei(function(){return!Array.isArray(c.value)&&!Cn(c.value)}),u=De(function(){if(this.N=si,d.value){var f=c.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=f)}}),p=e.__$u.d;return e.__$u.d=function(){u(),p.call(this)},[d,c]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}ii.displayName="ReactiveTextNode",Object.defineProperties(T.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ii},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Re("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var s=r[i];s instanceof T&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Re("__r",function(t,e){if(t(e),e.type!==M){pt();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,s){var o;return De(function(){o=this},{name:s}),o.c=i,o})(function(){var i;ta&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),pt(n)}}),Re("__e",function(t,e,n,r){pt(),t(e,n,r)}),Re("diffed",function(t,e){pt();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var s=n.U;if(s)for(var o in s){var l=s[o];l!==void 0&&!(o in r)&&(l.d(),s[o]=void 0)}else s={},n.U=s;for(var a in r){var c=s[a],d=r[a];c===void 0?(c=na(n,a,d,i),s[a]=c):c.o(d,i)}}}t(e)});function na(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=se(n);return{o:function(o,l){s.value=o,r=l},d:De(function(){this.N=si;var o=s.value.value;r[e]!==o&&(r[e]=o,i?t[e]=o:o!=null&&(o!==!1||e[4]==="-")?t.setAttribute(e,o):t.removeAttribute(e))})}}Re("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 s=r[i];s&&s.d()}}}}else{var o=e.__c;if(o){var l=o.__$u;l&&(o.__$u=void 0,l.d())}}t(e)}),Re("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),L.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 s=2&this.__$f;if(!(r||s||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function gt(t,e){return Q(function(){return se(t,e)},[])}var ra=function(t){queueMicrotask(function(){queueMicrotask(t)})};function ia(){Yo(function(){for(var t;t=ri.shift();)ni.call(t)})}function si(){ri.push(this)===1&&(m.requestAnimationFrame||ra)(ia)}const $=se(!1),mt=se(void 0);function sa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function oa(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function aa(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 la(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function ca(t,e){const[n,r]=O(null);return N(()=>{r(null);const i=e??"https://tame-spider-109.eu-west-1.convex.cloud",s=i?oa(i):void 0;if(!s||!t)return;const o=new AbortController;async function l(a){try{const c=await la(a,t,o.signal);c&&r(c)}catch(c){if(c instanceof Error&&c.name==="AbortError")return}}return l(s),()=>{o.abort()}},[t,e]),n}const oi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resume 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"},ua={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch fortsetzen",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"},ha=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],da="de",fa="jex-locale",sn=se("de"),pa={en:oi,de:ua};function ne(){return pa[sn.value]??oi}function on(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return ha.some(r=>r.value===e)?e:null}function ai(t){const e=on(t);if(e)return e;try{const n=on(localStorage.getItem(fa));if(n)return n}catch{}if(typeof navigator<"u"){const n=on(navigator.language);if(n)return n}return da}function ga(t){N(()=>{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&&(sn.value=ai(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const an="jex-session-ref",xt="jex-session-active",oe=se(null),fe=se(!1);function ma(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function xa(){try{const t=sessionStorage.getItem(an),e=sessionStorage.getItem(xt);oe.value=t??null,fe.value=t!==null&&e==="true"}catch{oe.value=null,fe.value=!1}}function li(){const t=ma();oe.value=t,fe.value=!1;try{sessionStorage.setItem(an,t),sessionStorage.removeItem(xt)}catch{}return t}function ya(t){oe.value=t,fe.value=!0;try{sessionStorage.setItem(an,t),sessionStorage.setItem(xt,"true")}catch{}}function ba(){if(oe.value){fe.value=!0;try{sessionStorage.setItem(xt,"true")}catch{}}}function _a(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}const B=se([{id:"chat"}]);function Ve(t){B.value=[...B.value,t]}function ci(){B.value.length>1&&(B.value=B.value.slice(0,-1))}function ln(t){B.value=[...B.value.slice(0,-1),t]}function cn({size:t=24}){return h("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:[h("path",{d:"M12 8V4H8"}),h("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),h("path",{d:"M2 14h2"}),h("path",{d:"M20 14h2"}),h("path",{d:"M15 13v2"}),h("path",{d:"M9 13v2"})]})}function ui({title:t}){const e=ne(),n=B.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:ci,"aria-label":e.back||"Go back",children:h("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:h("path",{d:"m15 18-6-6 6-6"})})}),!n&&h(cn,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function va({size:t=14}){return h("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:h("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 hi(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(va,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function di({size:t=28}){return h("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:h("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 wa({size:t=28}){return h("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:[h("path",{d:"M18 6 6 18"}),h("path",{d:"m6 6 12 12"})]})}function ka({size:t=24,...e}){return h("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:h("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 Sa={chat:h(di,{size:28}),bot:h(cn,{size:28}),sparkles:h(ka,{size:28})},ja={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Ca({radius:t="full",iconOption:e="chat",label:n="Chatte mit uns"}){const r=ne(),i=n!=="";return h("button",{class:`jex-floating-button ${!$.value&&i?"jex-has-label":""}`,style:{borderRadius:ja[t]??"9999px"},onClick:()=>{$.value=!$.value},"aria-label":$.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:$.value?h(wa,{size:28}):h("div",{class:"jex-fab-inner",children:[Sa[e],i&&h("span",{class:"jex-fab-label",children:n})]})})}function Ra({title:t}){const e=ne(),n=oe.value,[r,i]=O("");function s(){li(),Ve({id:"chat"})}function o(){Ve({id:"chat"})}function l(a){a.preventDefault();const c=r.trim().toUpperCase();c&&(ya(c),Ve({id:"chat"}))}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-hero",children:[h("div",{class:"jex-home-avatar",children:[h(di,{size:24}),h("span",{class:"jex-home-status-dot"})]}),h("div",{class:"jex-home-hero-text",children:[h("h2",{class:"jex-home-title",children:t}),h("span",{class:"jex-home-status",children:e.statusOnline})]})]}),h("form",{class:"jex-home-lookup",onSubmit:l,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:e.referencePlaceholder,value:r,onInput:a=>{i(a.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!r.trim(),children:e.resume})]}),h("div",{class:"jex-home-actions",children:[n&&h("button",{class:"jex-home-resume-card",onClick:o,children:[h("div",{class:"jex-home-resume-top",children:[h("span",{class:"jex-home-resume-label",children:e.resumeConversation}),h("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:h("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),h("span",{class:"jex-home-resume-ref",children:n})]}),h("button",{class:"jex-home-new-btn",onClick:s,children:n?e.startNewConversation:e.chatWith.replace("{title}",t)})]})]})}function Ta({title:t}){const e=ne();return h("div",{class:"jex-selection",children:[h("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),h("div",{class:"jex-selection-options",children:[h("button",{class:"jex-selection-option",onClick:()=>Ve({id:"chat"}),children:[h("span",{class:"jex-selection-icon",children:"💬"}),h("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),h("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),h("button",{class:"jex-selection-option",onClick:()=>Ve({id:"form"}),children:[h("span",{class:"jex-selection-icon",children:"📝"}),h("span",{class:"jex-selection-label",children:e.submitTicket}),h("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function fi(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return fi(t,s)}else if(i===Mr){if(e.length<1){const s=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${s}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const $a=()=>fi("components",[]),un=Ys;$a();function Aa(t){const e=et(null),n=gt(!1),r=gt(!1),i=Gr(un.functions.chat.public.sessions.createOrResume),s=tt(async()=>{if(e.current)return e.current;n.value=!0;const l=oe.value!==null,a=oe.value??li();try{const c=await i({orgSlug:t,visitorId:a,...mt.value?{source:mt.value}:{}});l&&c.isNew&&(r.value=!0);const d={sessionId:c.sessionId,visitorId:a};return e.current=d,d}catch(c){return console.error("[jexity] Failed to create session:",c),null}finally{n.value=!1}},[t,i,n,r]),o=e.current;return{sessionId:o?.sessionId??null,visitorId:o?.visitorId??null,isLoading:n.value,sessionNotFound:r.value,ensureSession:s}}function hn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var pe=hn();function pi(t){pe=t}var ge={exec:()=>null};function x(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(A.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var Ia=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),A={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)}}>`)},Ea=/^(?:[ \t]*(?:\n|$))+/,qa=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pa=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,We=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ma=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,dn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,gi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,mi=x(gi).replace(/bull/g,dn).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(),La=x(gi).replace(/bull/g,dn).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(),fn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Oa=/^[^\n]+/,pn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Na=x(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",pn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Qa=x(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,dn).getRegex(),yt="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",gn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ba=x("^ {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",gn).replace("tag",yt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xi=x(fn).replace("hr",We).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",yt).getRegex(),za=x(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",xi).getRegex(),mn={blockquote:za,code:qa,def:Na,fences:Pa,heading:Ma,hr:We,html:Ba,lheading:mi,list:Qa,newline:Ea,paragraph:xi,table:ge,text:Oa},yi=x("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",We).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",yt).getRegex(),Fa={...mn,lheading:La,table:yi,paragraph:x(fn).replace("hr",We).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",yi).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",yt).getRegex()},Ua={...mn,html:x(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",gn).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:ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:x(fn).replace("hr",We).replace("heading",` *#{1,6} *[^
2
+ Called by client`}function Kt(t,e){return e.data=t.errorData,e}function ue(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 he(t,e){return JSON.stringify({udfPath:ue(t),args:W(e)})}function Pr(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:ue(t),args:W(e),options:W({initialNumItems:r,id:i})})}var Ds=Object.defineProperty,Vs=(t,e,n)=>e in t?Ds(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,H=(t,e,n)=>Vs(t,typeof e!="symbol"?e+"":e,n);class Ws{constructor(){H(this,"nextQueryId"),H(this,"querySetVersion"),H(this,"querySet"),H(this,"queryIdToToken"),H(this,"identityVersion"),H(this,"auth"),H(this,"outstandingQueriesOlderThanRestart"),H(this,"outstandingAuthOlderThanRestart"),H(this,"paused"),H(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 s=ue(e),o=he(s,n),l=this.querySet.get(o);if(l!==void 0)return l.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{const a=this.nextQueryId++,c={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,c),this.queryIdToToken.set(a,o);const d=this.querySetVersion,u=this.querySetVersion+1,p={type:"Add",queryId:a,udfPath:s,args:[W(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,p):this.querySetVersion=u,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:u,modifications:[p]},unsubscribe:()=>this.removeSubscriber(o)}}}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=ue(e),i=he(r,n),s=this.querySet.get(i);return s!==void 0?s.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 s={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[W(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(s),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,s={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,s):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[s]}}}}var Hs=Object.defineProperty,Gs=(t,e,n)=>e in t?Hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,at=(t,e,n)=>Gs(t,typeof e!="symbol"?e+"":e,n);class Js{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,at(this,"inflightRequests"),at(this,"requestsOlderThanRestart"),at(this,"inflightMutationsCount",0),at(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const s=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:s,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)ot(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:ke(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:c}=e;ot(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:c!==void 0?ke(c):void 0,logLines:e.logLines},l=()=>s.onResult(o)}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:o}):(n.status={status:"Completed",result:o,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const s=i.status;s.status==="Completed"&&s.ts.lessThanOrEqual(e)&&(s.onResolve(),n.set(r,s.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 Qe=Symbol.for("functionName"),Mr=Symbol.for("toReferencePath");function Ks(t){return t[Mr]??null}function Zs(t){return t.startsWith("function://")}function Xs(t){let e;if(typeof t=="string")Zs(t)?e={functionHandle:t}:e={name:t};else if(t[Qe])e={name:t[Qe]};else{const n=Ks(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function I(t){const e=Xs(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[Qe];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Lr(t){return{[Qe]:t}}function Or(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Or(i)}else if(r===Qe){if(t.length<2){const o=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${o}\``)}const i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Ys=Or();var eo=Object.defineProperty,to=(t,e,n)=>e in t?eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lt=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n);class Be{constructor(e){lt(this,"queryResults"),lt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=ee(n[0]),i=I(e),s=this.queryResults.get(he(i,r));if(s!==void 0)return Be.queryValue(s.result)}getAllQueries(e){const n=[],r=I(e);for(const i of this.queryResults.values())i.udfPath===ue(r)&&n.push({args:i.args,value:Be.queryValue(i.result)});return n}setQuery(e,n,r){const i=ee(n),s=I(e),o=he(s,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:s,args:i,result:l};this.queryResults.set(o,a),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class no{constructor(){lt(this,"queryResults"),lt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(o=>!n.has(o.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Be(this.queryResults);for(const o of this.optimisticUpdates)o.update(i);const s=[];for(const[o,l]of this.queryResults){const a=r.get(o);(a===void 0||a.result!==l.result)&&s.push(o)}return s}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Be(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?Kt(r,new Jt(Se("query",n.udfPath,r))):new Error(Se("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var ro=Object.defineProperty,io=(t,e,n)=>e in t?ro(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zt=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);class E{constructor(e,n){Zt(this,"low"),Zt(this,"high"),Zt(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 E(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?Nr:e>=so?oo:new E(e%ze|0,e/ze|0)}toString(){return(BigInt(this.high)*BigInt(ze)+BigInt(this.low)).toString()}equals(e){return E.isLong(e)||(e=E.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 E.isLong(e)||(e=E.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"?E.fromNumber(e):new E(e.low,e.high)}}const Nr=new E(0,0),Qr=65536,ze=Qr*Qr,so=ze*ze,oo=new E(-1,-1);var ao=Object.defineProperty,lo=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ct=(t,e,n)=>lo(t,typeof e!="symbol"?e+"":e,n);class Br{constructor(e,n){ct(this,"version"),ct(this,"remoteQuerySet"),ct(this,"queryPath"),ct(this,"logger"),this.version={querySet:0,ts:E.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 o of r.logLines)ot(this.logger,"info","query",i,o);const s=ke(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:s,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ot(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?ke(s):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 Xt(t){const e=Le(t);return E.fromBytesLE(Array.from(e))}function co(t){const e=new Uint8Array(t.toBytesLE());return Oe(e)}function zr(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:Xt(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:Xt(t.startVersion.ts)},endVersion:{...t.endVersion,ts:Xt(t.endVersion.ts)}}}}function uo(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:co(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var ho=Object.defineProperty,fo=(t,e,n)=>e in t?ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C=(t,e,n)=>fo(t,typeof e!="symbol"?e+"":e,n);const po=1e3,go=1001,mo=1005,xo=4040;let ut;function je(){return ut===void 0&&(ut=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(ut+performance.now())}function Fr(){return`t=${Math.round((je()-ut)/100)/10}s`}const Ur={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 yo(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Ur))if(t.startsWith(e))return e;return"Unknown"}class bo{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,C(this,"socket"),C(this,"connectionCount"),C(this,"_hasEverConnected",!1),C(this,"lastCloseReason"),C(this,"transitionChunkBuffer",null),C(this,"defaultInitialBackoff"),C(this,"maxBackoff"),C(this,"retries"),C(this,"serverInactivityThreshold"),C(this,"reconnectDueToServerInactivityTimeout"),C(this,"scheduledReconnect",null),C(this,"networkOnlineHandler",null),C(this,"pendingNetworkRecoveryInfo",null),C(this,"uri"),C(this,"onOpen"),C(this,"onResume"),C(this,"onMessage"),C(this,"webSocketConstructor"),C(this,"logger"),C(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=zr(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:je()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Fr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Fr())),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=zr(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const o=this.assembleTransition(i);if(!o)return;i=o,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!==po&&n.code!==go&&n.code!==mo&&n.code!==xo){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=yo(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=uo(e),i=JSON.stringify(r);let s=!1;try{this.socket.ws.send(i),s=!0}catch(o){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${o}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${s?"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=je(),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=je()-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.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:je()})):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:Ur[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),s=i*(Math.random()-.5);return i+s}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=je()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,s=`${Math.round(n/1e4)/100}MB`,o=n/(r/1e3),l=`${Math.round(o/1e4)/100}MB per second`;this._logVerbose(`received ${s} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${s}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${s} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function _o(){return vo()}function vo(){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 Fe extends Error{}Fe.prototype.name="InvalidTokenError";function wo(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 ko(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 wo(e)}catch{return atob(e)}}function Dr(t,e){if(typeof t!="string")throw new Fe("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 Fe(`Invalid token specified: missing part #${n+1}`);let i;try{i=ko(r)}catch(s){throw new Fe(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new Fe(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var So=Object.defineProperty,jo=(t,e,n)=>e in t?So(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,P=(t,e,n)=>jo(t,typeof e!="symbol"?e+"":e,n);const Co=480*60*60*1e3,Vr=2;class Ro{constructor(e,n,r){P(this,"authState",{state:"noAuth"}),P(this,"configVersion",0),P(this,"syncState"),P(this,"authenticate"),P(this,"stopSocket"),P(this,"tryRestartSocket"),P(this,"pauseSocket"),P(this,"resumeSocket"),P(this,"clearAuth"),P(this,"logger"),P(this,"refreshTokenLeewaySeconds"),P(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>=Vr){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, ${Vr-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 s=i-r;if(s<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let o=Math.min(Co,(s-this.refreshTokenLeewaySeconds)*1e3);o<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${s}s`),o=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},o);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${o}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 Dr(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 To=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function $o(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function Ao(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Io(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of To){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(Ao)}var Eo=Object.defineProperty,qo=(t,e,n)=>e in t?Eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,R=(t,e,n)=>qo(t,typeof e!="symbol"?e+"":e,n);class Po{constructor(e,n,r){if(R(this,"address"),R(this,"state"),R(this,"requestManager"),R(this,"webSocketManager"),R(this,"authenticationManager"),R(this,"remoteQuerySet"),R(this,"optimisticQueryResults"),R(this,"_transitionHandlerCounter",0),R(this,"_nextRequestId"),R(this,"_onTransitionFns",new Map),R(this,"_sessionId"),R(this,"firstMessageReceived",!1),R(this,"debug"),R(this,"logger"),R(this,"maxObservedTimestamp"),R(this,"connectionStateSubscribers",new Map),R(this,"nextConnectionStateSubscriberId",0),R(this,"_lastPublishedConnectionState"),R(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const f=this.connectionState();if(JSON.stringify(f)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=f;for(const g of this.connectionStateSubscribers.values())g(f)}})}),R(this,"mark",f=>{this.debug&&$o(f,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&&Ts(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let s=r.webSocketConstructor;if(!s&&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");s=s||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?qr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Er({verbose:r.verbose??!1});const o=e.search("://");if(o===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(o+3),a=e.substring(0,o);let c;if(a==="http")c="ws";else if(a==="https")c="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${c}://${l}/api/${Tr}/sync`;this.state=new Ws,this.remoteQuerySet=new Br(f=>this.state.queryPath(f),this.logger),this.requestManager=new Js(this.logger,this.markConnectionStateDirty);const u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ro(this.state,{authenticate:f=>{const g=this.state.setAuth(f);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new no,this.addOnTransitionHandler(f=>{n(f.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=_o();const{unsavedChangesWarning:p}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(p===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else p!==!1&&window.addEventListener("beforeunload",f=>{if(this.requestManager.hasIncompleteRequests()){f.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(f||window.event).returnValue=g,g}});this.webSocketManager=new bo(d,{onOpen:f=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...f,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Br(S=>this.state.queryPath(S),this.logger);const[g,_]=this.state.restart();_&&this.webSocketManager.sendMessage(_),this.webSocketManager.sendMessage(g);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[f,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),f&&this.webSocketManager.sendMessage(f);for(const _ of this.requestManager.resume())this.webSocketManager.sendMessage(_)},onMessage:f=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),f.type){case"Transition":{this.observedTimestamp(f.endVersion.ts),this.authenticationManager.onTransition(f),this.remoteQuerySet.transition(f),this.state.transition(f);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{f.success&&this.observedTimestamp(f.ts);const g=this.requestManager.onResponse(f);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(f);break}case"AuthError":{this.authenticationManager.onAuthError(f);break}case"FatalError":{const g=Us(this.logger,f.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},s,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&u()}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[s,o]of n){const l=this.state.queryToken(s);if(l!==null){const a={result:o,udfPath:this.state.queryPath(s),args:this.state.queryArgs(s)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(s=>{const o=this.optimisticQueryResults.rawQueryResult(s);return{token:s,modification:{kind:"Updated",result:o}}}),reflectedMutations:Array.from(e).map(([s,o])=>({requestId:s,result:o})),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?Dr(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=ee(n),{modification:s,queryToken:o,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return s!==null&&this.webSocketManager.sendMessage(s),{queryToken:o,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=ee(n),i=he(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=ee(n),i=he(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=ee(n),i=he(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?Kt(i,new Jt(Se("mutation",e,i))):new Error(Se("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:s}=this.enqueueMutation(e,n,r,i);return s}enqueueMutation(e,n,r,i){const s=ee(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const u=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},f=this.optimisticQueryResults.applyOptimisticUpdate(u,o).map(g=>{const _=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:_===void 0?void 0:{success:!0,value:_,logLines:[]}}}});this.handleTransition({queries:f,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[W(s)]},a=this.webSocketManager.sendMessage(l),c=this.requestManager.request(l,a);return{requestId:o,mutationPromise:c}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?Kt(r,new Jt(Se("action",e,r))):new Error(Se("action",e,r));return r.value}async actionInternal(e,n,r){const i=ee(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[W(i)]},l=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,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=Io(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-${Tr}`},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 Yt(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 Mo=Object.defineProperty,Lo=(t,e,n)=>e in t?Mo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Wr=(t,e,n)=>Lo(t,typeof e!="symbol"?e+"":e,n);class Oo{constructor(e,n){this.client=e,this.onTransition=n,Wr(this,"paginatedQuerySet",new Map),Wr(this,"lastTransitionTs"),this.lastTransitionTs=E.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=ue(e),s=Pr(i,n,r),o=()=>this.removePaginatedQuerySubscriber(s),l=this.paginatedQuerySet.get(s);return l?(l.numSubscribers+=1,{paginatedQueryToken:s,unsubscribe:o}):(this.paginatedQuerySet.set(s,{token:s,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(s,null,r.initialNumItems),{paginatedQueryToken:s,unsubscribe:o})}localQueryResult(e,n,r){const i=ue(e),s=Pr(i,n,r);return this.localQueryResultByToken(s)}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=[],s=!1,o=!1;for(const a of r){const c=this.client.localQueryResultByToken(a);if(c===void 0){s=!0,o=!1;continue}const d=Yt(c);i=i.concat(d.page),o=!!d.isDone}let l;return s?l=i.length===0?"LoadingFirstPage":"LoadingMore":o?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(o=>o.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,o=>this.client.localQueryResultByToken(o)),i=r.map(o=>({token:o,modification:{kind:"Updated",result:this.localQueryResultByToken(o)}})));const s={...e,paginatedQueries:i};this.onTransition(s)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const s=Yt(i);if(s.isDone)return!1;this.addPageToPaginatedQuery(e,s.continueCursor,n);const o={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(o),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,s]of this.paginatedQuerySet)for(const o of this.allQueryTokens(s))if(r.has(o)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:s,pageKeyToQuery:o,pageKeys:l}=i;for(const[a,[c,d]]of s)n(o.get(c).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,c,d);for(const a of l){if(s.has(a))continue;const c=o.get(a).queryToken,d=n(c);if(!d)continue;const u=Yt(d);u.splitCursor&&(u.pageStatus==="SplitRecommended"||u.pageStatus==="SplitRequired"||u.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,u.splitCursor,u.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const s=e.nextPageKey++,o=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(s,a);const c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,c),e.ongoingSplits.set(n,[s,o])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),s=i.nextPageKey++,o={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:o},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(s),i.pageKeyToQuery.set(s,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 s=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const o=e.pageKeys.indexOf(n);e.pageKeys.splice(o,1,r,i),e.ongoingSplits.delete(n),s.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 No({getCurrentValue:t,subscribe:e}){const[n,r]=O(()=>({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})),N(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const c=t();return a.value===c?a:{...a,value:c}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var Qo=Object.defineProperty,Bo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,te=(t,e,n)=>Bo(t,typeof e!="symbol"?e+"":e,n);const zo=5e3;if(typeof Ft>"u")throw new Error("Required dependency 'react' not found");function Hr(t,e,n){function r(i){return Wo(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(s){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${I(t)}`);return Hr(t,e,s)},r}class Fo{constructor(e,n){if(te(this,"address"),te(this,"cachedSync"),te(this,"cachedPaginatedQueryClient"),te(this,"listeners"),te(this,"options"),te(this,"closed",!1),te(this,"_logger"),te(this,"adminAuth"),te(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?qr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Er({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 Po(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new Oo(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,s=I(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),c=this.listeners.get(l);return c!==void 0?c.add(o):this.listeners.set(l,new Set([o])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(o),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(s,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(s,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(s,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??zo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=I(e);return{onUpdate:s=>{const{paginatedQueryToken:o,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(o);return a!==void 0?a.add(s):this.listeners.set(o,new Set([s])),()=>{if(this.closed)return;const c=this.listeners.get(o);c.delete(s),c.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=I(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=I(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((s,o)=>{const l=r.onUpdate(()=>{l();try{s(r.localQueryResult())}catch(a){o(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 en=Ft.createContext(void 0);function Uo(){return nt(en)}const Do=({client:t,children:e})=>Ft.createElement(en.Provider,{value:t},e);function Vo(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:ee(e[0]),i=typeof t=="string"?Lr(t):t,s=I(i),o=Q(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(W(r)),s,n]),a=Ko(o).query;if(a instanceof Error)throw a;return a}function Gr(t){const e=typeof t=="string"?Lr(t):t,n=nt(en);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 Q(()=>Hr(e,n),[n,I(e)])}function Wo(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 Ho=Object.defineProperty,Go=(t,e,n)=>e in t?Ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tn=(t,e,n)=>Go(t,typeof e!="symbol"?e+"":e,n);class Jo{constructor(e){tn(this,"createWatch"),tn(this,"queries"),tn(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:s}=e[n];if(I(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(I(r)!==I(o.query)||JSON.stringify(W(i))!==JSON.stringify(W(o.args))||JSON.stringify(s)!==JSON.stringify(o.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,s?{paginationOptions:s}:{}))}}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:s}=e[r],o=e[r].paginationOptions;I(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(c){if(c instanceof Error)a=c;else throw c}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:s,paginationOptions:o}=this.queries[n],l="journal"in s?s.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...o?{paginationOptions:o}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:s}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const o=this.createWatch(n,r,{...s?{journal:s}:[],...i?{paginationOptions:i}:{}}),l=o.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:o,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 Ko(t){const e=Uo();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=Q(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return Zo(t,n)}function Zo(t,e){const[n]=O(()=>new Jo(e));n.createWatch!==e&&n.setCreateWatch(e),N(()=>()=>n.destroy(),[n]);const r=Q(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return No(r)}var Xo=Symbol.for("preact-signals");function ht(){if(ie>1)ie--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,nn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&Zr(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(nn=0,ie--,e)throw t}}function Yo(t){if(ie>0)return t();ie++;try{return t()}finally{ht()}}var y=void 0;function Jr(t){var e=y;y=void 0;try{return t()}finally{y=e}}var Ue=void 0,ie=0,nn=0,dt=0;function Kr(t){if(y!==void 0){var e=t.n;if(e===void 0||e.t!==y)return e={i:0,S:t,p:y.s,n:void 0,t:y,e:void 0,x:void 0,r:e},y.s!==void 0&&(y.s.n=e),y.s=e,t.n=e,32&y.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=y.s,e.n=void 0,y.s.n=e,y.s=e),e}}function T(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}T.prototype.brand=Xo,T.prototype.h=function(){return!0},T.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:Jr(function(){var r;(r=e.W)==null||r.call(e)}))},T.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&&Jr(function(){var i;(i=e.Z)==null||i.call(e)}))}},T.prototype.subscribe=function(t){var e=this;return De(function(){var n=e.value,r=y;y=void 0;try{t(n)}finally{y=r}},{name:"sub"})},T.prototype.valueOf=function(){return this.value},T.prototype.toString=function(){return this.value+""},T.prototype.toJSON=function(){return this.value},T.prototype.peek=function(){var t=y;y=void 0;try{return this.value}finally{y=t}},Object.defineProperty(T.prototype,"value",{get:function(){var t=Kr(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(nn>100)throw new Error("Cycle detected");this.v=t,this.i++,dt++,ie++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{ht()}}}});function se(t,e){return new T(t,e)}function Zr(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 Xr(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 Yr(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 de(t,e){T.call(this,void 0),this.x=t,this.s=void 0,this.g=dt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}de.prototype=new T,de.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===dt))return!0;if(this.g=dt,this.f|=1,this.i>0&&!Zr(this))return this.f&=-2,!0;var t=y;try{Xr(this),y=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 y=t,Yr(this),this.f&=-2,!0},de.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)}T.prototype.S.call(this,t)},de.prototype.U=function(t){if(this.t!==void 0&&(T.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)}},de.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(de.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Kr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ei(t,e){return new de(t,e)}function ti(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ie++;var n=y;y=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,rn(t),r}finally{y=n,ht()}}}function rn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ti(t)}function ea(t){if(y!==this)throw new Error("Out-of-order effect");Yr(this),y=t,this.f&=-2,8&this.f&&rn(this),ht()}function Ce(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ce.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()}},Ce.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ti(this),Xr(this),ie++;var t=y;return y=this,ea.bind(this,t)},Ce.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ce.prototype.d=function(){this.f|=8,1&this.f||rn(this)},Ce.prototype.dispose=function(){this.d()};function De(t,e){var n=new Ce(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var ni,ft,ta=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ri=[];De(function(){ni=this.N})();function Re(t,e){m[t]=e.bind(null,m[t]||function(){})}function pt(t){if(ft){var e=ft;ft=void 0,e()}ft=t&&t.S()}function ii(t){var e=this,n=t.data,r=gt(n);r.value=n;var i=Q(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var c=ei(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),d=ei(function(){return!Array.isArray(c.value)&&!Cn(c.value)}),u=De(function(){if(this.N=si,d.value){var f=c.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=f)}}),p=e.__$u.d;return e.__$u.d=function(){u(),p.call(this)},[d,c]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}ii.displayName="ReactiveTextNode",Object.defineProperties(T.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ii},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Re("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var s=r[i];s instanceof T&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Re("__r",function(t,e){if(t(e),e.type!==M){pt();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,s){var o;return De(function(){o=this},{name:s}),o.c=i,o})(function(){var i;ta&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),pt(n)}}),Re("__e",function(t,e,n,r){pt(),t(e,n,r)}),Re("diffed",function(t,e){pt();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var s=n.U;if(s)for(var o in s){var l=s[o];l!==void 0&&!(o in r)&&(l.d(),s[o]=void 0)}else s={},n.U=s;for(var a in r){var c=s[a],d=r[a];c===void 0?(c=na(n,a,d,i),s[a]=c):c.o(d,i)}}}t(e)});function na(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=se(n);return{o:function(o,l){s.value=o,r=l},d:De(function(){this.N=si;var o=s.value.value;r[e]!==o&&(r[e]=o,i?t[e]=o:o!=null&&(o!==!1||e[4]==="-")?t.setAttribute(e,o):t.removeAttribute(e))})}}Re("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 s=r[i];s&&s.d()}}}}else{var o=e.__c;if(o){var l=o.__$u;l&&(o.__$u=void 0,l.d())}}t(e)}),Re("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),L.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 s=2&this.__$f;if(!(r||s||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function gt(t,e){return Q(function(){return se(t,e)},[])}var ra=function(t){queueMicrotask(function(){queueMicrotask(t)})};function ia(){Yo(function(){for(var t;t=ri.shift();)ni.call(t)})}function si(){ri.push(this)===1&&(m.requestAnimationFrame||ra)(ia)}const $=se(!1),mt=se(void 0);function sa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function oa(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function aa(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 la(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function ca(t,e){const[n,r]=O(null);return N(()=>{r(null);const i=e??"https://festive-mouse-978.eu-west-1.convex.cloud",s=i?oa(i):void 0;if(!s||!t)return;const o=new AbortController;async function l(a){try{const c=await la(a,t,o.signal);c&&r(c)}catch(c){if(c instanceof Error&&c.name==="AbortError")return}}return l(s),()=>{o.abort()}},[t,e]),n}const oi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resume 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"},ua={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch fortsetzen",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"},ha=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],da="de",fa="jex-locale",sn=se("de"),pa={en:oi,de:ua};function ne(){return pa[sn.value]??oi}function on(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return ha.some(r=>r.value===e)?e:null}function ai(t){const e=on(t);if(e)return e;try{const n=on(localStorage.getItem(fa));if(n)return n}catch{}if(typeof navigator<"u"){const n=on(navigator.language);if(n)return n}return da}function ga(t){N(()=>{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&&(sn.value=ai(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const an="jex-session-ref",xt="jex-session-active",oe=se(null),fe=se(!1);function ma(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function xa(){try{const t=sessionStorage.getItem(an),e=sessionStorage.getItem(xt);oe.value=t??null,fe.value=t!==null&&e==="true"}catch{oe.value=null,fe.value=!1}}function li(){const t=ma();oe.value=t,fe.value=!1;try{sessionStorage.setItem(an,t),sessionStorage.removeItem(xt)}catch{}return t}function ya(t){oe.value=t,fe.value=!0;try{sessionStorage.setItem(an,t),sessionStorage.setItem(xt,"true")}catch{}}function ba(){if(oe.value){fe.value=!0;try{sessionStorage.setItem(xt,"true")}catch{}}}function _a(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}const B=se([{id:"chat"}]);function Ve(t){B.value=[...B.value,t]}function ci(){B.value.length>1&&(B.value=B.value.slice(0,-1))}function ln(t){B.value=[...B.value.slice(0,-1),t]}function cn({size:t=24}){return h("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:[h("path",{d:"M12 8V4H8"}),h("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),h("path",{d:"M2 14h2"}),h("path",{d:"M20 14h2"}),h("path",{d:"M15 13v2"}),h("path",{d:"M9 13v2"})]})}function ui({title:t}){const e=ne(),n=B.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:ci,"aria-label":e.back||"Go back",children:h("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:h("path",{d:"m15 18-6-6 6-6"})})}),!n&&h(cn,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function va({size:t=14}){return h("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:h("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 hi(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(va,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function di({size:t=28}){return h("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:h("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 wa({size:t=28}){return h("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:[h("path",{d:"M18 6 6 18"}),h("path",{d:"m6 6 12 12"})]})}function ka({size:t=24,...e}){return h("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:h("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 Sa={chat:h(di,{size:28}),bot:h(cn,{size:28}),sparkles:h(ka,{size:28})},ja={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Ca({radius:t="full",iconOption:e="chat",label:n="Chatte mit uns"}){const r=ne(),i=n!=="";return h("button",{class:`jex-floating-button ${!$.value&&i?"jex-has-label":""}`,style:{borderRadius:ja[t]??"9999px"},onClick:()=>{$.value=!$.value},"aria-label":$.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:$.value?h(wa,{size:28}):h("div",{class:"jex-fab-inner",children:[Sa[e],i&&h("span",{class:"jex-fab-label",children:n})]})})}function Ra({title:t}){const e=ne(),n=oe.value,[r,i]=O("");function s(){li(),Ve({id:"chat"})}function o(){Ve({id:"chat"})}function l(a){a.preventDefault();const c=r.trim().toUpperCase();c&&(ya(c),Ve({id:"chat"}))}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-hero",children:[h("div",{class:"jex-home-avatar",children:[h(di,{size:24}),h("span",{class:"jex-home-status-dot"})]}),h("div",{class:"jex-home-hero-text",children:[h("h2",{class:"jex-home-title",children:t}),h("span",{class:"jex-home-status",children:e.statusOnline})]})]}),h("form",{class:"jex-home-lookup",onSubmit:l,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:e.referencePlaceholder,value:r,onInput:a=>{i(a.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!r.trim(),children:e.resume})]}),h("div",{class:"jex-home-actions",children:[n&&h("button",{class:"jex-home-resume-card",onClick:o,children:[h("div",{class:"jex-home-resume-top",children:[h("span",{class:"jex-home-resume-label",children:e.resumeConversation}),h("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:h("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),h("span",{class:"jex-home-resume-ref",children:n})]}),h("button",{class:"jex-home-new-btn",onClick:s,children:n?e.startNewConversation:e.chatWith.replace("{title}",t)})]})]})}function Ta({title:t}){const e=ne();return h("div",{class:"jex-selection",children:[h("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),h("div",{class:"jex-selection-options",children:[h("button",{class:"jex-selection-option",onClick:()=>Ve({id:"chat"}),children:[h("span",{class:"jex-selection-icon",children:"💬"}),h("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),h("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),h("button",{class:"jex-selection-option",onClick:()=>Ve({id:"form"}),children:[h("span",{class:"jex-selection-icon",children:"📝"}),h("span",{class:"jex-selection-label",children:e.submitTicket}),h("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function fi(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return fi(t,s)}else if(i===Mr){if(e.length<1){const s=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${s}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const $a=()=>fi("components",[]),un=Ys;$a();function Aa(t){const e=et(null),n=gt(!1),r=gt(!1),i=Gr(un.functions.chat.public.sessions.createOrResume),s=tt(async()=>{if(e.current)return e.current;n.value=!0;const l=oe.value!==null,a=oe.value??li();try{const c=await i({orgSlug:t,visitorId:a,...mt.value?{source:mt.value}:{}});l&&c.isNew&&(r.value=!0);const d={sessionId:c.sessionId,visitorId:a};return e.current=d,d}catch(c){return console.error("[jexity] Failed to create session:",c),null}finally{n.value=!1}},[t,i,n,r]),o=e.current;return{sessionId:o?.sessionId??null,visitorId:o?.visitorId??null,isLoading:n.value,sessionNotFound:r.value,ensureSession:s}}function hn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var pe=hn();function pi(t){pe=t}var ge={exec:()=>null};function x(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(A.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var Ia=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),A={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)}}>`)},Ea=/^(?:[ \t]*(?:\n|$))+/,qa=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pa=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,We=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ma=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,dn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,gi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,mi=x(gi).replace(/bull/g,dn).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(),La=x(gi).replace(/bull/g,dn).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(),fn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Oa=/^[^\n]+/,pn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Na=x(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",pn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Qa=x(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,dn).getRegex(),yt="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",gn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ba=x("^ {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",gn).replace("tag",yt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xi=x(fn).replace("hr",We).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",yt).getRegex(),za=x(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",xi).getRegex(),mn={blockquote:za,code:qa,def:Na,fences:Pa,heading:Ma,hr:We,html:Ba,lheading:mi,list:Qa,newline:Ea,paragraph:xi,table:ge,text:Oa},yi=x("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",We).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",yt).getRegex(),Fa={...mn,lheading:La,table:yi,paragraph:x(fn).replace("hr",We).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",yi).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",yt).getRegex()},Ua={...mn,html:x(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",gn).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:ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:x(fn).replace("hr",We).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("lheading",mi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Da=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Va=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,bi=/^( {2,}|\\)\n(?!\s*$)/,Wa=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Te=/[\p{P}\p{S}]/u,bt=/[\s\p{P}\p{S}]/u,xn=/[^\s\p{P}\p{S}]/u,Ha=x(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,bt).getRegex(),_i=/(?!~)[\p{P}\p{S}]/u,Ga=/(?!~)[\s\p{P}\p{S}]/u,Ja=/(?:[^\s\p{P}\p{S}]|~)/u,Ka=x(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ia?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),vi=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Za=x(vi,"u").replace(/punct/g,Te).getRegex(),Xa=x(vi,"u").replace(/punct/g,_i).getRegex(),wi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ya=x(wi,"gu").replace(/notPunctSpace/g,xn).replace(/punctSpace/g,bt).replace(/punct/g,Te).getRegex(),el=x(wi,"gu").replace(/notPunctSpace/g,Ja).replace(/punctSpace/g,Ga).replace(/punct/g,_i).getRegex(),tl=x("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,xn).replace(/punctSpace/g,bt).replace(/punct/g,Te).getRegex(),nl=x(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Te).getRegex(),rl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",il=x(rl,"gu").replace(/notPunctSpace/g,xn).replace(/punctSpace/g,bt).replace(/punct/g,Te).getRegex(),sl=x(/\\(punct)/,"gu").replace(/punct/g,Te).getRegex(),ol=x(/^<(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(),al=x(gn).replace("(?:-->|$)","-->").getRegex(),ll=x("^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",al).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_t=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,cl=x(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",_t).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ki=x(/^!?\[(label)\]\[(ref)\]/).replace("label",_t).replace("ref",pn).getRegex(),Si=x(/^!?\[(ref)\](?:\[\])?/).replace("ref",pn).getRegex(),ul=x("reflink|nolink(?!\\()","g").replace("reflink",ki).replace("nolink",Si).getRegex(),ji=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,yn={_backpedal:ge,anyPunctuation:sl,autolink:ol,blockSkip:Ka,br:bi,code:Va,del:ge,delLDelim:ge,delRDelim:ge,emStrongLDelim:Za,emStrongRDelimAst:Ya,emStrongRDelimUnd:tl,escape:Da,link:cl,nolink:Si,punctuation:Ha,reflink:ki,reflinkSearch:ul,tag:ll,text:Wa,url:ge},hl={...yn,link:x(/^!?\[(label)\]\((.*?)\)/).replace("label",_t).getRegex(),reflink:x(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_t).getRegex()},bn={...yn,emStrongRDelimAst:el,emStrongLDelim:Xa,delLDelim:nl,delRDelim:il,url:x(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ji).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:x(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ji).getRegex()},dl={...bn,br:x(bi).replace("{2,}","*").getRegex(),text:x(bn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},vt={normal:mn,gfm:Fa,pedantic:Ua},He={normal:yn,gfm:bn,breaks:dl,pedantic:hl},fl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ci=t=>fl[t];function G(t,e){if(e){if(A.escapeTest.test(t))return t.replace(A.escapeReplace,Ci)}else if(A.escapeTestNoEncode.test(t))return t.replace(A.escapeReplaceNoEncode,Ci);return t}function Ri(t){try{t=encodeURI(t).replace(A.percentDecode,"%")}catch{return null}return t}function Ti(t,e){let n=t.replace(A.findPipe,(s,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),r=n.split(A.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(A.slashPipe,"|");return r}function Ge(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 pl(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 gl(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=i,n++;return r}function $i(t,e,n,r,i){let s=e.href,o=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:s,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function ml(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
4
4
  `).map(s=>{let o=s.match(n.other.beginningSpace);if(o===null)return s;let[l]=o;return l.length>=i.length?s.slice(i.length):s}).join(`
5
5
  `)}var wt=class{options;rules;lexer;constructor(t){this.options=t||pe}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:Ge(n,`
@@ -57,5 +57,5 @@ ${this.parser.parse(t)}</blockquote>
57
57
  ${t}</tr>
58
58
  `}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
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>${G(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=Ri(t);if(i===null)return r;t=i;let s='<a href="'+t+'"';return e&&(s+=' title="'+G(e)+'"'),s+=">"+r+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Ri(t);if(i===null)return G(n);t=i;let s=`<img src="${t}" alt="${G(n)}"`;return e&&(s+=` title="${G(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:G(t.text)}},_n=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}},F=class Sn{options;renderer;textRenderer;constructor(e){this.options=e||pe,this.options.renderer=this.options.renderer||new kt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new _n}static parse(e,n){return new Sn(n).parse(e)}static parseInline(e,n){return new Sn(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 o=i,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let s=i;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let o='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let s=e[i];if(this.options.extensions?.renderers?.[s.type]){let l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=l||"";continue}}let o=s;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},Je=class{options;block;constructor(t){this.options=t||pe}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?z.lex:z.lexInline}provideParser(){return this.block?F.parse:F.parseInline}},xl=class{defaults=hn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=F;Renderer=kt;TextRenderer=_n;Lexer=z;Tokenizer=wt;Hooks=Je;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 s of i.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of i.rows)for(let o of s)n=n.concat(this.walkTokens(o.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(s=>{let o=i[s].flat(1/0);n=n.concat(this.walkTokens(o,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 s=e.renderers[i.name];s?e.renderers[i.name]=function(...o){let l=i.renderer.apply(this,o);return l===!1&&(l=s.apply(this,o)),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 s=e[i.level];s?s.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 kt(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,l=n.renderer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new wt(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,l=n.tokenizer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new Je;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,l=n.hooks[o],a=i[o];Je.passThroughHooks.has(s)?i[o]=c=>{if(this.defaults.async&&Je.passThroughHooksRespectAsync.has(s))return(async()=>{let u=await l.call(i,c);return a.call(i,u)})();let d=l.call(i,c);return a.call(i,d)}:i[o]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await l.apply(i,c);return u===!1&&(u=await a.apply(i,c)),u})();let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(o){let l=[];return l.push(s.call(this,o)),i&&(l=l.concat(i.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return z.lex(t,e??this.defaults)}parser(t,e){return F.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return s(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 s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(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 o=i.hooks?await i.hooks.preprocess(e):e,l=await(i.hooks?await i.hooks.provideLexer():t?z.lex:z.lexInline)(o,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser():t?F.parse:F.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(s);try{i.hooks&&(e=i.hooks.preprocess(e));let o=(i.hooks?i.hooks.provideLexer():t?z.lex:z.lexInline)(e,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():t?F.parse:F.parseInline)(o,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(o){return s(o)}}}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>"+G(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},me=new xl;function b(t,e){return me.parse(t,e)}b.options=b.setOptions=function(t){return me.setOptions(t),b.defaults=me.defaults,pi(b.defaults),b},b.getDefaults=hn,b.defaults=pe,b.use=function(...t){return me.use(...t),b.defaults=me.defaults,pi(b.defaults),b},b.walkTokens=function(t,e){return me.walkTokens(t,e)},b.parseInline=me.parseInline,b.Parser=F,b.parser=F.parse,b.Renderer=kt,b.TextRenderer=_n,b.Lexer=z,b.lexer=z.lex,b.Tokenizer=wt,b.Hooks=Je,b.parse=b,b.options,b.setOptions,b.use,b.walkTokens,b.parseInline,F.parse,z.lex,b.setOptions({breaks:!0,gfm:!0});function yl({text:t}){const e=Q(()=>{if(!t)return"";const n=b.parse(t);return typeof n=="string"?n:""},[t]);return h("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}function bl(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function St({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:s,botAvatarUrl:o}){const l=!!r,[a,c]=O(!1),d=tt(()=>c(!0),[]),u=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return h("div",{class:"jex-message-row bot",children:[h("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?h("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?h("span",{class:"jex-avatar-initials",children:bl(i??"")}):o&&!a?h("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):h(cn,{size:14})}),h("div",{class:"jex-message-content",children:[h("div",{class:u,children:[h(yl,{text:t}),e&&h("span",{class:"jex-streaming-cursor"})]}),l&&i&&h("span",{class:"jex-message-author",children:i})]})]})}function _l({text:t}){return h("div",{class:"jex-message user",children:t})}function vl(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function wl({conversations:t,greeting:e,sessionNotFound:n}){const r=ne(),i=et(null);return N(()=>{i.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),h("div",{class:"jex-chat-messages",children:[h(St,{text:e}),n&&h("div",{class:"jex-session-notice",children:r.sessionNotFound??"Your previous session was not found. Starting a new conversation."}),t?.map(s=>{if(s.role==="user")return h(_l,{text:s.content},s._id);const o={authorId:s.authorId,authorName:s.authorName,authorImage:s.authorImage};return s.status==="streaming"&&s.content===""?h(vl,{},s._id):s.status==="streaming"?h(St,{text:s.content,streaming:!0,...o},s._id):s.status==="error"?h(St,{text:s.errorMessage??"Something went wrong. Please try again.",error:!0,...o},s._id):h(St,{text:s.content,...o},s._id)}),h("div",{ref:i})]})}function kl({size:t=18}){return h("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:[h("path",{d:"M22 2 11 13"}),h("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function Sl({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,ensureSession:i}){const s=ne(),o=gt(""),l=Gr(un.functions.chat.public.conversations.send),a=n||r;async function c(){const d=o.value.trim();if(!d||a)return;const u=t&&e?{sessionId:t,visitorId:e}:await i();u&&(ba(),o.value="",l({sessionId:u.sessionId,visitorId:u.visitorId,content:d}).catch(p=>{console.error("[jexity] Failed to send message:",p)}))}return h("div",{class:"jex-chat-input",children:[h("input",{type:"text","aria-label":s.inputPlaceholder,placeholder:r?s.aiThinking:s.inputPlaceholder,value:o.value,onInput:d=>{o.value=d.currentTarget.value},onKeyDown:d=>{d.key==="Enter"&&c()},disabled:a}),h("button",{class:"jex-send-btn",onClick:c,"aria-label":s.sendAriaLabel,disabled:a,children:h(kl,{size:18})})]})}function Ai({message:t}){return h("div",{class:"jex-overlay jex-loading",children:[h("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&h("p",{class:"jex-loading-message",children:t})]})}function jl({greeting:t,orgSlug:e}){const n=ne(),{sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,ensureSession:l}=Aa(e),a=Vo(un.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),c=r!==null&&a===void 0,d=a?.some(u=>u.status==="streaming")??!1;return N(()=>{fe.value&&!r&&l()},[l,r]),s||c&&fe.value?h(Ai,{message:n.resumeConversation}):h(M,{children:[h(wl,{conversations:a,greeting:t,sessionNotFound:o}),h(Sl,{sessionId:r,visitorId:i,isLoading:s,isStreaming:d,ensureSession:l})]})}function Cl(){const t=ne(),[e,n]=O(""),[r,i]=O(""),[s,o]=O("");async function l(a){a.preventDefault(),ln({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const c="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();ln({id:"confirmation",ref:c})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Rl({ticketRef:t}){const e=ne();return h("div",{class:"jex-confirmation",children:[h("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),h("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),h("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),h("div",{class:"jex-confirmation-ref",children:t}),h("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),h("button",{class:"jex-confirmation-done",onClick:()=>{$.value=!1},children:e.done})]})}function Tl({message:t,onRetry:e,onBack:n}){return h("div",{class:"jex-overlay jex-error",children:[h("p",{class:"jex-error-message",children:t}),h("div",{class:"jex-error-actions",children:[e&&h("button",{class:"jex-error-retry",onClick:e,children:"Try again"}),n&&h("button",{class:"jex-error-back",onClick:n,children:"Go back"})]})]})}function Ii({greeting:t,title:e,orgSlug:n}){const r=B.value,i=r[r.length-1],s=r.findLast(o=>o.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h(Ra,{greeting:t,title:e}),i.id==="selection"&&h(Ta,{title:e}),i.id==="form"&&h(Cl,{}),i.id==="confirmation"&&s&&h(Rl,{ticketRef:s.ref}),i.id==="chat"&&h(jl,{greeting:t,orgSlug:n}),i.id==="loading"&&h(Ai,{message:i.message}),i.id==="error"&&h(Tl,{message:i.message,onRetry:()=>ln({id:"loading"}),onBack:ci})]})}function $l({options:t}){const e=ca(t.orgSlug,t.convexUrl);ga(t.parentOrigin),N(()=>{xa()},[]);const n=aa(t,e);N(()=>{sn.value=ai(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",s=_a({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight}),o=n.mode==="embedded";return h("div",{class:`jex-widget ${i}`.trim(),style:s,children:o?h("div",{class:"jex-embedded",children:[h(ui,{title:n.title}),h(Ii,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(hi,{})]}):h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[$.value&&h("div",{class:"jex-chat-window",children:[h(ui,{title:n.title}),h(Ii,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(hi,{})]}),h(Ca,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Al='.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}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) 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-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-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{display:block;font-size:10px;color:var(--jex-text-muted);margin-top:2px;padding-left:4px}.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:16px;border-top:1px solid var(--jex-border-window);display:flex;gap:8px;flex-shrink:0}.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:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s cubic-bezier(.175,.885,.32,1.275);flex-shrink:0}.jex-send-btn:hover{transform:scale(1.05);background:var(--jex-primary-hover)}.jex-send-btn:active{transform:scale(.95)}.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}.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-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:13px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}.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}';function Il(t){const e=document.createElement("style");e.textContent=Al,t.appendChild(e)}const El="https://tame-spider-109.eu-west-1.convex.cloud";let vn=null;function ql(t){const e=t??El;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 vn||(vn=new Fo(sa(e))),vn}function Pl(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Il(n),mt.value=e.source,e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),$.value=!0,B.value=[{id:"home"}]);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),ce(h(Do,{client:ql(e.convexUrl),children:h($l,{options:e})}),r),function(){ce(null,r),$.value=!1,mt.value=void 0,B.value=[{id:"chat"}]}}function Ml(t,e,n){const r=Pl(t,e),i=new Set,s=$.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){$.value=!0},close(){$.value=!1},toggle(){$.value=!$.value},get isOpen(){return $.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let Ke=null;function Ll(t){Ke&&Ke.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=Ml(e,t,()=>{t.container||e.remove(),Ke===n&&(Ke=null)});return Ke=n,n}function xe(t,e){return t.getAttribute(e)??void 0}function Ei(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const n={orgSlug:t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",position:xe(t,"data-position")??void 0,theme:xe(t,"data-theme")??void 0,greeting:xe(t,"data-greeting"),title:xe(t,"data-title"),primaryColor:xe(t,"data-primary-color"),locale:xe(t,"data-locale"),convexUrl:xe(t,"data-convex-url")};window.JexityChat=Ll(n)}document.readyState==="complete"?Ei():window.addEventListener("load",Ei)})();
60
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+G(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},me=new xl;function b(t,e){return me.parse(t,e)}b.options=b.setOptions=function(t){return me.setOptions(t),b.defaults=me.defaults,pi(b.defaults),b},b.getDefaults=hn,b.defaults=pe,b.use=function(...t){return me.use(...t),b.defaults=me.defaults,pi(b.defaults),b},b.walkTokens=function(t,e){return me.walkTokens(t,e)},b.parseInline=me.parseInline,b.Parser=F,b.parser=F.parse,b.Renderer=kt,b.TextRenderer=_n,b.Lexer=z,b.lexer=z.lex,b.Tokenizer=wt,b.Hooks=Je,b.parse=b,b.options,b.setOptions,b.use,b.walkTokens,b.parseInline,F.parse,z.lex,b.setOptions({breaks:!0,gfm:!0});function yl({text:t}){const e=Q(()=>{if(!t)return"";const n=b.parse(t);return typeof n=="string"?n:""},[t]);return h("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}function bl(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function St({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:s,botAvatarUrl:o}){const l=!!r,[a,c]=O(!1),d=tt(()=>c(!0),[]),u=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return h("div",{class:"jex-message-row bot",children:[h("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?h("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?h("span",{class:"jex-avatar-initials",children:bl(i??"")}):o&&!a?h("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):h(cn,{size:14})}),h("div",{class:"jex-message-content",children:[h("div",{class:u,children:[h(yl,{text:t}),e&&h("span",{class:"jex-streaming-cursor"})]}),l&&i&&h("span",{class:"jex-message-author",children:i})]})]})}function _l({text:t}){return h("div",{class:"jex-message user",children:t})}function vl(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function wl({conversations:t,greeting:e,sessionNotFound:n}){const r=ne(),i=et(null);return N(()=>{i.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),h("div",{class:"jex-chat-messages",children:[h(St,{text:e}),n&&h("div",{class:"jex-session-notice",children:r.sessionNotFound??"Your previous session was not found. Starting a new conversation."}),t?.map(s=>{if(s.role==="user")return h(_l,{text:s.content},s._id);const o={authorId:s.authorId,authorName:s.authorName,authorImage:s.authorImage};return s.status==="streaming"&&s.content===""?h(vl,{},s._id):s.status==="streaming"?h(St,{text:s.content,streaming:!0,...o},s._id):s.status==="error"?h(St,{text:s.errorMessage??"Something went wrong. Please try again.",error:!0,...o},s._id):h(St,{text:s.content,...o},s._id)}),h("div",{ref:i})]})}function kl({size:t=18}){return h("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:[h("path",{d:"M22 2 11 13"}),h("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function Sl({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,ensureSession:i}){const s=ne(),o=gt(""),l=Gr(un.functions.chat.public.conversations.send),a=n||r;async function c(){const d=o.value.trim();if(!d||a)return;const u=t&&e?{sessionId:t,visitorId:e}:await i();u&&(ba(),o.value="",l({sessionId:u.sessionId,visitorId:u.visitorId,content:d}).catch(p=>{console.error("[jexity] Failed to send message:",p)}))}return h("div",{class:"jex-chat-input",children:[h("input",{type:"text","aria-label":s.inputPlaceholder,placeholder:r?s.aiThinking:s.inputPlaceholder,value:o.value,onInput:d=>{o.value=d.currentTarget.value},onKeyDown:d=>{d.key==="Enter"&&c()},disabled:a}),h("button",{class:"jex-send-btn",onClick:c,"aria-label":s.sendAriaLabel,disabled:a,children:h(kl,{size:18})})]})}function Ai({message:t}){return h("div",{class:"jex-overlay jex-loading",children:[h("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&h("p",{class:"jex-loading-message",children:t})]})}function jl({greeting:t,orgSlug:e}){const n=ne(),{sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,ensureSession:l}=Aa(e),a=Vo(un.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),c=r!==null&&a===void 0,d=a?.some(u=>u.status==="streaming")??!1;return N(()=>{fe.value&&!r&&l()},[l,r]),s||c&&fe.value?h(Ai,{message:n.resumeConversation}):h(M,{children:[h(wl,{conversations:a,greeting:t,sessionNotFound:o}),h(Sl,{sessionId:r,visitorId:i,isLoading:s,isStreaming:d,ensureSession:l})]})}function Cl(){const t=ne(),[e,n]=O(""),[r,i]=O(""),[s,o]=O("");async function l(a){a.preventDefault(),ln({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const c="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();ln({id:"confirmation",ref:c})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Rl({ticketRef:t}){const e=ne();return h("div",{class:"jex-confirmation",children:[h("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),h("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),h("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),h("div",{class:"jex-confirmation-ref",children:t}),h("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),h("button",{class:"jex-confirmation-done",onClick:()=>{$.value=!1},children:e.done})]})}function Tl({message:t,onRetry:e,onBack:n}){return h("div",{class:"jex-overlay jex-error",children:[h("p",{class:"jex-error-message",children:t}),h("div",{class:"jex-error-actions",children:[e&&h("button",{class:"jex-error-retry",onClick:e,children:"Try again"}),n&&h("button",{class:"jex-error-back",onClick:n,children:"Go back"})]})]})}function Ii({greeting:t,title:e,orgSlug:n}){const r=B.value,i=r[r.length-1],s=r.findLast(o=>o.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h(Ra,{greeting:t,title:e}),i.id==="selection"&&h(Ta,{title:e}),i.id==="form"&&h(Cl,{}),i.id==="confirmation"&&s&&h(Rl,{ticketRef:s.ref}),i.id==="chat"&&h(jl,{greeting:t,orgSlug:n}),i.id==="loading"&&h(Ai,{message:i.message}),i.id==="error"&&h(Tl,{message:i.message,onRetry:()=>ln({id:"loading"}),onBack:ci})]})}function $l({options:t}){const e=ca(t.orgSlug,t.convexUrl);ga(t.parentOrigin),N(()=>{xa()},[]);const n=aa(t,e);N(()=>{sn.value=ai(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",s=_a({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight}),o=n.mode==="embedded";return h("div",{class:`jex-widget ${i}`.trim(),style:s,children:o?h("div",{class:"jex-embedded",children:[h(ui,{title:n.title}),h(Ii,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(hi,{})]}):h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[$.value&&h("div",{class:"jex-chat-window",children:[h(ui,{title:n.title}),h(Ii,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(hi,{})]}),h(Ca,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Al='.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}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) 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-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-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{display:block;font-size:10px;color:var(--jex-text-muted);margin-top:2px;padding-left:4px}.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:16px;border-top:1px solid var(--jex-border-window);display:flex;gap:8px;flex-shrink:0}.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:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s cubic-bezier(.175,.885,.32,1.275);flex-shrink:0}.jex-send-btn:hover{transform:scale(1.05);background:var(--jex-primary-hover)}.jex-send-btn:active{transform:scale(.95)}.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}.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-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:13px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}.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}';function Il(t){const e=document.createElement("style");e.textContent=Al,t.appendChild(e)}const El="https://festive-mouse-978.eu-west-1.convex.cloud";let vn=null;function ql(t){const e=t??El;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 vn||(vn=new Fo(sa(e))),vn}function Pl(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Il(n),mt.value=e.source,e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),$.value=!0,B.value=[{id:"home"}]);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),ce(h(Do,{client:ql(e.convexUrl),children:h($l,{options:e})}),r),function(){ce(null,r),$.value=!1,mt.value=void 0,B.value=[{id:"chat"}]}}function Ml(t,e,n){const r=Pl(t,e),i=new Set,s=$.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){$.value=!0},close(){$.value=!1},toggle(){$.value=!$.value},get isOpen(){return $.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let Ke=null;function Ll(t){Ke&&Ke.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=Ml(e,t,()=>{t.container||e.remove(),Ke===n&&(Ke=null)});return Ke=n,n}function xe(t,e){return t.getAttribute(e)??void 0}function Ei(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const n={orgSlug:t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",position:xe(t,"data-position")??void 0,theme:xe(t,"data-theme")??void 0,greeting:xe(t,"data-greeting"),title:xe(t,"data-title"),primaryColor:xe(t,"data-primary-color"),locale:xe(t,"data-locale"),convexUrl:xe(t,"data-convex-url")};window.JexityChat=Ll(n)}document.readyState==="complete"?Ei():window.addEventListener("load",Ei)})();
61
61
  //# sourceMappingURL=widget.js.map