@evelan/jexity-widget 0.4.2-canary.8 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/widget.js +1 -1
- package/dist/widget.js.map +1 -1
- package/package.json +1 -1
package/dist/widget.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
(function(){"use strict";var me,g,Ut,Bt,X,Dt,Wt,zt,Ht,tt,nt,rt,Jt,ye={},Kt=[],Mr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ve=Array.isArray;function P(t,e){for(var n in e)t[n]=e[n];return t}function it(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function U(t,e,n){var r,i,o,s={};for(o in e)o=="key"?r=e[o]:o=="ref"?i=e[o]:s[o]=e[o];if(arguments.length>2&&(s.children=arguments.length>3?me.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return be(t,s,r,i,null)}function be(t,e,n,r,i){var o={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Ut,__i:-1,__u:0};return i==null&&g.vnode!=null&&g.vnode(o),o}function Pr(){return{current:null}}function q(t){return t.children}function I(t,e){this.props=t,this.context=e}function oe(t,e){if(e==null)return t.__?oe(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"?oe(t):null}function Gt(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 Gt(t)}}function ot(t){(!t.__d&&(t.__d=!0)&&X.push(t)&&!Oe.__r++||Dt!=g.debounceRendering)&&((Dt=g.debounceRendering)||Wt)(Oe)}function Oe(){for(var t,e,n,r,i,o,s,a=1;X.length;)X.length>a&&X.sort(zt),t=X.shift(),a=X.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,o=[],s=[],e.__P&&((n=P({},r)).__v=r.__v+1,g.vnode&&g.vnode(n),st(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,o,i??oe(r),!!(32&r.__u),s),n.__v=r.__v,n.__.__k[n.__i]=n,tn(o,n,s),r.__e=r.__=null,n.__e!=i&&Gt(n)));Oe.__r=0}function Xt(t,e,n,r,i,o,s,a,c,u,f){var l,_,d,p,C,w,y,v=r&&r.__k||Kt,K=e.length;for(c=Or(n,e,v,c,K),l=0;l<K;l++)(d=n.__k[l])!=null&&(_=d.__i==-1?ye:v[d.__i]||ye,d.__i=l,w=st(t,d,_,i,o,s,a,c,u,f),p=d.__e,d.ref&&_.ref!=d.ref&&(_.ref&&ct(_.ref,null,d),f.push(d.ref,d.__c||p,d)),C==null&&p!=null&&(C=p),(y=!!(4&d.__u))||_.__k===d.__k?c=Yt(d,c,t,y):typeof d.type=="function"&&w!==void 0?c=w:p&&(c=p.nextSibling),d.__u&=-7);return n.__e=C,c}function Or(t,e,n,r,i){var o,s,a,c,u,f=n.length,l=f,_=0;for(t.__k=new Array(i),o=0;o<i;o++)(s=e[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(c=o+_,(s=t.__k[o]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?be(null,s,null,null,null):ve(s)?be(q,{children:s},null,null,null):s.constructor==null&&s.__b>0?be(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=t,s.__b=t.__b+1,a=null,(u=s.__i=Lr(s,n,c,l))!=-1&&(l--,(a=n[u])&&(a.__u|=2)),a==null||a.__v==null?(u==-1&&(i>f?_--:i<f&&_++),typeof s.type!="function"&&(s.__u|=4)):u!=c&&(u==c-1?_--:u==c+1?_++:(u>c?_--:_++,s.__u|=4))):t.__k[o]=null;if(l)for(o=0;o<f;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=oe(a)),rn(a,a));return r}function Yt(t,e,n,r){var i,o;if(typeof t.type=="function"){for(i=t.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=t,e=Yt(i[o],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=oe(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function B(t,e){return e=e||[],t==null||typeof t=="boolean"||(ve(t)?t.some(function(n){B(n,e)}):e.push(t)),e}function Lr(t,e,n,r){var i,o,s,a=t.key,c=t.type,u=e[n],f=u!=null&&(2&u.__u)==0;if(u===null&&t.key==null||f&&a==u.key&&c==u.type)return n;if(r>(f?1:0)){for(i=n-1,o=n+1;i>=0||o<e.length;)if((u=e[s=i>=0?i--:o++])!=null&&(2&u.__u)==0&&a==u.key&&c==u.type)return s}return-1}function Zt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Mr.test(e)?n:n+"px"}function Le(t,e,n,r,i){var o,s;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof r=="string"&&(t.style.cssText=r=""),r)for(e in r)n&&e in n||Zt(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Zt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Ht,"$1")),s=e.toLowerCase(),e=s in t||e=="onFocusOut"||e=="onFocusIn"?s.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?r?n.u=r.u:(n.u=tt,t.addEventListener(e,o?rt:nt,o)):t.removeEventListener(e,o?rt:nt,o);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function en(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=tt++;else if(e.t<n.u)return;return n(g.event?g.event(e):e)}}}function st(t,e,n,r,i,o,s,a,c,u){var f,l,_,d,p,C,w,y,v,K,G,Ze,Me,Ir,et,Pe,Vt,V=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),o=[a=e.__e=n.__e]),(f=g.__b)&&f(e);e:if(typeof V=="function")try{if(y=e.props,v="prototype"in V&&V.prototype.render,K=(f=V.contextType)&&r[f.__c],G=f?K?K.props.value:f.__:r,n.__c?w=(l=e.__c=n.__c).__=l.__E:(v?e.__c=l=new V(y,G):(e.__c=l=new I(y,G),l.constructor=V,l.render=Qr),K&&K.sub(l),l.props=y,l.state||(l.state={}),l.context=G,l.__n=r,_=l.__d=!0,l.__h=[],l._sb=[]),v&&l.__s==null&&(l.__s=l.state),v&&V.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=P({},l.__s)),P(l.__s,V.getDerivedStateFromProps(y,l.__s))),d=l.props,p=l.state,l.__v=e,_)v&&V.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),v&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(v&&V.getDerivedStateFromProps==null&&y!==d&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(y,G),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(y,l.__s,G)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(l.props=y,l.state=l.__s,l.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(_e){_e&&(_e.__=e)}),Ze=0;Ze<l._sb.length;Ze++)l.__h.push(l._sb[Ze]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(y,l.__s,G),v&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(d,p,C)})}if(l.context=G,l.props=y,l.__P=t,l.__e=!1,Me=g.__r,Ir=0,v){for(l.state=l.__s,l.__d=!1,Me&&Me(e),f=l.render(l.props,l.state,l.context),et=0;et<l._sb.length;et++)l.__h.push(l._sb[et]);l._sb=[]}else do l.__d=!1,Me&&Me(e),f=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++Ir<25);l.state=l.__s,l.getChildContext!=null&&(r=P(P({},r),l.getChildContext())),v&&!_&&l.getSnapshotBeforeUpdate!=null&&(C=l.getSnapshotBeforeUpdate(d,p)),Pe=f,f!=null&&f.type===q&&f.key==null&&(Pe=nn(f.props.children)),a=Xt(t,ve(Pe)?Pe:[Pe],e,n,r,i,o,s,a,c,u),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),w&&(l.__E=l.__=null)}catch(_e){if(e.__v=null,c||o!=null)if(_e.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else{for(Vt=o.length;Vt--;)it(o[Vt]);at(e)}else e.__e=n.__e,e.__k=n.__k,_e.then||at(e);g.__e(_e,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Nr(n.__e,e,n,r,i,o,s,c,u);return(f=g.diffed)&&f(e),128&e.__u?void 0:a}function at(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(at)}function tn(t,e,n){for(var r=0;r<n.length;r++)ct(n[r],n[++r],n[++r]);g.__c&&g.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(o){o.call(i)})}catch(o){g.__e(o,i.__v)}})}function nn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:ve(t)?t.map(nn):P({},t)}function Nr(t,e,n,r,i,o,s,a,c){var u,f,l,_,d,p,C,w=n.props,y=e.props,v=e.type;if(v=="svg"?i="http://www.w3.org/2000/svg":v=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(u=0;u<o.length;u++)if((d=o[u])&&"setAttribute"in d==!!v&&(v?d.localName==v:d.nodeType==3)){t=d,o[u]=null;break}}if(t==null){if(v==null)return document.createTextNode(y);t=document.createElementNS(i,v,y.is&&y),a&&(g.__m&&g.__m(e,o),a=!1),o=null}if(v==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&me.call(t.childNodes),w=n.props||ye,!a&&o!=null)for(w={},u=0;u<t.attributes.length;u++)w[(d=t.attributes[u]).name]=d.value;for(u in w)if(d=w[u],u!="children"){if(u=="dangerouslySetInnerHTML")l=d;else if(!(u in y)){if(u=="value"&&"defaultValue"in y||u=="checked"&&"defaultChecked"in y)continue;Le(t,u,null,d,i)}}for(u in y)d=y[u],u=="children"?_=d:u=="dangerouslySetInnerHTML"?f=d:u=="value"?p=d:u=="checked"?C=d:a&&typeof d!="function"||w[u]===d||Le(t,u,d,w[u],i);if(f)a||l&&(f.__html==l.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(l&&(t.innerHTML=""),Xt(e.type=="template"?t.content:t,ve(_)?_:[_],e,n,r,v=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&oe(n,0),a,c),o!=null)for(u=o.length;u--;)it(o[u]);a||(u="value",v=="progress"&&p==null?t.removeAttribute("value"):p!=null&&(p!==t[u]||v=="progress"&&!p||v=="option"&&p!=w[u])&&Le(t,u,p,w[u],i),u="checked",C!=null&&C!=t[u]&&Le(t,u,C,w[u],i))}return t}function ct(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){g.__e(i,n)}}function rn(t,e,n){var r,i;if(g.unmount&&g.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||ct(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){g.__e(o,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&rn(r[i],e,n||typeof t.type!="function");n||it(t.__e),t.__c=t.__=t.__e=void 0}function Qr(t,e,n){return this.constructor(t,n)}function Y(t,e,n){var r,i,o,s;e==document&&(e=document.documentElement),g.__&&g.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,o=[],s=[],st(e,t=(!r&&n||e).__k=U(q,null,[t]),i||ye,ye,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?me.call(e.childNodes):null,o,!r&&n?n:i?i.__e:e.firstChild,r,s),tn(o,t,s)}function on(t,e){Y(t,e,on)}function Fr(t,e,n){var r,i,o,s,a=P({},t.props);for(o in t.type&&t.type.defaultProps&&(s=t.type.defaultProps),e)o=="key"?r=e[o]:o=="ref"?i=e[o]:a[o]=e[o]===void 0&&s!=null?s[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?me.call(arguments,2):n),be(t.type,a,r||t.key,i||t.ref,null)}function Vr(t){function e(n){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&r.forEach(function(s){s.__e=!0,ot(s)})},this.sub=function(o){r.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){r&&r.delete(o),s&&s.call(o)}}),n.children}return e.__c="__cC"+Jt++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}me=Kt.slice,g={__e:function(t,e,n,r){for(var i,o,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(t)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),s=i.__d),s)return i.__E=i}catch(a){t=a}throw t}},Ut=0,Bt=function(t){return t!=null&&t.constructor==null},I.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=P({},this.state),typeof t=="function"&&(t=t(P({},n),this.props)),t&&P(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),ot(this))},I.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ot(this))},I.prototype.render=q,X=[],Wt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,zt=function(t,e){return t.__v.__b-e.__v.__b},Oe.__r=0,Ht=/(PointerCapture)$|Capture$/i,tt=0,nt=en(!1),rt=en(!0),Jt=0;var Ur=0;function h(t,e,n,r,i,o){e||(e={});var s,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?s=e[a]:c[a]=e[a];var u={type:t,props:c,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ur,__i:-1,__u:0,__source:i,__self:o};if(typeof t=="function"&&(s=t.defaultProps))for(a in s)c[a]===void 0&&(c[a]=s[a]);return g.vnode&&g.vnode(u),u}var H,b,ut,sn,se=0,an=[],x=g,cn=x.__b,un=x.__r,ln=x.diffed,hn=x.__c,dn=x.unmount,fn=x.__;function ae(t,e){x.__h&&x.__h(b,t,se||e),se=0;var n=b.__H||(b.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function M(t){return se=1,lt(yn,t)}function lt(t,e,n){var r=ae(H++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):yn(void 0,e),function(a){var c=r.__N?r.__N[0]:r.__[0],u=r.t(c,a);c!==u&&(r.__N=[u,r.__[1]],r.__c.setState({}))}],r.__c=b,!b.__f)){var i=function(a,c,u){if(!r.__c.__H)return!0;var f=r.__c.__H.__.filter(function(_){return!!_.__c});if(f.every(function(_){return!_.__N}))return!o||o.call(this,a,c,u);var l=r.__c.props!==a;return f.forEach(function(_){if(_.__N){var d=_.__[0];_.__=_.__N,_.__N=void 0,d!==_.__[0]&&(l=!0)}}),o&&o.call(this,a,c,u)||l};b.__f=!0;var o=b.shouldComponentUpdate,s=b.componentWillUpdate;b.componentWillUpdate=function(a,c,u){if(this.__e){var f=o;o=void 0,i(a,c,u),o=f}s&&s.call(this,a,c,u)},b.shouldComponentUpdate=i}return r.__N||r.__}function O(t,e){var n=ae(H++,3);!x.__s&&ft(n.__H,e)&&(n.__=t,n.u=e,b.__H.__h.push(n))}function xe(t,e){var n=ae(H++,4);!x.__s&&ft(n.__H,e)&&(n.__=t,n.u=e,b.__h.push(n))}function Ne(t){return se=5,L(function(){return{current:t}},[])}function pn(t,e,n){se=6,xe(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 L(t,e){var n=ae(H++,7);return ft(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ht(t,e){return se=8,L(function(){return t},e)}function Qe(t){var e=b.context[t.__c],n=ae(H++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(b)),e.props.value):t.__}function gn(t,e){x.useDebugValue&&x.useDebugValue(e?e(t):t)}function _n(){var t=ae(H++,11);if(!t.__){for(var e=b.__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 Br(){for(var t;t=an.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Fe),t.__H.__h.forEach(dt),t.__H.__h=[]}catch(e){t.__H.__h=[],x.__e(e,t.__v)}}x.__b=function(t){b=null,cn&&cn(t)},x.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),fn&&fn(t,e)},x.__r=function(t){un&&un(t),H=0;var e=(b=t.__c).__H;e&&(ut===b?(e.__h=[],b.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Fe),e.__h.forEach(dt),e.__h=[],H=0)),ut=b},x.diffed=function(t){ln&&ln(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(an.push(e)!==1&&sn===x.requestAnimationFrame||((sn=x.requestAnimationFrame)||Dr)(Br)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ut=b=null},x.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Fe),n.__h=n.__h.filter(function(r){return!r.__||dt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],x.__e(r,n.__v)}}),hn&&hn(t,e)},x.unmount=function(t){dn&&dn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{Fe(r)}catch(i){e=i}}),n.__H=void 0,e&&x.__e(e,n.__v))};var mn=typeof requestAnimationFrame=="function";function Dr(t){var e,n=function(){clearTimeout(r),mn&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);mn&&(e=requestAnimationFrame(n))}function Fe(t){var e=b,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),b=e}function dt(t){var e=b;t.__c=t.__(),b=e}function ft(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function yn(t,e){return typeof e=="function"?e(t):e}function vn(t,e){for(var n in e)t[n]=e[n];return t}function pt(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 bn(t,e){var n=e(),r=M({t:{__:n,u:e}}),i=r[0].t,o=r[1];return xe(function(){i.__=n,i.u=e,gt(i)&&o({t:i})},[t,n,e]),O(function(){return gt(i)&&o({t:i}),t(function(){gt(i)&&o({t:i})})},[t]),n}function gt(t){var e,n,r=t.u,i=t.__;try{var o=r();return!((e=i)===(n=o)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function xn(t){t()}function wn(t){return t}function kn(){return[!1,xn]}var Sn=xe;function _t(t,e){this.props=t,this.context=e}function Wr(t,e){function n(i){var o=this.props.ref,s=o==i.ref;return!s&&o&&(o.call?o(null):o.current=null),e?!e(this.props,i)||!s:pt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,U(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(_t.prototype=new I).isPureReactComponent=!0,_t.prototype.shouldComponentUpdate=function(t,e){return pt(this.props,t)||pt(this.state,e)};var Cn=g.__b;g.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Cn&&Cn(t)};var zr=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Hr(t){function e(n){var r=vn({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=zr,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var jn=function(t,e){return t==null?null:B(B(t).map(e))},Jr={map:jn,forEach:jn,count:function(t){return t?B(t).length:0},only:function(t){var e=B(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:B},Kr=g.__e;g.__e=function(t,e,n,r){if(t.then){for(var i,o=e;o=o.__;)if((i=o.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}Kr(t,e,n,r)};var Tn=g.unmount;function Rn(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=vn({},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 Rn(r,e,n)})),t}function An(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return An(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 Ve(){this.__u=0,this.o=null,this.__b=null}function $n(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Gr(t){var e,n,r;function i(o){if(e||(e=t()).then(function(s){n=s.default||s},function(s){r=s}),r)throw r;if(!n)throw e;return U(n,o)}return i.displayName="Lazy",i.__f=!0,i}function we(){this.i=null,this.l=null}g.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Tn&&Tn(t)},(Ve.prototype=new I).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=$n(r.__v),o=!1,s=function(){o||(o=!0,n.__R=null,i?i(a):a())};n.__R=s;var a=function(){if(!--r.__u){if(r.state.__a){var c=r.state.__a;r.__v.__k[0]=An(c,c.__c.__P,c.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(s,s)},Ve.prototype.componentWillUnmount=function(){this.o=[]},Ve.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]=Rn(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&U(q,null,t.fallback);return i&&(i.__u&=-33),[U(q,null,e.__a?null:t.children),i]};var En=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 Xr(t){return this.getChildContext=function(){return t.context},t.children}function Yr(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){Y(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var r=e.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},insertBefore:function(i,o){this.childNodes.push(i),e.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}Y(U(Xr,{context:e.context},t.__v),e.v)}function Zr(t,e){var n=U(Yr,{__v:t,h:e});return n.containerInfo=e,n}(we.prototype=new I).__a=function(t){var e=this,n=$n(e.__v),r=e.l.get(t);return r[0]++,function(i){var o=function(){e.props.revealOrder?(r.push(i),En(e,t,r)):i()};n?n(o):o()}},we.prototype.render=function(t){this.i=null,this.l=new Map;var e=B(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},we.prototype.componentDidUpdate=we.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){En(t,n,e)})};var qn=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,ei=/^(?: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]/,ti=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ni=/[A-Z0-9]/g,ri=typeof document<"u",ii=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function oi(t,e,n){return e.__k==null&&(e.textContent=""),Y(t,e),typeof n=="function"&&n(),t?t.__c:null}function si(t,e,n){return on(t,e),typeof n=="function"&&n(),t?t.__c:null}I.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(I.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var In=g.event;function ai(){}function ci(){return this.cancelBubble}function ui(){return this.defaultPrevented}g.event=function(t){return In&&(t=In(t)),t.persist=ai,t.isPropagationStopped=ci,t.isDefaultPrevented=ui,t.nativeEvent=t};var mt,li={enumerable:!1,configurable:!0,get:function(){return this.class}},Mn=g.vnode;g.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},o=r.indexOf("-")===-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||ri&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||ii(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":ti.test(s)&&(s=c):c=s="oninput":o&&ei.test(s)?s=s.replace(ni,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&i[s=c]&&(s="oninputCapture"),i[s]=a}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=B(n.children).forEach(function(u){u.props.selected=i.value.indexOf(u.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=B(n.children).forEach(function(u){u.props.selected=i.multiple?i.defaultValue.indexOf(u.props.value)!=-1:i.defaultValue==u.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",li)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=qn,Mn&&Mn(t)};var Pn=g.__r;g.__r=function(t){Pn&&Pn(t),mt=t.__c};var On=g.diffed;g.diffed=function(t){On&&On(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),mt=null};var hi={ReactCurrentDispatcher:{current:{readContext:function(t){return mt.__n[t.__c].props.value},useCallback:ht,useContext:Qe,useDebugValue:gn,useDeferredValue:wn,useEffect:O,useId:_n,useImperativeHandle:pn,useInsertionEffect:Sn,useLayoutEffect:xe,useMemo:L,useReducer:lt,useRef:Ne,useState:M,useSyncExternalStore:bn,useTransition:kn}}};function di(t){return U.bind(null,t)}function Ue(t){return!!t&&t.$$typeof===qn}function fi(t){return Ue(t)&&t.type===q}function pi(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function gi(t){return Ue(t)?Fr.apply(null,arguments):t}function _i(t){return!!t.__k&&(Y(null,t),!0)}function mi(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var yi=function(t,e){return t(e)},vi=function(t,e){return t(e)},bi=q,xi=Ue,yt={useState:M,useId:_n,useReducer:lt,useEffect:O,useLayoutEffect:xe,useInsertionEffect:Sn,useTransition:kn,useDeferredValue:wn,useSyncExternalStore:bn,startTransition:xn,useRef:Ne,useImperativeHandle:pn,useMemo:L,useCallback:ht,useContext:Qe,useDebugValue:gn,version:"18.3.1",Children:Jr,render:oi,hydrate:si,unmountComponentAtNode:_i,createPortal:Zr,createElement:U,createContext:Vr,createFactory:di,cloneElement:gi,createRef:Pr,Fragment:q,isValidElement:Ue,isElement:xi,isFragment:fi,isMemo:pi,findDOMNode:mi,Component:I,PureComponent:_t,memo:Wr,forwardRef:Hr,flushSync:vi,unstable_batchedUpdates:yi,StrictMode:bi,Suspense:Ve,SuspenseList:we,lazy:Gr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi},N=[],$=[],wi=Uint8Array,vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ce=0,ki=vt.length;ce<ki;++ce)N[ce]=vt[ce],$[vt.charCodeAt(ce)]=ce;$[45]=62,$[95]=63;function Si(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 Ci(t,e,n){return(e+n)*3/4-n}function ke(t){var e,n=Si(t),r=n[0],i=n[1],o=new wi(Ci(t,r,i)),s=0,a=i>0?r-4:r,c;for(c=0;c<a;c+=4)e=$[t.charCodeAt(c)]<<18|$[t.charCodeAt(c+1)]<<12|$[t.charCodeAt(c+2)]<<6|$[t.charCodeAt(c+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=$[t.charCodeAt(c)]<<2|$[t.charCodeAt(c+1)]>>4,o[s++]=e&255),i===1&&(e=$[t.charCodeAt(c)]<<10|$[t.charCodeAt(c+1)]<<4|$[t.charCodeAt(c+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function ji(t){return N[t>>18&63]+N[t>>12&63]+N[t>>6&63]+N[t&63]}function Ti(t,e,n){for(var r,i=[],o=e;o<n;o+=3)r=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(ji(r));return i.join("")}function Se(t){for(var e,n=t.length,r=n%3,i=[],o=16383,s=0,a=n-r;s<a;s+=o)i.push(Ti(t,s,s+o>a?a:s+o));return r===1?(e=t[n-1],i.push(N[e>>2]+N[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(N[e>>10]+N[e>>4&63]+N[e<<2&63]+"=")),i.join("")}function D(t){if(t===void 0)return{};if(!Ln(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function Ri(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 Ln(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const Nn=!0,ue=BigInt("-9223372036854775808"),bt=BigInt("9223372036854775807"),xt=BigInt("0"),Ai=BigInt("8"),$i=BigInt("256");function Qn(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Ei(t){t<xt&&(t-=ue+ue);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>>=Ai;return Se(n)}function qi(t){const e=ke(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=xt,r=xt;for(const i of e)n+=BigInt(i)*$i**r,r++;return n>bt&&(n+=ue+ue),n}function Ii(t){if(t<ue||bt<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),Se(new Uint8Array(e))}function Mi(t){const e=ke(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 Pi=DataView.prototype.setBigInt64?Ii:Ei,Oi=DataView.prototype.getBigInt64?Mi:qi,Fn=1024;function Vn(t){if(t.length>Fn)throw new Error(`Field name ${t} exceeds maximum field name length ${Fn}.`);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 le(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>le(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 ke(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return Oi(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=ke(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,Nn);if(!Qn(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,i]of Object.entries(t))Vn(r),n[r]=le(i);return n}const Un=16384;function Ce(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Un){const n="[...truncated]";let r=Un-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 s=n&&` (present at path ${n} in original object ${Ce(e)})`;throw new Error(`undefined is not a valid Convex value${s}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<ue||bt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Pi(t)}}if(typeof t=="number")if(Qn(t)){const s=new ArrayBuffer(8);return new DataView(s).setFloat64(0,t,Nn),{$float:Se(new Uint8Array(s))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:Se(new Uint8Array(t))};if(Array.isArray(t))return t.map((s,a)=>wt(s,e,n+`[${a}]`));if(t instanceof Set)throw new Error(kt(n,"Set",[...t],e));if(t instanceof Map)throw new Error(kt(n,"Map",[...t],e));if(!Ln(t)){const s=t?.constructor?.name,a=s?`${s} `:"";throw new Error(kt(n,a,t,e))}const i={},o=Object.entries(t);o.sort(([s,a],[c,u])=>s===c?0:s<c?-1:1);for(const[s,a]of o)a!==void 0&&(Vn(s),i[s]=wt(a,e,n+`.${s}`));return i}function kt(t,e,n,r){return t?`${e}${Ce(n)} is not a supported Convex type (present at path ${t} in original object ${Ce(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${Ce(n)} is not a supported Convex type.`}function Q(t){return wt(t,t,"")}var Li=Object.defineProperty,Ni=(t,e,n)=>e in t?Li(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,St=(t,e,n)=>Ni(t,typeof e!="symbol"?e+"":e,n),Bn,Dn;const Qi=Symbol.for("ConvexError");class Ct extends(Dn=Error,Bn=Qi,Dn){constructor(e){super(typeof e=="string"?e:Ce(e)),St(this,"name","ConvexError"),St(this,"data"),St(this,Bn,!0),this.data=e}}const Wn=()=>Array.from({length:4},()=>0);Wn(),Wn();const zn="1.33.0";var Fi=Object.defineProperty,Vi=(t,e,n)=>e in t?Fi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hn=(t,e,n)=>Vi(t,typeof e!="symbol"?e+"":e,n);const Ui="color:rgb(0, 145, 255)";function Jn(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Kn{constructor(e){Hn(this,"_onLogLineFuncs"),Hn(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 Gn(t){const e=new Kn(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 Xn(t){return new Kn(t)}function Be(t,e,n,r,i){const o=Jn(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const s=i.match(/^\[.*?\] /);if(s===null){t.error(`[CONVEX ${o}(${r})] Could not parse console.log`);return}const a=i.slice(1,s[0].length-2),c=i.slice(s[0].length);t.log(`%c[CONVEX ${o}(${r})] [${a}]`,Ui,c)}else t.error(`[CONVEX ${o}(${r})] ${i}`)}function Bi(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function he(t,e,n){return`[CONVEX ${Jn(t)}(${e})] ${n.errorMessage}
|
|
2
|
-
Called by client`}function jt(t,e){return e.data=t.errorData,e}function Z(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 ee(t,e){return JSON.stringify({udfPath:Z(t),args:Q(e)})}function Yn(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:Z(t),args:Q(e),options:Q({initialNumItems:r,id:i})})}var Di=Object.defineProperty,Wi=(t,e,n)=>e in t?Di(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e,n)=>Wi(t,typeof e!="symbol"?e+"":e,n);class zi{constructor(){F(this,"nextQueryId"),F(this,"querySetVersion"),F(this,"querySet"),F(this,"queryIdToToken"),F(this,"identityVersion"),F(this,"auth"),F(this,"outstandingQueriesOlderThanRestart"),F(this,"outstandingAuthOlderThanRestart"),F(this,"paused"),F(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const o=Z(e),s=ee(o,n),a=this.querySet.get(s);if(a!==void 0)return a.numSubscribers+=1,{queryToken:s,modification:null,unsubscribe:()=>this.removeSubscriber(s)};{const c=this.nextQueryId++,u={id:c,canonicalizedUdfPath:o,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(s,u),this.queryIdToToken.set(c,s);const f=this.querySetVersion,l=this.querySetVersion+1,_={type:"Add",queryId:c,udfPath:o,args:[Q(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(c,_):this.querySetVersion=l,{queryToken:s,modification:{type:"ModifyQuerySet",baseVersion:f,newVersion:l,modifications:[_]},unsubscribe:()=>this.removeSubscriber(s)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=Z(e),i=ee(r,n),o=this.querySet.get(i);return o!==void 0?o.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const n=[];for(const o of this.querySet.values()){const s={type:"Add",queryId:o.id,udfPath:o.canonicalizedUdfPath,args:[Q(o.args)],journal:o.journal,componentPath:o.componentPath};n.push(s),e.has(o.id)||this.outstandingQueriesOlderThanRestart.add(o.id)}this.querySetVersion=1;const r={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:n};if(!this.auth)return this.identityVersion=0,[r,void 0];this.outstandingAuthOlderThanRestart=!0;const i={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[r,i]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,o={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,o):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[o]}}}}var Hi=Object.defineProperty,Ji=(t,e,n)=>e in t?Hi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,De=(t,e,n)=>Ji(t,typeof e!="symbol"?e+"":e,n);class Ki{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,De(this,"inflightRequests"),De(this,"requestsOlderThanRestart"),De(this,"inflightMutationsCount",0),De(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const o=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:o,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const c of e.logLines)Be(this.logger,"info",r,i,c);const o=n.status;let s,a;if(e.success)s={success:!0,logLines:e.logLines,value:le(e.result)},a=()=>o.onResult(s);else{const c=e.result,{errorData:u}=e;Be(this.logger,"error",r,i,c),s={success:!1,errorMessage:c,errorData:u!==void 0?le(u):void 0,logLines:e.logLines},a=()=>o.onResult(s)}return e.type==="ActionResponse"||!e.success?(a(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:s}):(n.status={status:"Completed",result:s,ts:e.ts,onResolve:a},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const o=i.status;o.status==="Completed"&&o.ts.lessThanOrEqual(e)&&(o.onResolve(),n.set(r,o.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const je=Symbol.for("functionName"),Zn=Symbol.for("toReferencePath");function Gi(t){return t[Zn]??null}function Xi(t){return t.startsWith("function://")}function Yi(t){let e;if(typeof t=="string")Xi(t)?e={functionHandle:t}:e={name:t};else if(t[je])e={name:t[je]};else{const n=Gi(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function T(t){const e=Yi(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[je];if(!n)throw new Error(`${t} is not a functionReference`);return n}function er(t){return{[je]:t}}function tr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return tr(i)}else if(r===je){if(t.length<2){const s=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${s}\``)}const i=t.slice(0,-1).join("/"),o=t[t.length-1];return o==="default"?i:i+":"+o}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Zi=tr();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,We=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n);class Te{constructor(e){We(this,"queryResults"),We(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=D(n[0]),i=T(e),o=this.queryResults.get(ee(i,r));if(o!==void 0)return Te.queryValue(o.result)}getAllQueries(e){const n=[],r=T(e);for(const i of this.queryResults.values())i.udfPath===Z(r)&&n.push({args:i.args,value:Te.queryValue(i.result)});return n}setQuery(e,n,r){const i=D(n),o=T(e),s=ee(o,i);let a;r===void 0?a=void 0:a={success:!0,value:r,logLines:[]};const c={udfPath:o,args:i,result:a};this.queryResults.set(s,c),this.modifiedQueries.push(s)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class no{constructor(){We(this,"queryResults"),We(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(s=>!n.has(s.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Te(this.queryResults);for(const s of this.optimisticUpdates)s.update(i);const o=[];for(const[s,a]of this.queryResults){const c=r.get(s);(c===void 0||c.result!==a.result)&&o.push(s)}return o}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Te(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?jt(r,new Ct(he("query",n.udfPath,r))):new Error(he("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,Tt=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);class R{constructor(e,n){Tt(this,"low"),Tt(this,"high"),Tt(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 R(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>=oo?so:new R(e%Re|0,e/Re|0)}toString(){return(BigInt(this.high)*BigInt(Re)+BigInt(this.low)).toString()}equals(e){return R.isLong(e)||(e=R.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 R.isLong(e)||(e=R.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"?R.fromNumber(e):new R(e.low,e.high)}}const nr=new R(0,0),rr=65536,Re=rr*rr,oo=Re*Re,so=new R(-1,-1);var ao=Object.defineProperty,co=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ze=(t,e,n)=>co(t,typeof e!="symbol"?e+"":e,n);class ir{constructor(e,n){ze(this,"version"),ze(this,"remoteQuerySet"),ze(this,"queryPath"),ze(this,"logger"),this.version={querySet:0,ts:R.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)Be(this.logger,"info","query",i,s);const o=le(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:o,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)Be(this.logger,"info","query",i,s);const{errorData:o}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:o!==void 0?le(o):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function Rt(t){const e=ke(t);return R.fromBytesLE(Array.from(e))}function uo(t){const e=new Uint8Array(t.toBytesLE());return Se(e)}function or(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:Rt(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:Rt(t.startVersion.ts)},endVersion:{...t.endVersion,ts:Rt(t.endVersion.ts)}}}}function lo(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:uo(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,k=(t,e,n)=>fo(t,typeof e!="symbol"?e+"":e,n);const po=1e3,go=1001,_o=1005,mo=4040;let He;function de(){return He===void 0&&(He=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(He+performance.now())}function sr(){return`t=${Math.round((de()-He)/100)/10}s`}const ar={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(ar))if(t.startsWith(e))return e;return"Unknown"}class vo{constructor(e,n,r,i,o,s){this.markConnectionStateDirty=o,this.debug=s,k(this,"socket"),k(this,"connectionCount"),k(this,"_hasEverConnected",!1),k(this,"lastCloseReason"),k(this,"transitionChunkBuffer",null),k(this,"defaultInitialBackoff"),k(this,"maxBackoff"),k(this,"retries"),k(this,"serverInactivityThreshold"),k(this,"reconnectDueToServerInactivityTimeout"),k(this,"scheduledReconnect",null),k(this,"networkOnlineHandler",null),k(this,"pendingNetworkRecoveryInfo",null),k(this,"uri"),k(this,"onOpen"),k(this,"onResume"),k(this,"onMessage"),k(this,"webSocketConstructor"),k(this,"logger"),k(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=or(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:de()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",sr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",sr())),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=or(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const s=this.assembleTransition(i);if(!s)return;i=s,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==po&&n.code!==go&&n.code!==_o&&n.code!==mo){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=lo(e),i=JSON.stringify(r);let o=!1;try{this.socket.ws.send(i),o=!0}catch(s){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${s}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${o?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=de(),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=de()-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:de()})):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:ar[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),o=i*(Math.random()-.5);return i+o}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=de()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,o=`${Math.round(n/1e4)/100}MB`,s=n/(r/1e3),a=`${Math.round(s/1e4)/100}MB per second`;this._logVerbose(`received ${o} transition in ${i} at ${a}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${o}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${o} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function bo(){return xo()}function xo(){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 Ae extends Error{}Ae.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 cr(t,e){if(typeof t!="string")throw new Ae("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 Ae(`Invalid token specified: missing part #${n+1}`);let i;try{i=ko(r)}catch(o){throw new Ae(`Invalid token specified: invalid base64 for part #${n+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Ae(`Invalid token specified: invalid json for part #${n+1} (${o.message})`)}}var So=Object.defineProperty,Co=(t,e,n)=>e in t?So(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,E=(t,e,n)=>Co(t,typeof e!="symbol"?e+"":e,n);const jo=480*60*60*1e3,ur=2;class To{constructor(e,n,r){E(this,"authState",{state:"noAuth"}),E(this,"configVersion",0),E(this,"syncState"),E(this,"authenticate"),E(this,"stopSocket"),E(this,"tryRestartSocket"),E(this,"pauseSocket"),E(this,"resumeSocket"),E(this,"clearAuth"),E(this,"logger"),E(this,"refreshTokenLeewaySeconds"),E(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.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>=ur){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, ${ur-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const o=i-r;if(o<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let s=Math.min(jo,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);const a=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},s);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:a,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return cr(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 Ro=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Ao(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function $o(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Eo(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of Ro){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map($o)}var qo=Object.defineProperty,Io=(t,e,n)=>e in t?qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,S=(t,e,n)=>Io(t,typeof e!="symbol"?e+"":e,n);class Mo{constructor(e,n,r){if(S(this,"address"),S(this,"state"),S(this,"requestManager"),S(this,"webSocketManager"),S(this,"authenticationManager"),S(this,"remoteQuerySet"),S(this,"optimisticQueryResults"),S(this,"_transitionHandlerCounter",0),S(this,"_nextRequestId"),S(this,"_onTransitionFns",new Map),S(this,"_sessionId"),S(this,"firstMessageReceived",!1),S(this,"debug"),S(this,"logger"),S(this,"maxObservedTimestamp"),S(this,"connectionStateSubscribers",new Map),S(this,"nextConnectionStateSubscriberId",0),S(this,"_lastPublishedConnectionState"),S(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const d=this.connectionState();if(JSON.stringify(d)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=d;for(const p of this.connectionStateSubscribers.values())p(d)}})}),S(this,"mark",d=>{this.debug&&Ao(d,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&&Ri(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let o=r.webSocketConstructor;if(!o&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");o=o||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Xn({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Gn({verbose:r.verbose??!1});const s=e.search("://");if(s===-1)throw new Error("Provided address was not an absolute URL.");const a=e.substring(s+3),c=e.substring(0,s);let u;if(c==="http")u="ws";else if(c==="https")u="wss";else throw new Error(`Unknown parent protocol ${c}`);const f=`${u}://${a}/api/${zn}/sync`;this.state=new zi,this.remoteQuerySet=new ir(d=>this.state.queryPath(d),this.logger),this.requestManager=new Ki(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new To(this.state,{authenticate:d=>{const p=this.state.setAuth(d);return this.webSocketManager.sendMessage(p),p.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new no,this.addOnTransitionHandler(d=>{n(d.queries.map(p=>p.token))}),this._nextRequestId=0,this._sessionId=bo();const{unsavedChangesWarning:_}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(_===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else _!==!1&&window.addEventListener("beforeunload",d=>{if(this.requestManager.hasIncompleteRequests()){d.preventDefault();const p="Are you sure you want to leave? Your changes may not be saved.";return(d||window.event).returnValue=p,p}});this.webSocketManager=new vo(f,{onOpen:d=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...d,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const p=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new ir(y=>this.state.queryPath(y),this.logger);const[C,w]=this.state.restart(p);w&&this.webSocketManager.sendMessage(w),this.webSocketManager.sendMessage(C);for(const y of this.requestManager.restart())this.webSocketManager.sendMessage(y)},onResume:()=>{const[d,p]=this.state.resume();p&&this.webSocketManager.sendMessage(p),d&&this.webSocketManager.sendMessage(d);for(const C of this.requestManager.resume())this.webSocketManager.sendMessage(C)},onMessage:d=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),d.type){case"Transition":{this.observedTimestamp(d.endVersion.ts),this.authenticationManager.onTransition(d),this.remoteQuerySet.transition(d),this.state.transition(d);const p=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(p);break}case"MutationResponse":{d.success&&this.observedTimestamp(d.ts);const p=this.requestManager.onResponse(d);p!==null&&this.notifyOnQueryResultChanges(new Map([[p.requestId,p.result]]));break}case"ActionResponse":{this.requestManager.onResponse(d);break}case"AuthError":{this.authenticationManager.onAuthError(d);break}case"FatalError":{const p=Bi(this.logger,d.error);throw this.webSocketManager.terminate(),p}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},o,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&l()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[o,s]of n){const a=this.state.queryToken(o);if(a!==null){const c={result:s,udfPath:this.state.queryPath(o),args:this.state.queryArgs(o)};r.set(a,c)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(o=>{const s=this.optimisticQueryResults.rawQueryResult(o);return{token:o,modification:{kind:"Updated",result:s}}}),reflectedMutations:Array.from(e).map(([o,s])=>({requestId:o,result:s})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?cr(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=D(n),{modification:o,queryToken:s,unsubscribe:a}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return o!==null&&this.webSocketManager.sendMessage(o),{queryToken:s,unsubscribe:()=>{const c=a();c&&this.webSocketManager.sendMessage(c)}}}localQueryResult(e,n){const r=D(n),i=ee(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=D(n),i=ee(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=D(n),i=ee(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?jt(i,new Ct(he("mutation",e,i))):new Error(he("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:o}=this.enqueueMutation(e,n,r,i);return o}enqueueMutation(e,n,r,i){const o=D(n);this.tryReportLongDisconnect();const s=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const f=r.optimisticUpdate;if(f!==void 0){const l=p=>{f(p,o)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},d=this.optimisticQueryResults.applyOptimisticUpdate(l,s).map(p=>{const C=this.localQueryResultByToken(p);return{token:p,modification:{kind:"Updated",result:C===void 0?void 0:{success:!0,value:C,logLines:[]}}}});this.handleTransition({queries:d,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const a={type:"Mutation",requestId:s,udfPath:e,componentPath:i,args:[Q(o)]},c=this.webSocketManager.sendMessage(a),u=this.requestManager.request(a,c);return{requestId:s,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?jt(r,new Ct(he("action",e,r))):new Error(he("action",e,r));return r.value}async actionInternal(e,n,r){const i=D(n),o=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const s={type:"Action",requestId:o,udfPath:e,componentPath:r,args:[Q(i)]},a=this.webSocketManager.sendMessage(s);return this.requestManager.request(s,a)}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=Eo(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-${zn}`},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 At(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 Po=Object.defineProperty,Oo=(t,e,n)=>e in t?Po(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lr=(t,e,n)=>Oo(t,typeof e!="symbol"?e+"":e,n);class Lo{constructor(e,n){this.client=e,this.onTransition=n,lr(this,"paginatedQuerySet",new Map),lr(this,"lastTransitionTs"),this.lastTransitionTs=R.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=Z(e),o=Yn(i,n,r),s=()=>this.removePaginatedQuerySubscriber(o),a=this.paginatedQuerySet.get(o);return a?(a.numSubscribers+=1,{paginatedQueryToken:o,unsubscribe:s}):(this.paginatedQuerySet.set(o,{token:o,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(o,null,r.initialNumItems),{paginatedQueryToken:o,unsubscribe:s})}localQueryResult(e,n,r){const i=Z(e),o=Yn(i,n,r);return this.localQueryResultByToken(o)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:c=>this.loadMoreOfPaginatedQuery(e,c)};let i=[],o=!1,s=!1;for(const c of r){const u=this.client.localQueryResultByToken(c);if(u===void 0){o=!0,s=!1;continue}const f=At(u);i=i.concat(f.page),s=!!f.isDone}let a;return o?a=i.length===0?"LoadingFirstPage":"LoadingMore":s?a="Exhausted":a="CanLoadMore",{results:i,status:a,loadMore:c=>this.loadMoreOfPaginatedQuery(e,c)}}onBaseTransition(e){const n=e.queries.map(s=>s.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,s=>this.client.localQueryResultByToken(s)),i=r.map(s=>({token:s,modification:{kind:"Updated",result:this.localQueryResultByToken(s)}})));const o={...e,paginatedQueries:i};this.onTransition(o)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const o=At(i);if(o.isDone)return!1;this.addPageToPaginatedQuery(e,o.continueCursor,n);const s={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(s),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,o]of this.paginatedQuerySet)for(const s of this.allQueryTokens(o))if(r.has(s)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:o,pageKeyToQuery:s,pageKeys:a}=i;for(const[c,[u,f]]of o)n(s.get(u).queryToken)!==void 0&&n(s.get(f).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,c,u,f);for(const c of a){if(o.has(c))continue;const u=s.get(c).queryToken,f=n(u);if(!f)continue;const l=At(f);l.splitCursor&&(l.pageStatus==="SplitRecommended"||l.pageStatus==="SplitRequired"||l.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,c,l.splitCursor,l.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const o=e.nextPageKey++,s=e.nextPageKey++,a={cursor:i,numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:null,endCursor:r}});e.pageKeyToQuery.set(o,c);const u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:r,endCursor:i}});e.pageKeyToQuery.set(s,u),e.ongoingSplits.set(n,[o,s])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),o=i.nextPageKey++,s={cursor:n,numItems:r,id:i.id},a={...i.args,paginationOpts:s},c=this.client.subscribe(i.canonicalizedUdfPath,a);return i.pageKeys.push(o),i.pageKeyToQuery.set(o,c),c}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const o=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const s=e.pageKeys.indexOf(n);e.pageKeys.splice(s,1,r,i),e.ongoingSplits.delete(n),o.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function No({getCurrentValue:t,subscribe:e}){const[n,r]=M(()=>({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})),O(()=>{let o=!1;const s=()=>{o||r(c=>{if(c.getCurrentValue!==t||c.subscribe!==e)return c;const u=t();return c.value===u?c:{...c,value:u}})},a=e(s);return s(),()=>{o=!0,a()}},[t,e]),i}var Qo=Object.defineProperty,Fo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,W=(t,e,n)=>Fo(t,typeof e!="symbol"?e+"":e,n);const Vo=5e3;if(typeof yt>"u")throw new Error("Required dependency 'react' not found");function hr(t,e,n){function r(i){return zo(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(o){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${T(t)}`);return hr(t,e,o)},r}class Uo{constructor(e,n){if(W(this,"address"),W(this,"cachedSync"),W(this,"cachedPaginatedQueryClient"),W(this,"listeners"),W(this,"options"),W(this,"closed",!1),W(this,"_logger"),W(this,"adminAuth"),W(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?Xn({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Gn({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 Mo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new Lo(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,o=T(e);return{onUpdate:s=>{const{queryToken:a,unsubscribe:c}=this.sync.subscribe(o,r,i),u=this.listeners.get(a);return u!==void 0?u.add(s):this.listeners.set(a,new Set([s])),()=>{if(this.closed)return;const f=this.listeners.get(a);f.delete(s),f.size===0&&this.listeners.delete(a),c()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(o,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(o,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(o,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??Vo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=T(e);return{onUpdate:o=>{const{paginatedQueryToken:s,unsubscribe:a}=this.paginatedQueryClient.subscribe(i,n||{},r),c=this.listeners.get(s);return c!==void 0?c.add(o):this.listeners.set(s,new Set([o])),()=>{if(this.closed)return;const u=this.listeners.get(s);u.delete(o),u.size===0&&this.listeners.delete(s),a()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,o=T(e);return this.sync.mutation(o,r,i)}action(e,...n){const r=T(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((o,s)=>{const a=r.onUpdate(()=>{a();try{o(r.localQueryResult())}catch(c){s(c)}})})}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 $t=yt.createContext(void 0);function Bo(){return Qe($t)}const Do=({client:t,children:e})=>yt.createElement($t.Provider,{value:t},e);function Wo(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:D(e[0]),i=typeof t=="string"?er(t):t,o=T(i),s=L(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(Q(r)),o,n]),c=Go(s).query;if(c instanceof Error)throw c;return c}function dr(t){const e=typeof t=="string"?er(t):t,n=Qe($t);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 L(()=>hr(e,n),[n,T(e)])}function zo(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,Jo=(t,e,n)=>e in t?Ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Et=(t,e,n)=>Jo(t,typeof e!="symbol"?e+"":e,n);class Ko{constructor(e){Et(this,"createWatch"),Et(this,"queries"),Et(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:o}=e[n];if(T(r),this.queries[n]===void 0)this.addQuery(n,r,i,o?{paginationOptions:o}:{});else{const s=this.queries[n];(T(r)!==T(s.query)||JSON.stringify(Q(i))!==JSON.stringify(Q(s.args))||JSON.stringify(o)!==JSON.stringify(s.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,o?{paginationOptions:o}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:o}=e[r],s=e[r].paginationOptions;T(i);const a=this.createWatch(i,o,s?{paginationOptions:s}:{});let c;try{c=a.localQueryResult()}catch(u){if(u instanceof Error)c=u;else throw u}n[r]=c}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:o,paginationOptions:s}=this.queries[n],a="journal"in o?o.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...a?{journal:a}:[],...s?{paginationOptions:s}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:o}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const s=this.createWatch(n,r,{...o?{journal:o}:[],...i?{paginationOptions:i}:{}}),a=s.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:s,unsubscribe:a,...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 Go(t){const e=Bo();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=L(()=>(r,i,{journal:o,paginationOptions:s})=>s?e.watchPaginatedQuery(r,i,s):e.watchQuery(r,i,o?{journal:o}:{}),[e]);return Xo(t,n)}function Xo(t,e){const[n]=M(()=>new Ko(e));n.createWatch!==e&&n.setCreateWatch(e),O(()=>()=>n.destroy(),[n]);const r=L(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return No(r)}var Yo=Symbol.for("preact-signals");function Je(){if(J>1)J--;else{for(var t,e=!1;$e!==void 0;){var n=$e;for($e=void 0,qt++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&gr(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(qt=0,J--,e)throw t}}function Zo(t){if(J>0)return t();J++;try{return t()}finally{Je()}}var m=void 0;function fr(t){var e=m;m=void 0;try{return t()}finally{m=e}}var $e=void 0,J=0,qt=0,Ke=0;function pr(t){if(m!==void 0){var e=t.n;if(e===void 0||e.t!==m)return e={i:0,S:t,p:m.s,n:void 0,t:m,e:void 0,x:void 0,r:e},m.s!==void 0&&(m.s.n=e),m.s=e,t.n=e,32&m.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=m.s,e.n=void 0,m.s.n=e,m.s=e),e}}function j(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}j.prototype.brand=Yo,j.prototype.h=function(){return!0},j.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:fr(function(){var r;(r=e.W)==null||r.call(e)}))},j.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&&fr(function(){var i;(i=e.Z)==null||i.call(e)}))}},j.prototype.subscribe=function(t){var e=this;return Ee(function(){var n=e.value,r=m;m=void 0;try{t(n)}finally{m=r}},{name:"sub"})},j.prototype.valueOf=function(){return this.value},j.prototype.toString=function(){return this.value+""},j.prototype.toJSON=function(){return this.value},j.prototype.peek=function(){var t=m;m=void 0;try{return this.value}finally{m=t}},Object.defineProperty(j.prototype,"value",{get:function(){var t=pr(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(qt>100)throw new Error("Cycle detected");this.v=t,this.i++,Ke++,J++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function te(t,e){return new j(t,e)}function gr(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 _r(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 mr(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 ne(t,e){j.call(this,void 0),this.x=t,this.s=void 0,this.g=Ke-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ne.prototype=new j,ne.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ke))return!0;if(this.g=Ke,this.f|=1,this.i>0&&!gr(this))return this.f&=-2,!0;var t=m;try{_r(this),m=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 m=t,mr(this),this.f&=-2,!0},ne.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)}j.prototype.S.call(this,t)},ne.prototype.U=function(t){if(this.t!==void 0&&(j.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)}},ne.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(ne.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=pr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function yr(t,e){return new ne(t,e)}function vr(t){var e=t.u;if(t.u=void 0,typeof e=="function"){J++;var n=m;m=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,It(t),r}finally{m=n,Je()}}}function It(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,vr(t)}function es(t){if(m!==this)throw new Error("Out-of-order effect");mr(this),m=t,this.f&=-2,8&this.f&&It(this),Je()}function fe(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}fe.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()}},fe.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,vr(this),_r(this),J++;var t=m;return m=this,es.bind(this,t)},fe.prototype.N=function(){2&this.f||(this.f|=2,this.o=$e,$e=this)},fe.prototype.d=function(){this.f|=8,1&this.f||It(this)},fe.prototype.dispose=function(){this.d()};function Ee(t,e){var n=new fe(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var br,Ge,ts=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,xr=[];Ee(function(){br=this.N})();function pe(t,e){g[t]=e.bind(null,g[t]||function(){})}function Xe(t){if(Ge){var e=Ge;Ge=void 0,e()}Ge=t&&t.S()}function wr(t){var e=this,n=t.data,r=Mt(n);r.value=n;var i=L(function(){for(var a=e,c=e.__v;c=c.__;)if(c.__c){c.__c.__$f|=4;break}var u=yr(function(){var d=r.value.value;return d===0?0:d===!0?"":d||""}),f=yr(function(){return!Array.isArray(u.value)&&!Bt(u.value)}),l=Ee(function(){if(this.N=kr,f.value){var d=u.value;a.__v&&a.__v.__e&&a.__v.__e.nodeType===3&&(a.__v.__e.data=d)}}),_=e.__$u.d;return e.__$u.d=function(){l(),_.call(this)},[f,u]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}wr.displayName="ReactiveTextNode",Object.defineProperties(j.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:wr},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),pe("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof j&&(n||(e.__np=n={}),n[i]=o,r[i]=o.peek())}}t(e)}),pe("__r",function(t,e){if(t(e),e.type!==q){Xe();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Ee(function(){s=this},{name:o}),s.c=i,s})(function(){var i;ts&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Xe(n)}}),pe("__e",function(t,e,n,r){Xe(),t(e,n,r)}),pe("diffed",function(t,e){Xe();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var o=n.U;if(o)for(var s in o){var a=o[s];a!==void 0&&!(s in r)&&(a.d(),o[s]=void 0)}else o={},n.U=o;for(var c in r){var u=o[c],f=r[c];u===void 0?(u=ns(n,c,f,i),o[c]=u):u.o(f,i)}}}t(e)});function ns(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,o=te(n);return{o:function(s,a){o.value=s,r=a},d:Ee(function(){this.N=kr;var s=o.value.value;r[e]!==s&&(r[e]=s,i?t[e]=s:s!=null&&(s!==!1||e[4]==="-")?t.setAttribute(e,s):t.removeAttribute(e))})}}pe("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}}else{var s=e.__c;if(s){var a=s.__$u;a&&(s.__$u=void 0,a.d())}}t(e)}),pe("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),I.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in t)if(s!=="__source"&&t[s]!==this.props[s])return!0;for(var a in this.props)if(!(a in t))return!0;return!1};function Mt(t,e){return L(function(){return te(t,e)},[])}var rs=function(t){queueMicrotask(function(){queueMicrotask(t)})};function is(){Zo(function(){for(var t;t=xr.shift();)br.call(t)})}function kr(){xr.push(this)===1&&(g.requestAnimationFrame||rs)(is)}const A=te(!1);function os(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function ss(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function as(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",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 cs(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function us(t,e){const[n,r]=M(null);return O(()=>{r(null);const i=e??"https://striped-woodpecker-382.convex.cloud",o=i?ss(i):void 0;if(!o||!t)return;const s=new AbortController;async function a(c){try{const u=await cs(c,t,s.signal);u&&r(u)}catch(u){if(u instanceof Error&&u.name==="AbortError")return}}return a(o),()=>{s.abort()}},[t,e]),n}const Sr={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",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",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"},ls={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",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",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"},hs=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],ds="de",fs="jex-locale",Pt=te("de"),ps={en:Sr,de:ls};function re(){return ps[Pt.value]??Sr}function Ot(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return hs.some(r=>r.value===e)?e:null}function Cr(t){const e=Ot(t);if(e)return e;try{const n=Ot(localStorage.getItem(fs));if(n)return n}catch{}if(typeof navigator<"u"){const n=Ot(navigator.language);if(n)return n}return ds}function gs(t){O(()=>{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&&(Pt.value=Cr(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const jr="jex-session-ref",Lt="jex-session-active",ge=te(null),Ye=te(!1);function _s(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function ms(){try{const t=sessionStorage.getItem(jr),e=sessionStorage.getItem(Lt);ge.value=t??null,Ye.value=t!==null&&e==="true"}catch{ge.value=null,Ye.value=!1}}function Tr(){const t=_s();ge.value=t,Ye.value=!1;try{sessionStorage.setItem(jr,t),sessionStorage.removeItem(Lt)}catch{}return t}function ys(){if(ge.value){Ye.value=!0;try{sessionStorage.setItem(Lt,"true")}catch{}}}function vs(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 z=te([{id:"chat"}]);function qe(t){z.value=[...z.value,t]}function Rr(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function Nt(t){z.value=[...z.value.slice(0,-1),t]}function Ar({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 bs({title:t}){const e=re(),n=z.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:Rr,"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(Ar,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function xs({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 ws(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexity.com",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(xs,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function ks({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 Ss({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 Cs({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 js={chat:h(ks,{size:28}),bot:h(Ar,{size:28}),sparkles:h(Cs,{size:28})},Ts={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Rs({radius:t="full",iconOption:e="chat",label:n="Chatte mit uns"}){const r=re(),i=n!=="";return h("button",{class:`jex-floating-button ${!A.value&&i?"jex-has-label":""}`,style:{borderRadius:Ts[t]??"9999px"},onClick:()=>{A.value=!A.value},"aria-label":A.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:A.value?h(Ss,{size:28}):h("div",{class:"jex-fab-inner",children:[js[e],i&&h("span",{class:"jex-fab-label",children:n})]})})}function As({greeting:t,title:e}){const n=re(),r=ge.value,[i,o]=M(!1),[s,a]=M("");function c(){Tr(),qe({id:"chat"})}function u(){qe({id:"chat"})}function f(l){l.preventDefault(),s.trim()&&qe({id:"chat"})}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-greeting",children:t}),r?h("div",{class:"jex-home-actions",children:[h("button",{class:"jex-home-start-btn",onClick:u,children:n.resumeConversation}),h("button",{class:"jex-home-new-btn",onClick:c,children:n.startNewConversation})]}):h("div",{class:"jex-home-actions",children:[h("button",{class:"jex-home-start-btn",onClick:c,children:n.chatWith.replace("{title}",e)}),!i&&h("button",{class:"jex-home-lookup-link",onClick:()=>{o(!0)},children:n.haveReferenceNumber}),i&&h("form",{class:"jex-home-lookup",onSubmit:f,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:n.referencePlaceholder,value:s,autoFocus:!0,onInput:l=>{a(l.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",children:n.resume})]})]})]})}function $s({title:t}){const e=re();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:()=>qe({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:()=>qe({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 $r(t,e){const n={get(r,i){if(typeof i=="string"){const o=[...e,i];return $r(t,o)}else if(i===Zn){if(e.length<1){const o=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${o}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const Es=()=>$r("components",[]),Qt=Zi;Es();function qs(t){const e=Ne(null),n=Mt(!1),r=dr(Qt.functions.chat.public.sessions.createOrResume),i=ht(async()=>{if(e.current)return e.current;n.value=!0;const s=ge.value??Tr();try{const c={sessionId:(await r({orgSlug:t,visitorId:s})).sessionId,visitorId:s};return e.current=c,c}catch(a){return console.error("[jexity] Failed to create session:",a),null}finally{n.value=!1}},[t,r,n]),o=e.current;return{sessionId:o?.sessionId??null,visitorId:o?.visitorId??null,isLoading:n.value,ensureSession:i}}function Er({text:t}){return h("div",{class:"jex-message bot",children:t})}function Is({text:t}){return h("div",{class:"jex-message user",children:t})}function Ms(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function Ps({sessionId:t,visitorId:e,greeting:n}){const r=Ne(null),i=Wo(Qt.functions.chat.public.conversations.listBySession,t&&e?{sessionId:t,visitorId:e}:"skip"),o=t!==null&&i===void 0;return O(()=>{r.current?.scrollIntoView({behavior:"smooth"})},[i?.length]),h("div",{class:"jex-chat-messages",children:[h(Er,{text:n}),o&&h(Ms,{}),i?.map(s=>s.role==="user"?h(Is,{text:s.content},s._id):h(Er,{text:s.content},s._id)),h("div",{ref:r})]})}function Os({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 Ls({sessionId:t,visitorId:e,isLoading:n,ensureSession:r}){const i=re(),o=Mt(""),s=dr(Qt.functions.chat.public.conversations.send);async function a(){const c=o.value.trim();if(!c||n)return;const u=t&&e?{sessionId:t,visitorId:e}:await r();u&&(ys(),o.value="",s({sessionId:u.sessionId,visitorId:u.visitorId,content:c}).catch(f=>{console.error("[jexity] Failed to send message:",f)}))}return h("div",{class:"jex-chat-input",children:[h("input",{type:"text","aria-label":i.inputPlaceholder,placeholder:i.inputPlaceholder,value:o.value,onInput:c=>{o.value=c.currentTarget.value},onKeyDown:c=>{c.key==="Enter"&&a()}}),h("button",{class:"jex-send-btn",onClick:a,"aria-label":i.sendAriaLabel,disabled:n,children:h(Os,{size:18})})]})}function Ns({greeting:t,orgSlug:e}){const{sessionId:n,visitorId:r,isLoading:i,ensureSession:o}=qs(e);return h(q,{children:[h(Ps,{sessionId:n,visitorId:r,greeting:t}),h(Ls,{sessionId:n,visitorId:r,isLoading:i,ensureSession:o})]})}function Qs(){const t=re(),[e,n]=M(""),[r,i]=M(""),[o,s]=M("");async function a(c){c.preventDefault(),Nt({id:"loading",message:t.submittingTicket}),await new Promise(f=>{setTimeout(f,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();Nt({id:"confirmation",ref:u})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:c=>{a(c)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:c=>{n(c.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:c=>{i(c.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:o,required:!0,onInput:c=>{s(c.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Fs({ticketRef:t}){const e=re();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:()=>{A.value=!1},children:e.done})]})}function Vs({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 Us({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 Bs({greeting:t,title:e,orgSlug:n}){const r=z.value,i=r[r.length-1],o=r.findLast(s=>s.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h(As,{greeting:t,title:e}),i.id==="selection"&&h($s,{title:e}),i.id==="form"&&h(Qs,{}),i.id==="confirmation"&&o&&h(Fs,{ticketRef:o.ref}),i.id==="chat"&&h(Ns,{greeting:t,orgSlug:n}),i.id==="loading"&&h(Vs,{message:i.message}),i.id==="error"&&h(Us,{message:i.message,onRetry:()=>Nt({id:"loading"}),onBack:Rr})]})}function Ds({options:t}){const e=us(t.orgSlug,t.convexUrl);gs(t.parentOrigin),O(()=>{ms()},[]);const n=as(t,e);O(()=>{Pt.value=Cr(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",o=vs({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight});return h("div",{class:`jex-widget ${i}`.trim(),style:o,children:h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[A.value&&h("div",{class:"jex-chat-window",children:[h(bs,{title:n.title}),h(Bs,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(ws,{})]}),h(Rs,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Ws='.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-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)}@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-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}.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-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:16px;padding:20px;font-size:15px;line-height:1.5;color:var(--jex-text-main)}.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;width:100%}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px)}.jex-home-start-btn:active{transform:translateY(0)}.jex-home-actions{display:flex;flex-direction:column;gap:8px}.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;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted)}.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{max-width:80%;padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{align-self:flex-start;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;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-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:6px;width:100%}.jex-home-lookup-input{flex:1;padding:8px 10px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:13px;outline:none}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:8px 14px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer}';function zs(t){const e=document.createElement("style");e.textContent=Ws,t.appendChild(e)}const Hs="https://striped-woodpecker-382.convex.cloud";let Ft=null;function Js(t){const e=t??Hs;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 Ft||(Ft=new Uo(os(e))),Ft}function Ks(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);zs(n);const r=document.createElement("div");return n.appendChild(r),Y(h(Do,{client:Js(e.convexUrl),children:h(Ds,{options:e})}),r),function(){Y(null,r),A.value=!1}}function Gs(t,e,n){const r=Ks(t,e),i=new Set,o=A.subscribe(a=>{for(const c of i)c(a)});return{shutdown(){o(),i.clear(),r(),n&&n()},open(){A.value=!0},close(){A.value=!1},toggle(){A.value=!A.value},get isOpen(){return A.value},subscribe(a){return i.add(a),()=>{i.delete(a)}}}}let Ie=null;function Xs(t){Ie&&Ie.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=Gs(e,t,()=>{t.container||e.remove(),Ie===n&&(Ie=null)});return Ie=n,n}function ie(t,e){return t.getAttribute(e)??void 0}function qr(){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:ie(t,"data-position")??void 0,theme:ie(t,"data-theme")??void 0,greeting:ie(t,"data-greeting"),title:ie(t,"data-title"),primaryColor:ie(t,"data-primary-color"),locale:ie(t,"data-locale"),convexUrl:ie(t,"data-convex-url")};window.JexityChat=Xs(n)}document.readyState==="complete"?qr():window.addEventListener("load",qr)})();
|
|
2
|
+
Called by client`}function jt(t,e){return e.data=t.errorData,e}function Z(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 ee(t,e){return JSON.stringify({udfPath:Z(t),args:Q(e)})}function Yn(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:Z(t),args:Q(e),options:Q({initialNumItems:r,id:i})})}var Di=Object.defineProperty,Wi=(t,e,n)=>e in t?Di(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F=(t,e,n)=>Wi(t,typeof e!="symbol"?e+"":e,n);class zi{constructor(){F(this,"nextQueryId"),F(this,"querySetVersion"),F(this,"querySet"),F(this,"queryIdToToken"),F(this,"identityVersion"),F(this,"auth"),F(this,"outstandingQueriesOlderThanRestart"),F(this,"outstandingAuthOlderThanRestart"),F(this,"paused"),F(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const o=Z(e),s=ee(o,n),a=this.querySet.get(s);if(a!==void 0)return a.numSubscribers+=1,{queryToken:s,modification:null,unsubscribe:()=>this.removeSubscriber(s)};{const c=this.nextQueryId++,u={id:c,canonicalizedUdfPath:o,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(s,u),this.queryIdToToken.set(c,s);const f=this.querySetVersion,l=this.querySetVersion+1,_={type:"Add",queryId:c,udfPath:o,args:[Q(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(c,_):this.querySetVersion=l,{queryToken:s,modification:{type:"ModifyQuerySet",baseVersion:f,newVersion:l,modifications:[_]},unsubscribe:()=>this.removeSubscriber(s)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=Z(e),i=ee(r,n),o=this.querySet.get(i);return o!==void 0?o.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const n=[];for(const o of this.querySet.values()){const s={type:"Add",queryId:o.id,udfPath:o.canonicalizedUdfPath,args:[Q(o.args)],journal:o.journal,componentPath:o.componentPath};n.push(s),e.has(o.id)||this.outstandingQueriesOlderThanRestart.add(o.id)}this.querySetVersion=1;const r={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:n};if(!this.auth)return this.identityVersion=0,[r,void 0];this.outstandingAuthOlderThanRestart=!0;const i={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[r,i]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,o={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,o):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[o]}}}}var Hi=Object.defineProperty,Ji=(t,e,n)=>e in t?Hi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,De=(t,e,n)=>Ji(t,typeof e!="symbol"?e+"":e,n);class Ki{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,De(this,"inflightRequests"),De(this,"requestsOlderThanRestart"),De(this,"inflightMutationsCount",0),De(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const o=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:o,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const c of e.logLines)Be(this.logger,"info",r,i,c);const o=n.status;let s,a;if(e.success)s={success:!0,logLines:e.logLines,value:le(e.result)},a=()=>o.onResult(s);else{const c=e.result,{errorData:u}=e;Be(this.logger,"error",r,i,c),s={success:!1,errorMessage:c,errorData:u!==void 0?le(u):void 0,logLines:e.logLines},a=()=>o.onResult(s)}return e.type==="ActionResponse"||!e.success?(a(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:s}):(n.status={status:"Completed",result:s,ts:e.ts,onResolve:a},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const o=i.status;o.status==="Completed"&&o.ts.lessThanOrEqual(e)&&(o.onResolve(),n.set(r,o.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const je=Symbol.for("functionName"),Zn=Symbol.for("toReferencePath");function Gi(t){return t[Zn]??null}function Xi(t){return t.startsWith("function://")}function Yi(t){let e;if(typeof t=="string")Xi(t)?e={functionHandle:t}:e={name:t};else if(t[je])e={name:t[je]};else{const n=Gi(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function T(t){const e=Yi(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[je];if(!n)throw new Error(`${t} is not a functionReference`);return n}function er(t){return{[je]:t}}function tr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return tr(i)}else if(r===je){if(t.length<2){const s=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${s}\``)}const i=t.slice(0,-1).join("/"),o=t[t.length-1];return o==="default"?i:i+":"+o}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const Zi=tr();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,We=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n);class Te{constructor(e){We(this,"queryResults"),We(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=D(n[0]),i=T(e),o=this.queryResults.get(ee(i,r));if(o!==void 0)return Te.queryValue(o.result)}getAllQueries(e){const n=[],r=T(e);for(const i of this.queryResults.values())i.udfPath===Z(r)&&n.push({args:i.args,value:Te.queryValue(i.result)});return n}setQuery(e,n,r){const i=D(n),o=T(e),s=ee(o,i);let a;r===void 0?a=void 0:a={success:!0,value:r,logLines:[]};const c={udfPath:o,args:i,result:a};this.queryResults.set(s,c),this.modifiedQueries.push(s)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class no{constructor(){We(this,"queryResults"),We(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(s=>!n.has(s.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Te(this.queryResults);for(const s of this.optimisticUpdates)s.update(i);const o=[];for(const[s,a]of this.queryResults){const c=r.get(s);(c===void 0||c.result!==a.result)&&o.push(s)}return o}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Te(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?jt(r,new Ct(he("query",n.udfPath,r))):new Error(he("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,Tt=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);class R{constructor(e,n){Tt(this,"low"),Tt(this,"high"),Tt(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 R(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>=oo?so:new R(e%Re|0,e/Re|0)}toString(){return(BigInt(this.high)*BigInt(Re)+BigInt(this.low)).toString()}equals(e){return R.isLong(e)||(e=R.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 R.isLong(e)||(e=R.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"?R.fromNumber(e):new R(e.low,e.high)}}const nr=new R(0,0),rr=65536,Re=rr*rr,oo=Re*Re,so=new R(-1,-1);var ao=Object.defineProperty,co=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ze=(t,e,n)=>co(t,typeof e!="symbol"?e+"":e,n);class ir{constructor(e,n){ze(this,"version"),ze(this,"remoteQuerySet"),ze(this,"queryPath"),ze(this,"logger"),this.version={querySet:0,ts:R.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)Be(this.logger,"info","query",i,s);const o=le(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:o,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const s of r.logLines)Be(this.logger,"info","query",i,s);const{errorData:o}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:o!==void 0?le(o):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function Rt(t){const e=ke(t);return R.fromBytesLE(Array.from(e))}function uo(t){const e=new Uint8Array(t.toBytesLE());return Se(e)}function or(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:Rt(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:Rt(t.startVersion.ts)},endVersion:{...t.endVersion,ts:Rt(t.endVersion.ts)}}}}function lo(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:uo(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,k=(t,e,n)=>fo(t,typeof e!="symbol"?e+"":e,n);const po=1e3,go=1001,_o=1005,mo=4040;let He;function de(){return He===void 0&&(He=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(He+performance.now())}function sr(){return`t=${Math.round((de()-He)/100)/10}s`}const ar={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(ar))if(t.startsWith(e))return e;return"Unknown"}class vo{constructor(e,n,r,i,o,s){this.markConnectionStateDirty=o,this.debug=s,k(this,"socket"),k(this,"connectionCount"),k(this,"_hasEverConnected",!1),k(this,"lastCloseReason"),k(this,"transitionChunkBuffer",null),k(this,"defaultInitialBackoff"),k(this,"maxBackoff"),k(this,"retries"),k(this,"serverInactivityThreshold"),k(this,"reconnectDueToServerInactivityTimeout"),k(this,"scheduledReconnect",null),k(this,"networkOnlineHandler",null),k(this,"pendingNetworkRecoveryInfo",null),k(this,"uri"),k(this,"onOpen"),k(this,"onResume"),k(this,"onMessage"),k(this,"webSocketConstructor"),k(this,"logger"),k(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=or(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:de()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",sr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",sr())),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=or(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const s=this.assembleTransition(i);if(!s)return;i=s,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==po&&n.code!==go&&n.code!==_o&&n.code!==mo){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=lo(e),i=JSON.stringify(r);let o=!1;try{this.socket.ws.send(i),o=!0}catch(s){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${s}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${o?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=de(),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=de()-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:de()})):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:ar[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),o=i*(Math.random()-.5);return i+o}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=de()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,o=`${Math.round(n/1e4)/100}MB`,s=n/(r/1e3),a=`${Math.round(s/1e4)/100}MB per second`;this._logVerbose(`received ${o} transition in ${i} at ${a}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${o}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${o} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function bo(){return xo()}function xo(){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 Ae extends Error{}Ae.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 cr(t,e){if(typeof t!="string")throw new Ae("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 Ae(`Invalid token specified: missing part #${n+1}`);let i;try{i=ko(r)}catch(o){throw new Ae(`Invalid token specified: invalid base64 for part #${n+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Ae(`Invalid token specified: invalid json for part #${n+1} (${o.message})`)}}var So=Object.defineProperty,Co=(t,e,n)=>e in t?So(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,E=(t,e,n)=>Co(t,typeof e!="symbol"?e+"":e,n);const jo=480*60*60*1e3,ur=2;class To{constructor(e,n,r){E(this,"authState",{state:"noAuth"}),E(this,"configVersion",0),E(this,"syncState"),E(this,"authenticate"),E(this,"stopSocket"),E(this,"tryRestartSocket"),E(this,"pauseSocket"),E(this,"resumeSocket"),E(this,"clearAuth"),E(this,"logger"),E(this,"refreshTokenLeewaySeconds"),E(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.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>=ur){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, ${ur-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const o=i-r;if(o<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let s=Math.min(jo,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);const a=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},s);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:a,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return cr(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 Ro=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Ao(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function $o(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Eo(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of Ro){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map($o)}var qo=Object.defineProperty,Io=(t,e,n)=>e in t?qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,S=(t,e,n)=>Io(t,typeof e!="symbol"?e+"":e,n);class Mo{constructor(e,n,r){if(S(this,"address"),S(this,"state"),S(this,"requestManager"),S(this,"webSocketManager"),S(this,"authenticationManager"),S(this,"remoteQuerySet"),S(this,"optimisticQueryResults"),S(this,"_transitionHandlerCounter",0),S(this,"_nextRequestId"),S(this,"_onTransitionFns",new Map),S(this,"_sessionId"),S(this,"firstMessageReceived",!1),S(this,"debug"),S(this,"logger"),S(this,"maxObservedTimestamp"),S(this,"connectionStateSubscribers",new Map),S(this,"nextConnectionStateSubscriberId",0),S(this,"_lastPublishedConnectionState"),S(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const d=this.connectionState();if(JSON.stringify(d)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=d;for(const p of this.connectionStateSubscribers.values())p(d)}})}),S(this,"mark",d=>{this.debug&&Ao(d,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&&Ri(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let o=r.webSocketConstructor;if(!o&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");o=o||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Xn({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Gn({verbose:r.verbose??!1});const s=e.search("://");if(s===-1)throw new Error("Provided address was not an absolute URL.");const a=e.substring(s+3),c=e.substring(0,s);let u;if(c==="http")u="ws";else if(c==="https")u="wss";else throw new Error(`Unknown parent protocol ${c}`);const f=`${u}://${a}/api/${zn}/sync`;this.state=new zi,this.remoteQuerySet=new ir(d=>this.state.queryPath(d),this.logger),this.requestManager=new Ki(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new To(this.state,{authenticate:d=>{const p=this.state.setAuth(d);return this.webSocketManager.sendMessage(p),p.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new no,this.addOnTransitionHandler(d=>{n(d.queries.map(p=>p.token))}),this._nextRequestId=0,this._sessionId=bo();const{unsavedChangesWarning:_}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(_===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else _!==!1&&window.addEventListener("beforeunload",d=>{if(this.requestManager.hasIncompleteRequests()){d.preventDefault();const p="Are you sure you want to leave? Your changes may not be saved.";return(d||window.event).returnValue=p,p}});this.webSocketManager=new vo(f,{onOpen:d=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...d,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const p=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new ir(y=>this.state.queryPath(y),this.logger);const[C,w]=this.state.restart(p);w&&this.webSocketManager.sendMessage(w),this.webSocketManager.sendMessage(C);for(const y of this.requestManager.restart())this.webSocketManager.sendMessage(y)},onResume:()=>{const[d,p]=this.state.resume();p&&this.webSocketManager.sendMessage(p),d&&this.webSocketManager.sendMessage(d);for(const C of this.requestManager.resume())this.webSocketManager.sendMessage(C)},onMessage:d=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),d.type){case"Transition":{this.observedTimestamp(d.endVersion.ts),this.authenticationManager.onTransition(d),this.remoteQuerySet.transition(d),this.state.transition(d);const p=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(p);break}case"MutationResponse":{d.success&&this.observedTimestamp(d.ts);const p=this.requestManager.onResponse(d);p!==null&&this.notifyOnQueryResultChanges(new Map([[p.requestId,p.result]]));break}case"ActionResponse":{this.requestManager.onResponse(d);break}case"AuthError":{this.authenticationManager.onAuthError(d);break}case"FatalError":{const p=Bi(this.logger,d.error);throw this.webSocketManager.terminate(),p}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},o,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&l()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[o,s]of n){const a=this.state.queryToken(o);if(a!==null){const c={result:s,udfPath:this.state.queryPath(o),args:this.state.queryArgs(o)};r.set(a,c)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(o=>{const s=this.optimisticQueryResults.rawQueryResult(o);return{token:o,modification:{kind:"Updated",result:s}}}),reflectedMutations:Array.from(e).map(([o,s])=>({requestId:o,result:s})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?cr(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=D(n),{modification:o,queryToken:s,unsubscribe:a}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return o!==null&&this.webSocketManager.sendMessage(o),{queryToken:s,unsubscribe:()=>{const c=a();c&&this.webSocketManager.sendMessage(c)}}}localQueryResult(e,n){const r=D(n),i=ee(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=D(n),i=ee(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=D(n),i=ee(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?jt(i,new Ct(he("mutation",e,i))):new Error(he("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:o}=this.enqueueMutation(e,n,r,i);return o}enqueueMutation(e,n,r,i){const o=D(n);this.tryReportLongDisconnect();const s=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const f=r.optimisticUpdate;if(f!==void 0){const l=p=>{f(p,o)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},d=this.optimisticQueryResults.applyOptimisticUpdate(l,s).map(p=>{const C=this.localQueryResultByToken(p);return{token:p,modification:{kind:"Updated",result:C===void 0?void 0:{success:!0,value:C,logLines:[]}}}});this.handleTransition({queries:d,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const a={type:"Mutation",requestId:s,udfPath:e,componentPath:i,args:[Q(o)]},c=this.webSocketManager.sendMessage(a),u=this.requestManager.request(a,c);return{requestId:s,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?jt(r,new Ct(he("action",e,r))):new Error(he("action",e,r));return r.value}async actionInternal(e,n,r){const i=D(n),o=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const s={type:"Action",requestId:o,udfPath:e,componentPath:r,args:[Q(i)]},a=this.webSocketManager.sendMessage(s);return this.requestManager.request(s,a)}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=Eo(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-${zn}`},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 At(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 Po=Object.defineProperty,Oo=(t,e,n)=>e in t?Po(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lr=(t,e,n)=>Oo(t,typeof e!="symbol"?e+"":e,n);class Lo{constructor(e,n){this.client=e,this.onTransition=n,lr(this,"paginatedQuerySet",new Map),lr(this,"lastTransitionTs"),this.lastTransitionTs=R.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=Z(e),o=Yn(i,n,r),s=()=>this.removePaginatedQuerySubscriber(o),a=this.paginatedQuerySet.get(o);return a?(a.numSubscribers+=1,{paginatedQueryToken:o,unsubscribe:s}):(this.paginatedQuerySet.set(o,{token:o,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(o,null,r.initialNumItems),{paginatedQueryToken:o,unsubscribe:s})}localQueryResult(e,n,r){const i=Z(e),o=Yn(i,n,r);return this.localQueryResultByToken(o)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:c=>this.loadMoreOfPaginatedQuery(e,c)};let i=[],o=!1,s=!1;for(const c of r){const u=this.client.localQueryResultByToken(c);if(u===void 0){o=!0,s=!1;continue}const f=At(u);i=i.concat(f.page),s=!!f.isDone}let a;return o?a=i.length===0?"LoadingFirstPage":"LoadingMore":s?a="Exhausted":a="CanLoadMore",{results:i,status:a,loadMore:c=>this.loadMoreOfPaginatedQuery(e,c)}}onBaseTransition(e){const n=e.queries.map(s=>s.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,s=>this.client.localQueryResultByToken(s)),i=r.map(s=>({token:s,modification:{kind:"Updated",result:this.localQueryResultByToken(s)}})));const o={...e,paginatedQueries:i};this.onTransition(o)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const o=At(i);if(o.isDone)return!1;this.addPageToPaginatedQuery(e,o.continueCursor,n);const s={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(s),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,o]of this.paginatedQuerySet)for(const s of this.allQueryTokens(o))if(r.has(s)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:o,pageKeyToQuery:s,pageKeys:a}=i;for(const[c,[u,f]]of o)n(s.get(u).queryToken)!==void 0&&n(s.get(f).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,c,u,f);for(const c of a){if(o.has(c))continue;const u=s.get(c).queryToken,f=n(u);if(!f)continue;const l=At(f);l.splitCursor&&(l.pageStatus==="SplitRecommended"||l.pageStatus==="SplitRequired"||l.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,c,l.splitCursor,l.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const o=e.nextPageKey++,s=e.nextPageKey++,a={cursor:i,numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:null,endCursor:r}});e.pageKeyToQuery.set(o,c);const u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:r,endCursor:i}});e.pageKeyToQuery.set(s,u),e.ongoingSplits.set(n,[o,s])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),o=i.nextPageKey++,s={cursor:n,numItems:r,id:i.id},a={...i.args,paginationOpts:s},c=this.client.subscribe(i.canonicalizedUdfPath,a);return i.pageKeys.push(o),i.pageKeyToQuery.set(o,c),c}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const o=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const s=e.pageKeys.indexOf(n);e.pageKeys.splice(s,1,r,i),e.ongoingSplits.delete(n),o.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function No({getCurrentValue:t,subscribe:e}){const[n,r]=M(()=>({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})),O(()=>{let o=!1;const s=()=>{o||r(c=>{if(c.getCurrentValue!==t||c.subscribe!==e)return c;const u=t();return c.value===u?c:{...c,value:u}})},a=e(s);return s(),()=>{o=!0,a()}},[t,e]),i}var Qo=Object.defineProperty,Fo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,W=(t,e,n)=>Fo(t,typeof e!="symbol"?e+"":e,n);const Vo=5e3;if(typeof yt>"u")throw new Error("Required dependency 'react' not found");function hr(t,e,n){function r(i){return zo(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(o){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${T(t)}`);return hr(t,e,o)},r}class Uo{constructor(e,n){if(W(this,"address"),W(this,"cachedSync"),W(this,"cachedPaginatedQueryClient"),W(this,"listeners"),W(this,"options"),W(this,"closed",!1),W(this,"_logger"),W(this,"adminAuth"),W(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?Xn({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Gn({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 Mo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new Lo(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,o=T(e);return{onUpdate:s=>{const{queryToken:a,unsubscribe:c}=this.sync.subscribe(o,r,i),u=this.listeners.get(a);return u!==void 0?u.add(s):this.listeners.set(a,new Set([s])),()=>{if(this.closed)return;const f=this.listeners.get(a);f.delete(s),f.size===0&&this.listeners.delete(a),c()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(o,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(o,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(o,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??Vo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=T(e);return{onUpdate:o=>{const{paginatedQueryToken:s,unsubscribe:a}=this.paginatedQueryClient.subscribe(i,n||{},r),c=this.listeners.get(s);return c!==void 0?c.add(o):this.listeners.set(s,new Set([o])),()=>{if(this.closed)return;const u=this.listeners.get(s);u.delete(o),u.size===0&&this.listeners.delete(s),a()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,o=T(e);return this.sync.mutation(o,r,i)}action(e,...n){const r=T(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((o,s)=>{const a=r.onUpdate(()=>{a();try{o(r.localQueryResult())}catch(c){s(c)}})})}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 $t=yt.createContext(void 0);function Bo(){return Qe($t)}const Do=({client:t,children:e})=>yt.createElement($t.Provider,{value:t},e);function Wo(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:D(e[0]),i=typeof t=="string"?er(t):t,o=T(i),s=L(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(Q(r)),o,n]),c=Go(s).query;if(c instanceof Error)throw c;return c}function dr(t){const e=typeof t=="string"?er(t):t,n=Qe($t);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 L(()=>hr(e,n),[n,T(e)])}function zo(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,Jo=(t,e,n)=>e in t?Ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Et=(t,e,n)=>Jo(t,typeof e!="symbol"?e+"":e,n);class Ko{constructor(e){Et(this,"createWatch"),Et(this,"queries"),Et(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:o}=e[n];if(T(r),this.queries[n]===void 0)this.addQuery(n,r,i,o?{paginationOptions:o}:{});else{const s=this.queries[n];(T(r)!==T(s.query)||JSON.stringify(Q(i))!==JSON.stringify(Q(s.args))||JSON.stringify(o)!==JSON.stringify(s.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,o?{paginationOptions:o}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:o}=e[r],s=e[r].paginationOptions;T(i);const a=this.createWatch(i,o,s?{paginationOptions:s}:{});let c;try{c=a.localQueryResult()}catch(u){if(u instanceof Error)c=u;else throw u}n[r]=c}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:o,paginationOptions:s}=this.queries[n],a="journal"in o?o.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...a?{journal:a}:[],...s?{paginationOptions:s}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:o}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const s=this.createWatch(n,r,{...o?{journal:o}:[],...i?{paginationOptions:i}:{}}),a=s.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:s,unsubscribe:a,...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 Go(t){const e=Bo();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=L(()=>(r,i,{journal:o,paginationOptions:s})=>s?e.watchPaginatedQuery(r,i,s):e.watchQuery(r,i,o?{journal:o}:{}),[e]);return Xo(t,n)}function Xo(t,e){const[n]=M(()=>new Ko(e));n.createWatch!==e&&n.setCreateWatch(e),O(()=>()=>n.destroy(),[n]);const r=L(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return No(r)}var Yo=Symbol.for("preact-signals");function Je(){if(J>1)J--;else{for(var t,e=!1;$e!==void 0;){var n=$e;for($e=void 0,qt++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&gr(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(qt=0,J--,e)throw t}}function Zo(t){if(J>0)return t();J++;try{return t()}finally{Je()}}var m=void 0;function fr(t){var e=m;m=void 0;try{return t()}finally{m=e}}var $e=void 0,J=0,qt=0,Ke=0;function pr(t){if(m!==void 0){var e=t.n;if(e===void 0||e.t!==m)return e={i:0,S:t,p:m.s,n:void 0,t:m,e:void 0,x:void 0,r:e},m.s!==void 0&&(m.s.n=e),m.s=e,t.n=e,32&m.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=m.s,e.n=void 0,m.s.n=e,m.s=e),e}}function j(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}j.prototype.brand=Yo,j.prototype.h=function(){return!0},j.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:fr(function(){var r;(r=e.W)==null||r.call(e)}))},j.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&&fr(function(){var i;(i=e.Z)==null||i.call(e)}))}},j.prototype.subscribe=function(t){var e=this;return Ee(function(){var n=e.value,r=m;m=void 0;try{t(n)}finally{m=r}},{name:"sub"})},j.prototype.valueOf=function(){return this.value},j.prototype.toString=function(){return this.value+""},j.prototype.toJSON=function(){return this.value},j.prototype.peek=function(){var t=m;m=void 0;try{return this.value}finally{m=t}},Object.defineProperty(j.prototype,"value",{get:function(){var t=pr(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(qt>100)throw new Error("Cycle detected");this.v=t,this.i++,Ke++,J++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function te(t,e){return new j(t,e)}function gr(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 _r(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 mr(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 ne(t,e){j.call(this,void 0),this.x=t,this.s=void 0,this.g=Ke-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ne.prototype=new j,ne.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ke))return!0;if(this.g=Ke,this.f|=1,this.i>0&&!gr(this))return this.f&=-2,!0;var t=m;try{_r(this),m=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 m=t,mr(this),this.f&=-2,!0},ne.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)}j.prototype.S.call(this,t)},ne.prototype.U=function(t){if(this.t!==void 0&&(j.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)}},ne.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(ne.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=pr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function yr(t,e){return new ne(t,e)}function vr(t){var e=t.u;if(t.u=void 0,typeof e=="function"){J++;var n=m;m=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,It(t),r}finally{m=n,Je()}}}function It(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,vr(t)}function es(t){if(m!==this)throw new Error("Out-of-order effect");mr(this),m=t,this.f&=-2,8&this.f&&It(this),Je()}function fe(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}fe.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()}},fe.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,vr(this),_r(this),J++;var t=m;return m=this,es.bind(this,t)},fe.prototype.N=function(){2&this.f||(this.f|=2,this.o=$e,$e=this)},fe.prototype.d=function(){this.f|=8,1&this.f||It(this)},fe.prototype.dispose=function(){this.d()};function Ee(t,e){var n=new fe(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var br,Ge,ts=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,xr=[];Ee(function(){br=this.N})();function pe(t,e){g[t]=e.bind(null,g[t]||function(){})}function Xe(t){if(Ge){var e=Ge;Ge=void 0,e()}Ge=t&&t.S()}function wr(t){var e=this,n=t.data,r=Mt(n);r.value=n;var i=L(function(){for(var a=e,c=e.__v;c=c.__;)if(c.__c){c.__c.__$f|=4;break}var u=yr(function(){var d=r.value.value;return d===0?0:d===!0?"":d||""}),f=yr(function(){return!Array.isArray(u.value)&&!Bt(u.value)}),l=Ee(function(){if(this.N=kr,f.value){var d=u.value;a.__v&&a.__v.__e&&a.__v.__e.nodeType===3&&(a.__v.__e.data=d)}}),_=e.__$u.d;return e.__$u.d=function(){l(),_.call(this)},[f,u]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}wr.displayName="ReactiveTextNode",Object.defineProperties(j.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:wr},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),pe("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof j&&(n||(e.__np=n={}),n[i]=o,r[i]=o.peek())}}t(e)}),pe("__r",function(t,e){if(t(e),e.type!==q){Xe();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Ee(function(){s=this},{name:o}),s.c=i,s})(function(){var i;ts&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Xe(n)}}),pe("__e",function(t,e,n,r){Xe(),t(e,n,r)}),pe("diffed",function(t,e){Xe();var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var o=n.U;if(o)for(var s in o){var a=o[s];a!==void 0&&!(s in r)&&(a.d(),o[s]=void 0)}else o={},n.U=o;for(var c in r){var u=o[c],f=r[c];u===void 0?(u=ns(n,c,f,i),o[c]=u):u.o(f,i)}}}t(e)});function ns(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,o=te(n);return{o:function(s,a){o.value=s,r=a},d:Ee(function(){this.N=kr;var s=o.value.value;r[e]!==s&&(r[e]=s,i?t[e]=s:s!=null&&(s!==!1||e[4]==="-")?t.setAttribute(e,s):t.removeAttribute(e))})}}pe("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}}else{var s=e.__c;if(s){var a=s.__$u;a&&(s.__$u=void 0,a.d())}}t(e)}),pe("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),I.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in t)if(s!=="__source"&&t[s]!==this.props[s])return!0;for(var a in this.props)if(!(a in t))return!0;return!1};function Mt(t,e){return L(function(){return te(t,e)},[])}var rs=function(t){queueMicrotask(function(){queueMicrotask(t)})};function is(){Zo(function(){for(var t;t=xr.shift();)br.call(t)})}function kr(){xr.push(this)===1&&(g.requestAnimationFrame||rs)(is)}const A=te(!1);function os(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function ss(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function as(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",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 cs(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function us(t,e){const[n,r]=M(null);return O(()=>{r(null);const i=e??"https://festive-mouse-978.eu-west-1.convex.cloud",o=i?ss(i):void 0;if(!o||!t)return;const s=new AbortController;async function a(c){try{const u=await cs(c,t,s.signal);u&&r(u)}catch(u){if(u instanceof Error&&u.name==="AbortError")return}}return a(o),()=>{s.abort()}},[t,e]),n}const Sr={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",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",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"},ls={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",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",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"},hs=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],ds="de",fs="jex-locale",Pt=te("de"),ps={en:Sr,de:ls};function re(){return ps[Pt.value]??Sr}function Ot(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return hs.some(r=>r.value===e)?e:null}function Cr(t){const e=Ot(t);if(e)return e;try{const n=Ot(localStorage.getItem(fs));if(n)return n}catch{}if(typeof navigator<"u"){const n=Ot(navigator.language);if(n)return n}return ds}function gs(t){O(()=>{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&&(Pt.value=Cr(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const jr="jex-session-ref",Lt="jex-session-active",ge=te(null),Ye=te(!1);function _s(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function ms(){try{const t=sessionStorage.getItem(jr),e=sessionStorage.getItem(Lt);ge.value=t??null,Ye.value=t!==null&&e==="true"}catch{ge.value=null,Ye.value=!1}}function Tr(){const t=_s();ge.value=t,Ye.value=!1;try{sessionStorage.setItem(jr,t),sessionStorage.removeItem(Lt)}catch{}return t}function ys(){if(ge.value){Ye.value=!0;try{sessionStorage.setItem(Lt,"true")}catch{}}}function vs(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 z=te([{id:"chat"}]);function qe(t){z.value=[...z.value,t]}function Rr(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function Nt(t){z.value=[...z.value.slice(0,-1),t]}function Ar({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 bs({title:t}){const e=re(),n=z.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:Rr,"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(Ar,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function xs({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 ws(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexity.com",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(xs,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function ks({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 Ss({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 Cs({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 js={chat:h(ks,{size:28}),bot:h(Ar,{size:28}),sparkles:h(Cs,{size:28})},Ts={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Rs({radius:t="full",iconOption:e="chat",label:n="Chatte mit uns"}){const r=re(),i=n!=="";return h("button",{class:`jex-floating-button ${!A.value&&i?"jex-has-label":""}`,style:{borderRadius:Ts[t]??"9999px"},onClick:()=>{A.value=!A.value},"aria-label":A.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:A.value?h(Ss,{size:28}):h("div",{class:"jex-fab-inner",children:[js[e],i&&h("span",{class:"jex-fab-label",children:n})]})})}function As({greeting:t,title:e}){const n=re(),r=ge.value,[i,o]=M(!1),[s,a]=M("");function c(){Tr(),qe({id:"chat"})}function u(){qe({id:"chat"})}function f(l){l.preventDefault(),s.trim()&&qe({id:"chat"})}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-greeting",children:t}),r?h("div",{class:"jex-home-actions",children:[h("button",{class:"jex-home-start-btn",onClick:u,children:n.resumeConversation}),h("button",{class:"jex-home-new-btn",onClick:c,children:n.startNewConversation})]}):h("div",{class:"jex-home-actions",children:[h("button",{class:"jex-home-start-btn",onClick:c,children:n.chatWith.replace("{title}",e)}),!i&&h("button",{class:"jex-home-lookup-link",onClick:()=>{o(!0)},children:n.haveReferenceNumber}),i&&h("form",{class:"jex-home-lookup",onSubmit:f,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:n.referencePlaceholder,value:s,autoFocus:!0,onInput:l=>{a(l.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",children:n.resume})]})]})]})}function $s({title:t}){const e=re();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:()=>qe({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:()=>qe({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 $r(t,e){const n={get(r,i){if(typeof i=="string"){const o=[...e,i];return $r(t,o)}else if(i===Zn){if(e.length<1){const o=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${o}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const Es=()=>$r("components",[]),Qt=Zi;Es();function qs(t){const e=Ne(null),n=Mt(!1),r=dr(Qt.functions.chat.public.sessions.createOrResume),i=ht(async()=>{if(e.current)return e.current;n.value=!0;const s=ge.value??Tr();try{const c={sessionId:(await r({orgSlug:t,visitorId:s})).sessionId,visitorId:s};return e.current=c,c}catch(a){return console.error("[jexity] Failed to create session:",a),null}finally{n.value=!1}},[t,r,n]),o=e.current;return{sessionId:o?.sessionId??null,visitorId:o?.visitorId??null,isLoading:n.value,ensureSession:i}}function Er({text:t}){return h("div",{class:"jex-message bot",children:t})}function Is({text:t}){return h("div",{class:"jex-message user",children:t})}function Ms(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function Ps({sessionId:t,visitorId:e,greeting:n}){const r=Ne(null),i=Wo(Qt.functions.chat.public.conversations.listBySession,t&&e?{sessionId:t,visitorId:e}:"skip"),o=t!==null&&i===void 0;return O(()=>{r.current?.scrollIntoView({behavior:"smooth"})},[i?.length]),h("div",{class:"jex-chat-messages",children:[h(Er,{text:n}),o&&h(Ms,{}),i?.map(s=>s.role==="user"?h(Is,{text:s.content},s._id):h(Er,{text:s.content},s._id)),h("div",{ref:r})]})}function Os({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 Ls({sessionId:t,visitorId:e,isLoading:n,ensureSession:r}){const i=re(),o=Mt(""),s=dr(Qt.functions.chat.public.conversations.send);async function a(){const c=o.value.trim();if(!c||n)return;const u=t&&e?{sessionId:t,visitorId:e}:await r();u&&(ys(),o.value="",s({sessionId:u.sessionId,visitorId:u.visitorId,content:c}).catch(f=>{console.error("[jexity] Failed to send message:",f)}))}return h("div",{class:"jex-chat-input",children:[h("input",{type:"text","aria-label":i.inputPlaceholder,placeholder:i.inputPlaceholder,value:o.value,onInput:c=>{o.value=c.currentTarget.value},onKeyDown:c=>{c.key==="Enter"&&a()}}),h("button",{class:"jex-send-btn",onClick:a,"aria-label":i.sendAriaLabel,disabled:n,children:h(Os,{size:18})})]})}function Ns({greeting:t,orgSlug:e}){const{sessionId:n,visitorId:r,isLoading:i,ensureSession:o}=qs(e);return h(q,{children:[h(Ps,{sessionId:n,visitorId:r,greeting:t}),h(Ls,{sessionId:n,visitorId:r,isLoading:i,ensureSession:o})]})}function Qs(){const t=re(),[e,n]=M(""),[r,i]=M(""),[o,s]=M("");async function a(c){c.preventDefault(),Nt({id:"loading",message:t.submittingTicket}),await new Promise(f=>{setTimeout(f,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();Nt({id:"confirmation",ref:u})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:c=>{a(c)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:c=>{n(c.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:c=>{i(c.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:o,required:!0,onInput:c=>{s(c.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Fs({ticketRef:t}){const e=re();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:()=>{A.value=!1},children:e.done})]})}function Vs({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 Us({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 Bs({greeting:t,title:e,orgSlug:n}){const r=z.value,i=r[r.length-1],o=r.findLast(s=>s.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h(As,{greeting:t,title:e}),i.id==="selection"&&h($s,{title:e}),i.id==="form"&&h(Qs,{}),i.id==="confirmation"&&o&&h(Fs,{ticketRef:o.ref}),i.id==="chat"&&h(Ns,{greeting:t,orgSlug:n}),i.id==="loading"&&h(Vs,{message:i.message}),i.id==="error"&&h(Us,{message:i.message,onRetry:()=>Nt({id:"loading"}),onBack:Rr})]})}function Ds({options:t}){const e=us(t.orgSlug,t.convexUrl);gs(t.parentOrigin),O(()=>{ms()},[]);const n=as(t,e);O(()=>{Pt.value=Cr(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",o=vs({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight});return h("div",{class:`jex-widget ${i}`.trim(),style:o,children:h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[A.value&&h("div",{class:"jex-chat-window",children:[h(bs,{title:n.title}),h(Bs,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(ws,{})]}),h(Rs,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Ws='.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-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)}@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-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}.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-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:16px;padding:20px;font-size:15px;line-height:1.5;color:var(--jex-text-main)}.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;width:100%}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px)}.jex-home-start-btn:active{transform:translateY(0)}.jex-home-actions{display:flex;flex-direction:column;gap:8px}.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;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted)}.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{max-width:80%;padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{align-self:flex-start;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;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-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:6px;width:100%}.jex-home-lookup-input{flex:1;padding:8px 10px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:13px;outline:none}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:8px 14px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer}';function zs(t){const e=document.createElement("style");e.textContent=Ws,t.appendChild(e)}const Hs="https://festive-mouse-978.eu-west-1.convex.cloud";let Ft=null;function Js(t){const e=t??Hs;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 Ft||(Ft=new Uo(os(e))),Ft}function Ks(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);zs(n);const r=document.createElement("div");return n.appendChild(r),Y(h(Do,{client:Js(e.convexUrl),children:h(Ds,{options:e})}),r),function(){Y(null,r),A.value=!1}}function Gs(t,e,n){const r=Ks(t,e),i=new Set,o=A.subscribe(a=>{for(const c of i)c(a)});return{shutdown(){o(),i.clear(),r(),n&&n()},open(){A.value=!0},close(){A.value=!1},toggle(){A.value=!A.value},get isOpen(){return A.value},subscribe(a){return i.add(a),()=>{i.delete(a)}}}}let Ie=null;function Xs(t){Ie&&Ie.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=Gs(e,t,()=>{t.container||e.remove(),Ie===n&&(Ie=null)});return Ie=n,n}function ie(t,e){return t.getAttribute(e)??void 0}function qr(){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:ie(t,"data-position")??void 0,theme:ie(t,"data-theme")??void 0,greeting:ie(t,"data-greeting"),title:ie(t,"data-title"),primaryColor:ie(t,"data-primary-color"),locale:ie(t,"data-locale"),convexUrl:ie(t,"data-convex-url")};window.JexityChat=Xs(n)}document.readyState==="complete"?qr():window.addEventListener("load",qr)})();
|
|
3
3
|
//# sourceMappingURL=widget.js.map
|