@nhost/nhost-js 2.2.3 → 2.2.5
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.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +61 -0
- package/dist/index.esm.js.map +1 -1
- package/package.json +5 -5
- package/umd/nhost-js.umd.js +7 -7
- package/umd/nhost-js.umd.js.map +1 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(v,ve){typeof exports=="object"&&typeof module!="undefined"?ve(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],ve):(v=typeof globalThis!="undefined"?globalThis:v||self,ve(v["@nhost/nhost-js"]={},v.graphql))})(this,function(v,ve){"use strict";function Tt(t){this.message=t}Tt.prototype=new Error,Tt.prototype.name="InvalidCharacterError";var er=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new Tt("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,s=0,o="";n=e.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?o+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function jn(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(r){return decodeURIComponent(er(r).replace(/(.)/g,function(n,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return er(e)}}function Ke(t){this.message=t}function $n(t,e){if(typeof t!="string")throw new Ke("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse(jn(t.split(".")[r]))}catch(n){throw new Ke("Invalid token specified: "+n.message)}}Ke.prototype=new Error,Ke.prototype.name="InvalidTokenError";/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -11,10 +11,10 @@
|
|
|
11
11
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
12
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
13
|
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */var v=function(){return v=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},v.apply(this,arguments)};function Tt(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function k(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function A(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function C(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var P;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(P||(P={}));var Q;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(Q||(Q={}));var Ke=P.Start,ze=P.Stop,le=P.Raise,de=P.Send,bt=P.Cancel,er=P.NullEvent,He=P.Assign,Ln=P.After,jn=P.DoneState,Ye=P.Log,tr=P.Init,We=P.Invoke,$n=P.ErrorExecution,At=P.ErrorPlatform,kt=P.ErrorCustom,Je=P.Update,rr=P.Choose,nr=P.Pure;const qn=Object.freeze(Object.defineProperty({__proto__:null,after:Ln,assign:He,cancel:bt,choose:rr,doneState:jn,error:kt,errorExecution:$n,errorPlatform:At,init:tr,invoke:We,log:Ye,nullEvent:er,pure:nr,raise:le,send:de,start:Ke,stop:ze,update:Je},Symbol.toStringTag,{value:"Module"}));var ir=".",sr={},Ot="xstate.guard",Fn="",L=process.env.NODE_ENV==="production",Be;function It(t,e,r){r===void 0&&(r=ir);var n=Re(t,r),i=Re(e,r);return x(i)?x(n)?i===n:!1:x(n)?n in i:Object.keys(n).every(function(s){return s in i?It(n[s],i[s]):!1})}function or(t){try{return x(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function xt(t,e){try{return ve(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function Gn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Re(t,e){if(Gn(t))return t.value;if(ve(t))return Qe(t);if(typeof t!="string")return t;var r=xt(t,e);return Qe(r)}function Qe(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function Pe(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function ar(t,e,r){var n,i,s={};try{for(var o=k(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,h=t[c];r(h)&&(s[c]=e(h,c,t))}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var Vn=function(t){return function(e){var r,n,i=e;try{for(var s=k(t),o=s.next();!o.done;o=s.next()){var u=o.value;i=i[u]}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function Kn(t,e){return function(r){var n,i,s=r;try{for(var o=k(t),u=o.next();!u.done;u=o.next()){var c=u.value;s=s[e][c]}}catch(h){n={error:h}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function Xe(t){if(!t)return[[]];if(x(t))return[[t]];var e=j(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:Xe(t[r]).map(function(i){return[r].concat(i)})}));return e}function j(t){var e;return(e=[]).concat.apply(e,C([],A(t),!1))}function cr(t){return ve(t)?t:[t]}function H(t){return t===void 0?[]:cr(t)}function Ze(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=k(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,h=t[c];N(h)?s[c]=h(e,r.data):s[c]=h}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function zn(t){return/^(done|error)\./.test(t)}function ur(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function Hn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Yn(t,e){var r,n,i=A([[],[]],2),s=i[0],o=i[1];try{for(var u=k(t),c=u.next();!c.done;c=u.next()){var h=c.value;e(h)?s.push(h):o.push(h)}}catch(a){r={error:a}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[s,o]}function lr(t,e){return Pe(t.states,function(r,n){if(r){var i=(x(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:lr(r,i)}}})}function Wn(t,e){return{current:e,states:lr(t,e)}}function dr(t,e,r,n){L||$(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var u,c,h=o.assignment,a={state:n,action:o,_event:e},l={};if(N(h))l=h(s,e.data,a);else try{for(var d=k(Object.keys(h)),f=d.next();!f.done;f=d.next()){var p=f.value,m=h[p];l[p]=N(m)?m(s,e.data,a):m}}catch(w){u={error:w}}finally{try{f&&!f.done&&(c=d.return)&&c.call(d)}finally{if(u)throw u.error}}return Object.assign({},s,l)},t);return i}var $=function(){};L||($=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function ve(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function x(t){return typeof t=="string"}function hr(t,e){if(t)return x(t)?{type:Ot,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Ot,name:t.name,predicate:t}:t}function Jn(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var oe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();Be={},Be[oe]=function(){return this},Be[Symbol.observable]=function(){return this};function ee(t){return!!t&&"__xstatenode"in t}function Bn(t){return!!t&&typeof t.send=="function"}var Qn=function(){var t=0;return function(){return t++,t.toString(16)}}();function Rt(t,e){return x(t)||typeof t=="number"?v({type:t},e):t}function G(t,e){if(!x(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Rt(t);return v({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function ge(t,e){var r=cr(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||ee(n)?{target:n,event:t}:v(v({},n),{event:t})});return r}function Xn(t){if(!(t===void 0||t===Fn))return H(t)}function Zn(t,e,r){if(!L){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function fr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Ot)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var u=s==null?void 0:s[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,o)}function pr(t){return typeof t=="string"?{type:t}:t}function et(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function tt(t,e){return"".concat(t,":invocation[").concat(e,"]")}var he=G({type:tr});function rt(t,e){return e&&e[t]||void 0}function me(t,e){var r;if(x(t)||typeof t=="number"){var n=rt(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=rt(t.type,e);if(N(n))r=v(v({},t),{exec:n});else if(n){var i=n.type||t.type;r=v(v(v({},n),t),{type:i})}else r=t}return r}var te=function(t,e){if(!t)return[];var r=ve(t)?t:[t];return r.map(function(n){return me(n,e)})};function nt(t){var e=me(t);return v(v({id:x(t)?t:e.id},e),{type:e.type})}function vr(t){return x(t)?{type:le,event:t}:ae(t,{to:Q.Internal})}function gr(t){return{type:le,_event:G(t.event)}}function ae(t,e){return{to:e?e.to:void 0,type:de,event:N(t)?t:Rt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:or(t)}}function mr(t,e,r,n){var i={_event:r},s=G(N(t.event)?t.event(e,r.data,i):t.event),o;if(x(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var c=N(t.to)?t.to(e,r.data,i):t.to;return v(v({},t),{to:c,_event:s,event:s.data,delay:o})}function Pt(t,e){return ae(t,v(v({},e),{to:Q.Parent}))}function ei(t,e,r){return ae(e,v(v({},r),{to:t}))}function ti(){return Pt(Je)}function ri(t,e){return ae(t,v(v({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var ni=function(t,e){return{context:t,event:e}};function ii(t,e){return t===void 0&&(t=ni),{type:Ye,label:e,expr:t}}var yr=function(t,e,r){return v(v({},t),{value:x(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},wr=function(t){return{type:bt,sendId:t}};function Er(t){var e=nt(t);return{type:P.Start,activity:e,exec:void 0}}function Sr(t){var e=N(t)?t:nt(t);return{type:P.Stop,activity:e,exec:void 0}}function Tr(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:P.Stop,activity:i};return s}var br=function(t){return{type:He,assignment:t}};function si(t){return typeof t=="object"&&"type"in t}function Ar(t,e){var r=e?"#".concat(e):"";return"".concat(P.After,"(").concat(t,")").concat(r)}function Ne(t,e){var r="".concat(P.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Ue(t,e){var r="".concat(P.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function ye(t,e){var r="".concat(P.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function oi(t){return{type:P.Pure,get:t}}function ai(t,e){if(!L&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var s=typeof r=="function"?r.apply(void 0,C([],A(n),!1)):r;if(!s)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return s}}return ae(function(n,i){return i},v(v({},e),{to:t}))}function ci(t,e){return Pt(function(r,n,i){return{type:kt,data:N(t)?t(r,n,i):t}},v(v({},e),{to:Q.Parent}))}function ui(t){return{type:P.Choose,conds:t}}var li=function(t){var e,r,n=[];try{for(var i=k(t),s=i.next();!s.done;s=i.next())for(var o=s.value,u=0;u<o.length;){if(o[u].type===He){n.push(o[u]),o.splice(u,1);continue}u++}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function _e(t,e,r,n,i,s,o){o===void 0&&(o=!1);var u=o?[]:li(i),c=u.length?dr(r,n,u,e):r,h=o?[r]:void 0,a=[];function l(p){var m;switch(p.type){case le:return gr(p);case de:var w=mr(p,c,n,t.options.delays);return L||$(!x(p.delay)||typeof w.delay=="number","No delay reference for delay expression '".concat(p.delay,"' was found on machine '").concat(t.id,"'")),s&&w.to!==Q.Internal&&a.push(w),w;case Ye:{var S=yr(p,c,n);return s==null||s(S,c,n),S}case rr:{var y=p,E=(m=y.conds.find(function(J){var se=hr(J.cond,t.options.guards);return!se||fr(t,se,c,n,s?void 0:e)}))===null||m===void 0?void 0:m.actions;if(!E)return[];var U=A(_e(t,e,c,n,[te(H(E),t.options.actions)],s,o),2),O=U[0],M=U[1];return c=M,h==null||h.push(c),O}case nr:{var E=p.get(c,n.data);if(!E)return[];var I=A(_e(t,e,c,n,[te(H(E),t.options.actions)],s,o),2),R=I[0],_=I[1];return c=_,h==null||h.push(c),R}case ze:{var S=Tr(p,c,n);return s==null||s(S,r,n),S}case He:{c=dr(c,n,[p],s?void 0:e),h==null||h.push(c);break}default:var T=me(p,t.options.actions),D=T.exec;if(s)s(T,c,n);else if(D&&h){var z=h.length-1;T=v(v({},T),{exec:function(J){for(var se=[],Oe=1;Oe<arguments.length;Oe++)se[Oe-1]=arguments[Oe];D.apply(void 0,C([h[z]],A(se),!1))}})}return T}}function d(p){var m,w,S=[];try{for(var y=k(p),E=y.next();!E.done;E=y.next()){var U=E.value,O=l(U);O&&(S=S.concat(O))}}catch(M){m={error:M}}finally{try{E&&!E.done&&(w=y.return)&&w.call(y)}finally{if(m)throw m.error}}return a.forEach(function(M){s(M,c,n)}),a.length=0,S}var f=j(i.map(d));return[f,c]}const di=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:qn,after:Ar,assign:br,cancel:wr,choose:ui,done:Ne,doneInvoke:Ue,error:ye,escalate:ci,forwardTo:ai,getActionFunction:rt,initEvent:he,isActionObject:si,log:ii,pure:oi,raise:vr,resolveActions:_e,resolveLog:yr,resolveRaise:gr,resolveSend:mr,resolveStop:Tr,respond:ri,send:ae,sendParent:Pt,sendTo:ei,sendUpdate:ti,start:Er,stop:Sr,toActionObject:me,toActionObjects:te,toActivityDefinition:nt},Symbol.toStringTag,{value:"Module"}));var it=[],we=function(t,e){it.push(t);var r=e(t);return it.pop(),r},hi=function(t){return t(it[it.length-1])};function kr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[oe]=function(){return this},e}function fi(t,e,r,n){var i,s=pr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],u=t.data?Ze(t.data,r,n):void 0,c=o?Nt(o,t.id,u):kr(t.id);return c.meta=t,c}function Nt(t,e,r){var n=kr(e);if(n.deferred=!0,ee(t)){var i=n.state=we(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function pi(t){try{return typeof t.send=="function"}catch{return!1}}function vi(t){return pi(t)&&"id"in t}function gi(t){var e;return v((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[oe]=function(){return this},e),t)}var st=function(t){return t.type==="atomic"||t.type==="final"};function Or(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Ce(t){return Or(t).filter(function(e){return e.type!=="history"})}function Ir(t){var e=[t];return st(t)?e:e.concat(j(Ce(t).map(Ir)))}function De(t,e){var r,n,i,s,o,u,c,h,a=new Set(t),l=Ut(a),d=new Set(e);try{for(var f=k(d),p=f.next();!p.done;p=f.next())for(var m=p.value,w=m.parent;w&&!d.has(w);)d.add(w),w=w.parent}catch(_){r={error:_}}finally{try{p&&!p.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}var S=Ut(d);try{for(var y=k(d),E=y.next();!E.done;E=y.next()){var m=E.value;if(m.type==="compound"&&(!S.get(m)||!S.get(m).length))l.get(m)?l.get(m).forEach(function(T){return d.add(T)}):m.initialStateNodes.forEach(function(T){return d.add(T)});else if(m.type==="parallel")try{for(var U=(o=void 0,k(Ce(m))),O=U.next();!O.done;O=U.next()){var M=O.value;d.has(M)||(d.add(M),l.get(M)?l.get(M).forEach(function(T){return d.add(T)}):M.initialStateNodes.forEach(function(T){return d.add(T)}))}}catch(T){o={error:T}}finally{try{O&&!O.done&&(u=U.return)&&u.call(U)}finally{if(o)throw o.error}}}}catch(_){i={error:_}}finally{try{E&&!E.done&&(s=y.return)&&s.call(y)}finally{if(i)throw i.error}}try{for(var I=k(d),R=I.next();!R.done;R=I.next())for(var m=R.value,w=m.parent;w&&!d.has(w);)d.add(w),w=w.parent}catch(_){c={error:_}}finally{try{R&&!R.done&&(h=I.return)&&h.call(I)}finally{if(c)throw c.error}}return d}function xr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(st(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=xr(s,e)}),i}function Ut(t){var e,r,n=new Map;try{for(var i=k(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function mi(t,e){var r=De([t],e);return xr(t,Ut(r))}function Me(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function yi(t){return C([],A(new Set(j(C([],A(t.map(function(e){return e.ownEvents})),!1)))),!1)}function ot(t,e){return e.type==="compound"?Ce(e).some(function(r){return r.type==="final"&&Me(t,r)}):e.type==="parallel"?Ce(e).every(function(r){return ot(t,r)}):!1}function wi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Rr(t){return new Set(j(t.map(function(e){return e.tags})))}function Pr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(x(t)||x(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Pr(t[i],e[i])})}function Ei(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Si(t,e){var r=t.exec,n=v(v({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var X=function(){function t(e){var r=this,n;this.actions=[],this.activities=sr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||sr,this.meta=wi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return yi(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=he;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=he;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),x(e))return[e];var i=Object.keys(e);return i.concat.apply(i,C([],A(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Tt(e,["configuration","transitions","tags","machine"]);return v(v({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return It(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;L&&$(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),Ti={deferEvents:!1},Nr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=v(v({},Ti),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),_t=new Map,bi=0,at={bookId:function(){return"x:".concat(bi++)},register:function(t,e){return _t.set(t,e),t},get:function(t){return _t.get(t)},free:function(t){_t.delete(t)}};function Ct(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;L||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function Ai(){var t=Ct();if(t&&"__xstate__"in t)return t.__xstate__}function ki(t){if(Ct()){var e=Ai();e&&e.register(t)}}function Oi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var h=i.shift();r=t.transition(r,h,c),n.forEach(function(a){return a.next(r)})}s=!1}},u=gi({id:e.id,send:function(h){i.push(h),o()},getSnapshot:function(){return r},subscribe:function(h,a,l){var d=et(h,a,l);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),c={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(c):r,u}var Dt={sync:!1,autoForward:!1},q;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(q||(q={}));var Ii=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=q.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(a,l){if(ve(a))return n.batch(a),n.state;var d=G(Rt(a,l));if(n.status===q.Stopped)return L||$(!1,'Event "'.concat(d.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
15
|
-
Event: `).concat(JSON.stringify(d.data))),n.state;if(n.status!==
|
|
16
|
-
Event: `).concat(JSON.stringify(d.data)));return n.scheduler.schedule(function(){n.forward(d);var f=n._nextState(d);n.update(f,d)}),n._state},this.sendTo=function(a,
|
|
17
|
-
Event: `).concat(JSON.stringify(event)));else if(this.status!==q.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,u=!1,c=[],h=function(f){var p=G(f);r.forward(p),o=we(r,function(){return r.machine.transition(o,p,void 0,n||void 0)}),c.push.apply(c,C([],A(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(m){return Si(m,o)})),!1)),u=u||!!o.changed};try{for(var a=k(e),l=a.next();!l.done;l=a.next()){var d=l.value;h(d)}}catch(f){i={error:f}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}o.changed=u,o.actions=c,r.update(o,G(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=G(e);if(i.name.indexOf(At)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(At)===0}))throw i.data.data;var s=we(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=k(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,u=this.children.get(o);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));u.send(e)}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==q.Running)return Nt(e,r);if(ur(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(vi(e))return this.spawnActor(e,r);if(Jn(e))return this.spawnObservable(e,r);if(ee(e))return this.spawnMachine(e,v(v({},n),{id:r}));if(Hn(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,v(v({},this.options),{parent:this,id:r.id||e.id})),s=v(v({},Dt),r);s.sync&&i.onTransition(function(u){n.send(Je,{state:u,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(G(u,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Oi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(c){s||(o=c,i.removeChild(r),i.send(G(Ue(r,c),{origin:r})))},function(c){if(!s){i.removeChild(r);var h=ye(r,c);try{i.send(G(h,{origin:r}))}catch(a){Zn(c,a,r),i.devTools&&i.devTools.send(h,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(c,h,a){var l=et(c,h,a),d=!1;return e.then(function(f){d||(l.next(f),!d&&l.complete())},function(f){d||l.error(f)}),{unsubscribe:function(){return d=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[oe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,u=new Set,c,h=function(d){c=d,u.forEach(function(f){return f(d)}),!s&&i.send(G(d,{origin:r}))},a;try{a=e(h,function(d){o.add(d)})}catch(d){this.send(ye(r,d))}if(ur(a))return this.spawnPromise(a,r);var l=(n={id:r,send:function(d){return o.forEach(function(f){return f(d)})},subscribe:function(d){var f=et(d);return u.add(f.next),{unsubscribe:function(){u.delete(f.next)}}},stop:function(){s=!0,N(a)&&a()},toJSON:function(){return{id:r}},getSnapshot:function(){return c}},n[oe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(c){s=c,i.send(G(c,{origin:r}))},function(c){i.removeChild(r),i.send(G(ye(r,c),{origin:r}))},function(){i.removeChild(r),i.send(G(Ue(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(c,h,a){return e.subscribe(c,h,a)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[oe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){L||$(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[oe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Ct();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(v(v({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:v({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}ki(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[oe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===q.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=Ee,t}(),xi=function(t){return x(t)?v(v({},Dt),{name:t}):v(v(v({},Dt),{name:Qn()}),t)};function Ri(t,e){var r=xi(e);return hi(function(n){if(!L){var i=ee(t)||N(t);$(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ee(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):Nt(t,r.name)})}function Ee(t,e){var r=new Ii(t,e);return r}function Pi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ct(t){return v(v({type:We},t),{toJSON:function(){t.onDone,t.onError;var e=Tt(t,["onDone","onError"]);return v(v({},e),{type:We,src:Pi(t.src)})}})}var Se="",Mt="#",Le="*",Te={},be=function(t){return t[0]===Mt},Ni=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Ui=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(x(s.target)||ee(s.target))}),i=e===Se?"the transient event":"event '".concat(e,"'");$(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},_i=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ni(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:ir),this.id=this.config.id||C([this.machine.key],A(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,L||$(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?Pe(this.config.states,function(h,a){var l,d=new t(h,{},void 0,{parent:s,key:a});return Object.assign(s.idMap,v((l={},l[d.id]=d,l),d.idMap)),d}):Te;var u=0;function c(h){var a,l;h.order=u++;try{for(var d=k(Or(h)),f=d.next();!f.done;f=d.next()){var p=f.value;c(p)}}catch(m){a={error:m}}finally{try{f&&!f.done&&(l=d.return)&&l.call(d)}finally{if(a)throw a.error}}}c(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(h){var a=h.event;return a===Se}):Se in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=H(this.config.entry||this.config.onEntry).map(function(h){return me(h)}),this.onExit=H(this.config.exit||this.config.onExit).map(function(h){return me(h)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=H(this.config.invoke).map(function(h,a){var l,d;if(ee(h)){var f=tt(s.id,a);return s.machine.options.services=v((l={},l[f]=h,l),s.machine.options.services),ct({src:f,id:f})}else if(x(h.src)){var f=h.id||tt(s.id,a);return ct(v(v({},h),{id:f,src:h.src}))}else if(ee(h.src)||N(h.src)){var f=h.id||tt(s.id,a);return s.machine.options.services=v((d={},d[f]=h.src,d),s.machine.options.services),ct(v(v({id:f},h),{src:f}))}else{var p=h.src;return ct(v(v({id:tt(s.id,a)},h),{src:p}))}}),this.activities=H(this.config.activities).concat(this.invoke).map(function(h){return nt(h)}),this.transition=this.transition.bind(this),this.tags=H(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Ir(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,u=n.services,c=n.delays;return new t(this.config,{actions:v(v({},i),e.actions),activities:v(v({},s),e.activities),guards:v(v({},o),e.guards),services:v(v({},u),e.services),delays:v(v({},c),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:Pe(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Se,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===Le});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var u=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,c=Ar(u,e.id);return e.onEntry.push(ae(c,{delay:s})),e.onExit.push(wr(c)),c},i=ve(r)?r.map(function(s,o){var u=n(s.delay,o);return v(v({},s),{event:u})}):j(Object.keys(r).map(function(s,o){var u=r[s],c=x(u)?{target:u}:u,h=isNaN(+s)?s:+s,a=n(h,o);return H(c).map(function(l){return v(v({},l),{event:a,delay:h})})}));return i.map(function(s){var o=s.delay;return v(v({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof X?e.value:Re(e,this.delimiter);if(x(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),u=[this];return u.push.apply(u,C([],A(j(o.map(function(c){return n.getStateNode(c).getStateNodes(i[c])}))),!1)),u},t.prototype.handles=function(e){var r=or(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof X?e:X.create(e),n=Array.from(De([],this.getStateNodes(r.value)));return new X(v(v({},r),{value:this.resolve(r.value),configuration:n,done:ot(n,this),tags:Rr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var u=k(Object.keys(e)),c=u.next();!c.done;c=u.next()){var h=c.value,a=e[h];if(a){var l=this.getStateNode(h),d=l._transition(a,r,n);d&&(o[h]=d)}}}catch(y){i={error:y}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(i)throw i.error}}var f=Object.keys(o).map(function(y){return o[y]}),p=j(f.map(function(y){return y.transitions})),m=f.some(function(y){return y.transitions.length>0});if(!m)return this.next(r,n);var w=j(f.map(function(y){return y.entrySet})),S=j(Object.keys(o).map(function(y){return o[y].configuration}));return{transitions:p,entrySet:w,exitSet:j(f.map(function(y){return y.exitSet})),configuration:S,source:r,actions:j(Object.keys(o).map(function(y){return o[y].actions}))}},t.prototype._transition=function(e,r,n){return x(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,G(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,u=[],c=[],h;try{for(var a=k(this.getCandidates(o)),l=a.next();!l.done;l=a.next()){var d=l.value,f=d.cond,p=d.in,m=e.context,w=p?x(p)&&be(p)?e.matches(Re(this.getStateNodeById(p).path,this.delimiter)):It(Re(p,this.delimiter),Vn(this.path.slice(0,-2))(e.value)):!0,S=!1;try{S=!f||fr(this.machine,f,m,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(f.name||f.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
-
`).concat(O.message))}if(S&&w){d.target!==void 0&&(c=d.target),u.push.apply(u,C([],A(d.actions),!1)),h=d;break}}}catch(O){n={error:O}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}if(h){if(!c.length)return{transitions:[h],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var y=j(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),E=!!h.internal,U=[];return E||c.forEach(function(O){U.push.apply(U,C([],A(s.getExternalReentryNodes(O)),!1))}),{transitions:[h],entrySet:U,exitSet:E?[]:[this],configuration:y,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=A(e.order>this.order?[e,this]:[this,e],2),i=n[0],s=n[1];i&&i!==s;)r.push(i),i=i.parent;return i!==s?[]:(r.push(s),r)},t.prototype.getActions=function(e,r,n,i,s,o,u){var c,h,a,l,d=this,f=De([],o?this.getStateNodes(o.value):[this]);try{for(var p=k(e),m=p.next();!m.done;m=p.next()){var w=m.value;(!Me(f,w)||Me(n.entrySet,w.parent))&&n.entrySet.push(w)}}catch(T){c={error:T}}finally{try{m&&!m.done&&(h=p.return)&&h.call(p)}finally{if(c)throw c.error}}try{for(var S=k(f),y=S.next();!y.done;y=S.next()){var w=y.value;(!Me(e,w)||Me(n.exitSet,w.parent))&&n.exitSet.push(w)}}catch(T){a={error:T}}finally{try{y&&!y.done&&(l=S.return)&&l.call(S)}finally{if(a)throw a.error}}var E=j(n.entrySet.map(function(T){var D=[];if(T.type!=="final")return D;var z=T.parent;if(!z.parent)return D;D.push(Ne(T.id,T.doneData),Ne(z.id,T.doneData?Ze(T.doneData,i,s):void 0));var J=z.parent;return J.type==="parallel"&&Ce(J).every(function(se){return ot(n.configuration,se)})&&D.push(Ne(J.id)),D}));n.exitSet.sort(function(T,D){return D.order-T.order}),n.entrySet.sort(function(T,D){return T.order-D.order});var U=new Set(n.entrySet),O=new Set(n.exitSet),M=Array.from(U).map(function(T){var D=T.onEntry,z=T.activities.map(function(J){return Er(J)});return te(u?C(C([],A(D),!1),A(z),!1):C(C([],A(z),!1),A(D),!1),d.machine.options.actions)}).concat([E.map(vr)]),I=Array.from(O).map(function(T){return te(C(C([],A(T.onExit),!1),A(T.activities.map(function(D){return Sr(D)})),!1),d.machine.options.actions)}),R=I.concat([te(n.actions,this.machine.options.actions)]).concat(M);if(r){var _=te(j(C([],A(e),!1).sort(function(T,D){return D.order-T.order}).map(function(T){return T.onExit})),this.machine.options.actions).filter(function(T){return T.type!==le&&(T.type!==de||!!T.to&&T.to!==Q.Internal)});return R.concat([_])}return R},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=G(r),o;if(e instanceof X)o=n===void 0?e:this.resolveState(X.from(e,n));else{var u=x(e)?this.resolve(Qe(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(X.from(u,c))}if(!L&&s.name===Le)throw new Error("An event cannot have the wildcard type ('".concat(Le,"')"));if(this.strict&&!this.events.includes(s.name)&&!zn(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var h=this._transition(o.value,o,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:o,actions:[]},a=De([],this.getStateNodes(o.value)),l=h.configuration.length?De(a,h.configuration):a;return h.configuration=C([],A(l),!1),this.resolveTransition(h,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,C([],A(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,u,c,h,a=this;s===void 0&&(s=he);var l=e.configuration,d=!r||e.transitions.length>0,f=d?e.configuration:r?r.configuration:[],p=ot(f,this),m=d?mi(this.machine,l):void 0,w=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,S=this.getActions(new Set(f),p,e,n,s,r,i),y=r?v({},r.activities):{};try{for(var E=k(S),U=E.next();!U.done;U=E.next()){var O=U.value;try{for(var M=(c=void 0,k(O)),I=M.next();!I.done;I=M.next()){var R=I.value;R.type===Ke?y[R.activity.id||R.activity.type]=R:R.type===ze&&(y[R.activity.id||R.activity.type]=!1)}}catch(K){c={error:K}}finally{try{I&&!I.done&&(h=M.return)&&h.call(M)}finally{if(c)throw c.error}}}}catch(K){o={error:K}}finally{try{U&&!U.done&&(u=E.return)&&u.call(E)}finally{if(o)throw o.error}}var _=A(_e(this,r,n,s,S,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),T=_[0],D=_[1],z=A(Yn(T,function(K){return K.type===le||K.type===de&&K.to===Q.Internal}),2),J=z[0],se=z[1],Oe=T.filter(function(K){var xe;return K.type===Ke&&((xe=K.activity)===null||xe===void 0?void 0:xe.type)===We}),ls=Oe.reduce(function(K,xe){return K[xe.activity.id]=fi(xe.activity,a.machine,D,s),K},r?v({},r.children):{}),Et=new X({value:m||r.value,context:D,_event:s,_sessionid:r?r._sessionid:null,historyValue:m?w?Wn(w,m):void 0:r?r.historyValue:void 0,history:!m||e.source?r:void 0,actions:m?se:[],activities:m?y:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:ls,done:p,tags:Rr(f),machine:this}),_n=n!==D;Et.changed=s.name===Je||_n;var Ie=Et.history;Ie&&delete Ie.history;var Cn=!p&&(this._transient||l.some(function(K){return K._transient}));if(!d&&(!Cn||s.name===Se))return Et;var B=Et;if(!p)for(Cn&&(B=this.resolveRaisedTransition(B,{type:er},s,i));J.length;){var ds=J.shift();B=this.resolveRaisedTransition(B,ds._event,s,i)}var hs=B.changed||(Ie?!!B.actions.length||_n||typeof Ie.value!=typeof B.value||!Pr(B.value,Ie.value):void 0);return B.changed=hs,B.history=Ie,B},t.prototype.getStateNode=function(e){if(be(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=be(e)?e.slice(Mt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&be(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=xt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Te;switch(this.type){case"parallel":return Pe(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Te});case"compound":if(x(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?Pe(e,function(s,o){return s?n.getStateNode(o).resolve(s):Te}):this.initialStateValue||{};default:return e||Te}},t.prototype.getResolvedPath=function(e){if(be(e)){var r=this.machine.idMap[e.slice(Mt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return xt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=ar(this.states,function(n){return n.initialStateValue||Te},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=st(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:C([],A(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;x(r.target)?e=be(r.target)?Qe(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(st(this))return[this];if(this.type==="compound"&&!this.initial)return L||$(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=Xe(this.initialStateValue);return j(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=A(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:ar(this.states,function(r,n){if(!e)return r.historyValue();var i=x(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?j(Xe(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=Kn(n.path,"states")(e).current;return x(s)?[n.getStateNode(s)]:j(Xe(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=j(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var u=k(Object.keys(s)),c=u.next();!c.done;c=u.next()){var h=c.value,a=s[h];if(a.states)try{for(var l=(n=void 0,k(a.events)),d=l.next();!d.done;d=l.next()){var f=d.value;o.add("".concat(f))}}catch(p){n={error:p}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(p){e={error:p}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!x(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(u.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Xn(e.target),i="internal"in e?e.internal:n?n.some(function(c){return x(c)&&c[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),u=v(v({},e),{actions:te(H(e.actions)),cond:hr(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return v(v({},u),{target:u.target?u.target.map(function(c){return"#".concat(c.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=Le,u=s[o],c=u===void 0?[]:u,h=Tt(s,[typeof o=="symbol"?o:o+""]);i=j(Object.keys(h).map(function(y){!L&&y===Se&&$(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var E=ge(y,h[y]);return L||Ui(n,y,E),E}).concat(ge(Le,c)))}var a=this.config.always?ge("",this.config.always):[],l=this.config.onDone?ge(String(Ne(this.id)),this.config.onDone):[];L||$(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=j(this.invoke.map(function(y){var E=[];return y.onDone&&E.push.apply(E,C([],A(ge(String(Ue(y.id)),y.onDone)),!1)),y.onError&&E.push.apply(E,C([],A(ge(String(ye(y.id)),y.onError)),!1)),E})),f=this.after,p=j(C(C(C(C([],A(l),!1),A(d),!1),A(i),!1),A(a),!1).map(function(y){return H(y).map(function(E){return n.formatTransition(E)})}));try{for(var m=k(f),w=m.next();!w.done;w=m.next()){var S=w.value;p.push(S)}}catch(y){e={error:y}}finally{try{w&&!w.done&&(r=m.return)&&r.call(m)}finally{if(e)throw e.error}}return p},t}(),Ur=!1;function ce(t,e){return!L&&!t.predictableActionArguments&&!Ur&&(Ur=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new _i(t,e)}var b=br,F=ae;/*! js-cookie v3.0.1 | MIT */function ut(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var Ci={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Lt(t,e){function r(i,s,o){if(typeof document!="undefined"){o=ut({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var c in o)o[c]&&(u+="; "+c,o[c]!==!0&&(u+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+u}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},u=0;u<s.length;u++){var c=s[u].split("="),h=c.slice(1).join("=");try{var a=decodeURIComponent(c[0]);if(o[a]=t.read(h,a),i===a)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",ut({},s,{expires:-1}))},withAttributes:function(i){return Lt(this.converter,ut({},this.attributes,i))},withConverter:function(i){return Lt(ut({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var jt=Lt(Ci,{path:"/"});function Di(t){var e=t.default;if(typeof e=="function"){var r=function n(){if(this instanceof n){var i=[null];i.push.apply(i,arguments);var s=Function.bind.apply(e,i);return new s}return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}function Mi(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},c=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(a){return u[a.toLowerCase()]},has:function(a){return a.toLowerCase()in u}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,l,d){s.push(l=l.toLowerCase()),o.push([l,d]),u[l]=u[l]?u[l]+","+d:d}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}const _r=Di(Object.freeze(Object.defineProperty({__proto__:null,default:Mi},Symbol.toStringTag,{value:"Module"})));var Ae=self.fetch||(self.fetch=_r.default||_r);const je="nhostRefreshToken",$e="nhostRefreshTokenExpiresAt",Cr=3,Dr=300,$t=5,qt=0,Ft=1,Y=10,ke=20;class qe extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Ft,message:e.message}):(this.name=e.error,this.error=e)}}const re={status:Y,error:"invalid-email",message:"Email is incorrectly formatted"},Mr={status:Y,error:"invalid-mfa-type",message:"MFA type is invalid"},Lr={status:Y,error:"invalid-mfa-code",message:"MFA code is invalid"},lt={status:Y,error:"invalid-password",message:"Password is incorrectly formatted"},Gt={status:Y,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},jr={status:Y,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},$r={status:Y,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},qr={status:Y,error:"no-refresh-token",message:"No refresh token has been provided"},Fr={status:ke,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},Z={status:ke,error:"already-signed-in",message:"User is already signed in"},Gr={status:ke,error:"unauthenticated-user",message:"User is not authenticated"},Li={status:ke,error:"user-not-anonymous",message:"User is not anonymous"},Vr={status:ke,error:"unverified-user",message:"Email needs verification"},Kr={status:Y,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},zr={status:Ft,error:"invalid-sign-in-method",message:"Invalid sign-in method"},dt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function ji(t){return new TextEncoder().encode(t)}function fe(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Vt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let u=0;u<i.length;u++)o[u]=i.charCodeAt(u);return s}function Hr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Yr(t){const{id:e}=t;return{...t,id:Vt(e),transports:t.transports}}function Wr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let V=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function $i({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new V("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new V("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new V("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new V("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new V("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(s=>s.type==="public-key").length===0?new V('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new V("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(Wr(s)){if(i.rp.id!==s)return new V(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new V(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new V("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new V("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class qi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const ht=new qi;async function Jr(t){if(!Hr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Vt(t.challenge),user:{...t.user,id:ji(t.user.id)},excludeCredentials:t.excludeCredentials.map(Yr)}};e.signal=ht.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(c){throw $i({error:c,options:e})}finally{ht.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,u={id:n,rawId:fe(i),response:{attestationObject:fe(s.attestationObject),clientDataJSON:fe(s.clientDataJSON)},type:o,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof s.getTransports=="function"&&(u.transports=s.getTransports()),u}function Fi(t){return new TextDecoder("utf-8").decode(t)}async function Gi(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function Vi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new V("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new V("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new V("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Wr(i)){if(n.rpId!==i)return new V(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new V(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new V("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Ki(t,e=!1){var r,n;if(!Hr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Yr));const s={...t,challenge:Vt(t.challenge),allowCredentials:i},o={};if(e){if(!await Gi())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=ht.createNewAbortSignal();let u;try{u=await navigator.credentials.get(o)}catch(f){throw Vi({error:f,options:o})}finally{ht.reset()}if(!u)throw new Error("Authentication was not completed");const{id:c,rawId:h,response:a,type:l}=u;let d;return a.userHandle&&(d=Fi(a.userHandle)),{id:c,rawId:fe(h),response:{authenticatorData:fe(a.authenticatorData),clientDataJSON:fe(a.clientDataJSON),signature:fe(a.signature),userHandle:d},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const ft=typeof window!="undefined",pt=new Map,zi=t=>{var e;return ft&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=pt.get(t))!=null?e:null},Hi=(t,e)=>{ft&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?pt.set(t,e):pt.has(t)&&pt.delete(t)},Br=(t,e)=>{if(t==="localStorage"||t==="web")return zi;if(t==="cookie")return r=>{var n;return ft&&(n=jt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},Qr=(t,e)=>{if(t==="localStorage"||t==="web")return Hi;if(t==="cookie")return(r,n)=>{ft&&(n?jt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):jt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},Fe=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ue=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},vt=()=>typeof window!="undefined",Xr=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await Ae(t,s);if(!o.ok){const u=await o.json();return Promise.reject({error:u})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:qt,error:"network"};return Promise.reject({error:o})}},ne=async(t,e,r)=>Xr(t,"POST",{token:r,body:e}),Zr=(t,e)=>Xr(t,"GET",{token:e}),Kt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},W=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(o.search);let c=Object.fromEntries(u);r.startsWith("/")&&(c={...s,...c});let h=i.pathname;return o.pathname.length>1&&(h+=o.pathname.slice(1)),{...n,redirectTo:Kt(o.origin+h,c)}};function Ge(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function zt(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const ie=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),gt=t=>!!t&&typeof t=="string"&&t.length>=Cr,Ht=t=>!!t&&typeof t=="string",en=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),tn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const u=Br(r,n),c=Qr(r,n),h=async(a,l,d)=>(await ne(`${t}${a}`,l,d)).data;return ce({schema:{context:{},events:{},services:{}},tsTypes:{},context:dt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:F("SIGNED_IN"),reportSignedOut:F("SIGNED_OUT"),reportTokenChanged:F("TOKEN_CHANGED"),incrementTokenImportAttempts:b({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:b(()=>(c($e,null),c(je,null),{...dt})),clearContextExceptRefreshToken:b(({refreshToken:{value:a}})=>(c($e,null),{...dt,refreshToken:{value:a}})),saveSession:b({user:(a,{data:l})=>{var d;return((d=l==null?void 0:l.session)==null?void 0:d.user)||null},accessToken:(a,{data:l})=>{if(l.session){const{accessTokenExpiresIn:d,accessToken:f}=l.session,p=new Date(Date.now()+d*1e3);return c($e,p.toISOString()),{value:f,expiresAt:p}}return c($e,null),{value:null,expiresAt:null}},refreshToken:(a,{data:l})=>{var d;const f=((d=l.session)==null?void 0:d.refreshToken)||null;return f&&c(je,f),{value:f}}}),saveMfaTicket:b({mfa:(a,l)=>{var d;return(d=l.data)==null?void 0:d.mfa}}),resetTimer:b({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:b({refreshTimer:(a,l)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:b({errors:({errors:a},{data:{error:l}})=>({...a,authentication:l})}),resetErrors:b({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:b({errors:({errors:a},{data:{error:l}})=>({...a,registration:l})}),destroyRefreshToken:b({refreshToken:a=>(c(je,null),{value:null})}),cleanUrl:()=>{o&&Ge("refreshToken")&&(zt("refreshToken"),zt("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage(a.refreshToken.value)}catch{}}},guards:{isAnonymous:(a,l)=>{var d;return!!((d=a.user)!=null&&d.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.refreshToken.value&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:l}=a.accessToken;return l?a.refreshTimer.lastAttempt?a.refreshTimer.attempts>$t?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3:i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Dr<=0:!1},shouldRetryImportToken:(a,l)=>a.importTokenAttempts<$t&&(l.data.error.status===qt||l.data.error.status>=500),unverified:(a,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(a,l)=>{var d;return!!((d=l.data)!=null&&d.session)},hasMfaTicket:(a,l)=>{var d;return!!((d=l.data)!=null&&d.mfa)}},services:{signInPassword:(a,{email:l,password:d})=>ie(l)?gt(d)?h("/signin/email-password",{email:l,password:d}):Promise.reject({error:lt}):Promise.reject({error:re}),passwordlessSms:(a,{phoneNumber:l,options:d})=>{var f;return Ht(l)?(f=a.user)!=null&&f.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:W(e,d)},a.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:l,options:W(e,d)}):Promise.reject({error:Gt})},passwordlessSmsOtp:(a,{phoneNumber:l,otp:d})=>Ht(l)?h("/signin/passwordless/sms/otp",{phoneNumber:l,otp:d}):Promise.reject({error:Gt}),passwordlessEmail:(a,{email:l,options:d})=>{var f;return ie(l)?(f=a.user)!=null&&f.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:W(e,d)},a.accessToken.value):h("/signin/passwordless/email",{email:l,options:W(e,d)}):Promise.reject({error:re})},signInAnonymous:a=>h("/signin/anonymous"),signInMfaTotp:(a,l)=>{var d;const f=l.ticket||((d=a.mfa)==null?void 0:d.ticket);return f?en(f)?h("/signin/mfa/totp",{ticket:f,otp:l.otp}):Promise.reject({error:jr}):Promise.reject({error:$r})},signInSecurityKeyEmail:async(a,{email:l})=>{if(!ie(l))throw new qe(re);const d=await h("/signin/webauthn",{email:l});let f;try{f=await Ki(d)}catch(p){throw new qe(p)}return h("/signin/webauthn/verify",{email:l,credential:f})},refreshToken:async(a,l)=>{const d=l.type==="TRY_TOKEN"?l.token:a.refreshToken.value;return{session:await h("/token",{refreshToken:d}),error:null}},signout:(a,l)=>h("/signout",{refreshToken:a.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(a,{email:l,password:d,options:f})=>{var p;return ie(l)?gt(d)?(p=a.user)!=null&&p.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:l,password:d,options:W(e,f)},a.accessToken.value):h("/signup/email-password",{email:l,password:d,options:W(e,f)}):Promise.reject({error:lt}):Promise.reject({error:re})},signUpSecurityKey:async(a,{email:l,options:d})=>{if(!ie(l))return Promise.reject({error:re});const f=d==null?void 0:d.nickname;f&&delete d.nickname;const p=await h("/signup/webauthn",{email:l,options:d});let m;try{m=await Jr(p)}catch(w){throw new qe(w)}return h("/signup/webauthn/verify",{credential:m,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:f}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let l=null;if(o){const f=Ge("refreshToken")||null;if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(p){l=p.error}else{const p=Ge("error");if(p)return Promise.reject({session:null,error:{status:Y,error:p,message:Ge("errorDescription")||p}})}}const d=await u(je);if(d)try{return{session:await h("/token",{refreshToken:d}),error:null}}catch(f){l=f.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},rn=({backendUrl:t,clientUrl:e,interpreter:r})=>ce({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:n=>re}),saveRequestError:b({error:(n,{data:{error:i}})=>i}),reportError:F(n=>({type:"ERROR",error:n.error})),reportSuccess:F("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ie(i)},services:{requestChange:async(n,{email:i,options:s})=>(await ne(`${t}/user/email/change`,{newEmail:i,options:W(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),nn=({backendUrl:t,interpreter:e})=>ce({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:b({error:r=>lt}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:F(r=>({type:"ERROR",error:r.error})),reportSuccess:F("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!gt(n)},services:{requestChange:(r,{password:n,ticket:i})=>ne(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Yi=({backendUrl:t,interpreter:e})=>ce({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:b({error:r=>Mr}),saveInvalidMfaCodeError:b({error:r=>Lr}),saveError:b({error:(r,{data:{error:n}})=>n}),saveGeneration:b({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:F((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:F("SUCCESS"),reportGeneratedSuccess:F("GENERATED"),reportGeneratedError:F(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await Zr(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>ne(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),sn=({backendUrl:t,clientUrl:e})=>ce({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:r=>re}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:F(r=>({type:"ERROR",error:r.error})),reportSuccess:F("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ie(n)},services:{requestChange:(r,{email:n,options:i})=>ne(`${t}/user/password/reset`,{email:n,options:W(e,i)})}}),on=({backendUrl:t,clientUrl:e})=>ce({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:r=>re}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:F(r=>({type:"ERROR",error:r.error})),reportSuccess:F("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ie(n)},services:{request:async(r,{email:n,options:i})=>(await ne(`${t}/user/email/send-verification-email`,{email:n,options:W(e,i)})).data}});class Yt{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:u,...c}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=tn({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",h=>{var a;const l=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&h.data!==l&&this.interpreter.send("TRY_TOKEN",{token:h.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||Ee(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class an extends Yt{constructor({...e}){super({...e,autoSignIn:vt()&&e.autoSignIn,autoRefreshToken:vt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Wi=an,cn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await ne("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await Jr(n)}catch(o){throw new qe(o)}const{data:s}=await ne(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},un=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),ln=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Ji=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),Bi=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),dn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),hn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),fn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:Z,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),pn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,error:Z,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),Wt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:Z,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),vn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:Z,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),gn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,error:Z,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Jt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:Z,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),mn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:Z,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),yn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:Gr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),Bt=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:Z,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:Z,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})});class En{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:u=!0}){var c;this.url=e,this._client=new Yt({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ue(await wn(r,n,i)):ue(await Bt(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await fn(r);return{...ue(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=Kt(`${this._client.backendUrl}/signin/provider/${n}`,W(this._client.clientUrl,i));return vt()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await pn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Vr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ue(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await vn(r,e.email);return{...ue(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await Wt(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await mn(r,e.phoneNumber,e.otp);return{...ue(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Jt(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await gn(r,e.otp,e.ticket);return{...ue(n),mfa:null}}return{error:zr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await yn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=Ee(sn(this._client)).start(),{error:i}=await dn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=Ee(nn(this._client)).start(),{error:i}=await ln(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=Ee(on(this._client)).start(),{error:i}=await hn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=Ee(rn(this._client)).start(),{error:i}=await un(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Wt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await Jt(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await Bt(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await cn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(Fe(s))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,Fe(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Mn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:qr});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:Fr});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:Kr}):o.event.type==="TOKEN_CHANGED"&&n({session:Fe(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return Fe((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Sn=typeof self=="object"?self.FormData:window.FormData;const Qi=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},Tn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u}={})=>{const c={};i&&(c["x-nhost-file-id"]=i),s&&(c["x-nhost-bucket-id"]=s),n&&(c["x-nhost-file-name"]=Qi(n)),o&&(c["x-hasura-admin-secret"]=o),r&&(c.Authorization=`Bearer ${r}`);const h=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{const a=await Ae(h,{method:"POST",headers:c,body:e});return a.ok?{fileMetadata:await a.json(),error:null}:{error:{status:a.status,message:await a.text(),error:a.statusText},fileMetadata:null}}catch(a){return{error:{status:0,message:a.message,error:a.message},fileMetadata:null}}return new Promise(a=>{let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?a({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):a({fileMetadata:l.response,error:null}),l.onerror=()=>a({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),u&&l.upload.addEventListener("progress",u,!1),l.open("POST",h,!0),Object.entries(c).forEach(([d,f])=>{l.setRequestHeader(d,f)}),l.send(e)})};class bn{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return Tn(this.url,r,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await Ae(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await Ae(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}function Qt(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}class An{constructor({url:e,adminSecret:r}){this.url=e,this.api=new bn({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new Sn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Qt(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,...n}=e,{presignedUrl:i,error:s}=await this.api.getPresignedUrl(e);if(s)return{presignedUrl:null,error:s};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const o=Qt(i.url,n);return{presignedUrl:{...i,url:o},error:null}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const mt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},kn=()=>ce({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...mt},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:b({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:b({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:b({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:b({progress:t=>null,loaded:t=>0}),resetContext:b(t=>mt),addFile:b({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new Sn;i.append("file",n);let s=0;return Tn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o){const{id:c,bucketId:h}=o;r({type:"UPLOAD_DONE",id:c,bucketId:h})}}),()=>{}}}}),{pure:Xt,sendParent:yt}=di,Xi=()=>ce({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:b((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:b({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:b({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:b({loaded:t=>0}),startProgress:b({progress:t=>0}),resetProgress:b({progress:t=>null}),addItem:b((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,u)=>o+u.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Ri(kn().withConfig({actions:{sendProgress:yt((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:yt("UPLOAD_DONE"),sendError:yt("UPLOAD_ERROR"),sendDestroy:yt("REMOVE")}}).withContext({...mt,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:b({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:Xt(t=>t.files.map(e=>F({type:"DESTROY"},{to:e.id}))),upload:Xt((t,e)=>t.files.map(r=>F(e,{to:r.id}))),cancel:Xt(t=>t.files.map(e=>F({type:"CANCEL"},{to:e.id})))}}),Zi=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),es=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ts=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function wt(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const s=n.match(ts);if(s!=null&&s.groups){const{protocol:o,host:u,port:c}=s.groups,h=is(e);return h||(u==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${o||"http"}://localhost:${c||1337}/v1/${e}`):c?`${o||"https"}://local.${e}.nhost.run:${c}/v1`:`${o||"https"}://local.${e}.nhost.run/v1`)}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${n}.${e}.${i}.nhost.run/v1`}function rs(){return typeof window!="undefined"}function ns(){return typeof process!="undefined"&&process.env}function is(t){return rs()||!ns()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function ss(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function On(t){const e="subdomain"in t||"backendUrl"in t?wt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new En({url:e,...t})}function In(t){const e="subdomain"in t||"backendUrl"in t?wt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new xn({url:e,...t})}class xn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,u;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s=ss(this.url,e);try{const c=await Ae(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let h;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?h=await c.json():h=await c.text(),{res:{data:h,status:c.status,statusText:c.statusText},error:null}}catch(c){const h=c;return{res:null,error:{message:h.message,status:h.name==="AbortError"?0:500,error:h.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function os(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Rn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function as(t){if(typeof t=="string"){let r;try{const n=pe.parse(t);r=Rn(n)}catch{}return{query:t,operationName:r}}const e=Rn(t);return{query:pe.print(t),operationName:e}}class cs{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=os(e,n,i),{headers:o,...u}=i||{},{query:c,operationName:h}=as(s.document);try{const a=await Ae(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...o},...u});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:l,errors:d}=await a.json();return d?{data:null,error:d}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(a){const l=a;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Pn(t){const e="subdomain"in t||"backendUrl"in t?wt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new cs({url:e,...t})}function Nn(t){const e="subdomain"in t||"backendUrl"in t?wt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new An({url:e,...t})}const us=t=>new Un(t);class Un{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...h}){this.auth=On({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...h}),this.storage=Nn({adminSecret:o,...h}),this.functions=In({adminSecret:o,...h}),this.graphql=Pn({adminSecret:o,...h}),this.auth.onAuthStateChanged((a,l)=>{a==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(a=>{const l=a==null?void 0:a.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Yt,g.AuthClientSSR=Wi,g.AuthCookieClient=an,g.CodifiedError=qe,g.EMAIL_NEEDS_VERIFICATION=Vr,g.HasuraAuthClient=En,g.HasuraStorageApi=bn,g.HasuraStorageClient=An,g.INITIAL_FILE_CONTEXT=mt,g.INITIAL_MACHINE_CONTEXT=dt,g.INVALID_EMAIL_ERROR=re,g.INVALID_MFA_CODE_ERROR=Lr,g.INVALID_MFA_TICKET_ERROR=jr,g.INVALID_MFA_TYPE_ERROR=Mr,g.INVALID_PASSWORD_ERROR=lt,g.INVALID_PHONE_NUMBER_ERROR=Gt,g.INVALID_REFRESH_TOKEN=Kr,g.INVALID_SIGN_IN_METHOD=zr,g.MIN_PASSWORD_LENGTH=Cr,g.NETWORK_ERROR_CODE=qt,g.NHOST_JWT_EXPIRES_AT_KEY=$e,g.NHOST_REFRESH_TOKEN_KEY=je,g.NO_MFA_TICKET_ERROR=$r,g.NO_REFRESH_TOKEN=qr,g.NhostClient=Un,g.NhostFunctionsClient=xn,g.OTHER_ERROR_CODE=Ft,g.REFRESH_TOKEN_MAX_ATTEMPTS=$t,g.STATE_ERROR_CODE=ke,g.TOKEN_REFRESHER_RUNNING_ERROR=Fr,g.TOKEN_REFRESH_MARGIN=Dr,g.USER_ALREADY_SIGNED_IN=Z,g.USER_NOT_ANONYMOUS=Li,g.USER_UNAUTHENTICATED=Gr,g.VALIDATION_ERROR_CODE=Y,g.activateMfaPromise=Bi,g.addSecurityKeyPromise=cn,g.appendImageTransformationParameters=Qt,g.changeEmailPromise=un,g.changePasswordPromise=ln,g.createAuthClient=On,g.createAuthMachine=tn,g.createChangeEmailMachine=rn,g.createChangePasswordMachine=nn,g.createEnableMfaMachine=Yi,g.createFileUploadMachine=kn,g.createFunctionsClient=In,g.createGraphqlClient=Pn,g.createMultipleFilesUploadMachine=Xi,g.createNhostClient=us,g.createResetPasswordMachine=sn,g.createSendVerificationEmailMachine=on,g.createStorageClient=Nn,g.encodeQueryParameters=Kt,g.generateQrCodePromise=Ji,g.getAuthenticationResult=ue,g.getFetch=Zr,g.getParameterByName=Ge,g.getSession=Fe,g.isBrowser=vt,g.isValidEmail=ie,g.isValidPassword=gt,g.isValidPhoneNumber=Ht,g.isValidTicket=en,g.localStorageGetter=Br,g.localStorageSetter=Qr,g.postFetch=ne,g.removeParameterFromWindow=zt,g.resetPasswordPromise=dn,g.rewriteRedirectTo=W,g.sendVerificationEmailPromise=hn,g.signInAnonymousPromise=fn,g.signInEmailPasswordPromise=pn,g.signInEmailPasswordlessPromise=Wt,g.signInEmailSecurityKeyPromise=vn,g.signInMfaTotpPromise=gn,g.signInSmsPasswordlessOtpPromise=mn,g.signInSmsPasswordlessPromise=Jt,g.signOutPromise=yn,g.signUpEmailPasswordPromise=Bt,g.signUpEmailSecurityKeyPromise=wn,g.uploadFilePromise=Zi,g.uploadMultipleFilesPromise=es,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
14
|
+
***************************************************************************** */var g=function(){return g=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},g.apply(this,arguments)};function bt(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function k(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function A(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){o={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function C(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var P;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(P||(P={}));var X;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(X||(X={}));var ze=P.Start,He=P.Stop,le=P.Raise,de=P.Send,At=P.Cancel,tr=P.NullEvent,Ye=P.Assign,Fn=P.After,qn=P.DoneState,We=P.Log,rr=P.Init,Je=P.Invoke,Gn=P.ErrorExecution,kt=P.ErrorPlatform,Ot=P.ErrorCustom,Be=P.Update,nr=P.Choose,ir=P.Pure;const Vn=Object.freeze(Object.defineProperty({__proto__:null,after:Fn,assign:Ye,cancel:At,choose:nr,doneState:qn,error:Ot,errorExecution:Gn,errorPlatform:kt,init:rr,invoke:Je,log:We,nullEvent:tr,pure:ir,raise:le,send:de,start:ze,stop:He,update:Be},Symbol.toStringTag,{value:"Module"}));var sr=".",or={},It="xstate.guard",Kn="",L=process.env.NODE_ENV==="production",Qe;function xt(t,e,r){r===void 0&&(r=sr);var n=Ne(t,r),i=Ne(e,r);return x(i)?x(n)?i===n:!1:x(n)?n in i:Object.keys(n).every(function(s){return s in i?xt(n[s],i[s]):!1})}function ar(t){try{return x(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Rt(t,e){try{return ge(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function zn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Ne(t,e){if(zn(t))return t.value;if(ge(t))return Xe(t);if(typeof t!="string")return t;var r=Rt(t,e);return Xe(r)}function Xe(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function _e(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function cr(t,e,r){var n,i,s={};try{for(var o=k(Object.keys(t)),l=o.next();!l.done;l=o.next()){var c=l.value,h=t[c];r(h)&&(s[c]=e(h,c,t))}}catch(a){n={error:a}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var Hn=function(t){return function(e){var r,n,i=e;try{for(var s=k(t),o=s.next();!o.done;o=s.next()){var l=o.value;i=i[l]}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function Yn(t,e){return function(r){var n,i,s=r;try{for(var o=k(t),l=o.next();!l.done;l=o.next()){var c=l.value;s=s[e][c]}}catch(h){n={error:h}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function Ze(t){if(!t)return[[]];if(x(t))return[[t]];var e=j(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:Ze(t[r]).map(function(i){return[r].concat(i)})}));return e}function j(t){var e;return(e=[]).concat.apply(e,C([],A(t),!1))}function ur(t){return ge(t)?t:[t]}function H(t){return t===void 0?[]:ur(t)}function et(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=k(Object.keys(t)),l=o.next();!l.done;l=o.next()){var c=l.value,h=t[c];N(h)?s[c]=h(e,r.data):s[c]=h}}catch(a){n={error:a}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function Wn(t){return/^(done|error)\./.test(t)}function lr(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function Jn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Bn(t,e){var r,n,i=A([[],[]],2),s=i[0],o=i[1];try{for(var l=k(t),c=l.next();!c.done;c=l.next()){var h=c.value;e(h)?s.push(h):o.push(h)}}catch(a){r={error:a}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}return[s,o]}function dr(t,e){return _e(t.states,function(r,n){if(r){var i=(x(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:dr(r,i)}}})}function Qn(t,e){return{current:e,states:dr(t,e)}}function hr(t,e,r,n){L||$(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var l,c,h=o.assignment,a={state:n,action:o,_event:e},u={};if(N(h))u=h(s,e.data,a);else try{for(var d=k(Object.keys(h)),f=d.next();!f.done;f=d.next()){var p=f.value,m=h[p];u[p]=N(m)?m(s,e.data,a):m}}catch(w){l={error:w}}finally{try{f&&!f.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}return Object.assign({},s,u)},t);return i}var $=function(){};L||($=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function ge(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function x(t){return typeof t=="string"}function fr(t,e){if(t)return x(t)?{type:It,name:t,predicate:e?e[t]:void 0}:N(t)?{type:It,name:t.name,predicate:t}:t}function Xn(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var ae=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();Qe={},Qe[ae]=function(){return this},Qe[Symbol.observable]=function(){return this};function te(t){return!!t&&"__xstatenode"in t}function Zn(t){return!!t&&typeof t.send=="function"}var ei=function(){var t=0;return function(){return t++,t.toString(16)}}();function Pt(t,e){return x(t)||typeof t=="number"?g({type:t},e):t}function G(t,e){if(!x(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Pt(t);return g({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function me(t,e){var r=ur(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||te(n)?{target:n,event:t}:g(g({},n),{event:t})});return r}function ti(t){if(!(t===void 0||t===Kn))return H(t)}function ri(t,e,r){if(!L){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function pr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===It)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var l=s==null?void 0:s[e.type];if(!l)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return l(r,n.data,o)}function vr(t){return typeof t=="string"?{type:t}:t}function tt(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function rt(t,e){return"".concat(t,":invocation[").concat(e,"]")}var he=G({type:rr});function nt(t,e){return e&&e[t]||void 0}function ye(t,e){var r;if(x(t)||typeof t=="number"){var n=nt(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=nt(t.type,e);if(N(n))r=g(g({},t),{exec:n});else if(n){var i=n.type||t.type;r=g(g(g({},n),t),{type:i})}else r=t}return r}var re=function(t,e){if(!t)return[];var r=ge(t)?t:[t];return r.map(function(n){return ye(n,e)})};function it(t){var e=ye(t);return g(g({id:x(t)?t:e.id},e),{type:e.type})}function gr(t){return x(t)?{type:le,event:t}:ce(t,{to:X.Internal})}function mr(t){return{type:le,_event:G(t.event)}}function ce(t,e){return{to:e?e.to:void 0,type:de,event:N(t)?t:Pt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:ar(t)}}function yr(t,e,r,n){var i={_event:r},s=G(N(t.event)?t.event(e,r.data,i):t.event),o;if(x(t.delay)){var l=n&&n[t.delay];o=N(l)?l(e,r.data,i):l}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var c=N(t.to)?t.to(e,r.data,i):t.to;return g(g({},t),{to:c,_event:s,event:s.data,delay:o})}function Nt(t,e){return ce(t,g(g({},e),{to:X.Parent}))}function ni(t,e,r){return ce(e,g(g({},r),{to:t}))}function ii(){return Nt(Be)}function si(t,e){return ce(t,g(g({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var oi=function(t,e){return{context:t,event:e}};function ai(t,e){return t===void 0&&(t=oi),{type:We,label:e,expr:t}}var wr=function(t,e,r){return g(g({},t),{value:x(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Er=function(t){return{type:At,sendId:t}};function Sr(t){var e=it(t);return{type:P.Start,activity:e,exec:void 0}}function Tr(t){var e=N(t)?t:it(t);return{type:P.Stop,activity:e,exec:void 0}}function br(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:P.Stop,activity:i};return s}var Ar=function(t){return{type:Ye,assignment:t}};function ci(t){return typeof t=="object"&&"type"in t}function kr(t,e){var r=e?"#".concat(e):"";return"".concat(P.After,"(").concat(t,")").concat(r)}function Ue(t,e){var r="".concat(P.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Ce(t,e){var r="".concat(P.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function we(t,e){var r="".concat(P.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function ui(t){return{type:P.Pure,get:t}}function li(t,e){if(!L&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var s=typeof r=="function"?r.apply(void 0,C([],A(n),!1)):r;if(!s)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return s}}return ce(function(n,i){return i},g(g({},e),{to:t}))}function di(t,e){return Nt(function(r,n,i){return{type:Ot,data:N(t)?t(r,n,i):t}},g(g({},e),{to:X.Parent}))}function hi(t){return{type:P.Choose,conds:t}}var fi=function(t){var e,r,n=[];try{for(var i=k(t),s=i.next();!s.done;s=i.next())for(var o=s.value,l=0;l<o.length;){if(o[l].type===Ye){n.push(o[l]),o.splice(l,1);continue}l++}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function De(t,e,r,n,i,s,o){o===void 0&&(o=!1);var l=o?[]:fi(i),c=l.length?hr(r,n,l,e):r,h=o?[r]:void 0,a=[];function u(p){var m;switch(p.type){case le:return mr(p);case de:var w=yr(p,c,n,t.options.delays);return L||$(!x(p.delay)||typeof w.delay=="number","No delay reference for delay expression '".concat(p.delay,"' was found on machine '").concat(t.id,"'")),s&&w.to!==X.Internal&&a.push(w),w;case We:{var S=wr(p,c,n);return s==null||s(S,c,n),S}case nr:{var y=p,E=(m=y.conds.find(function(B){var oe=fr(B.cond,t.options.guards);return!oe||pr(t,oe,c,n,s?void 0:e)}))===null||m===void 0?void 0:m.actions;if(!E)return[];var _=A(De(t,e,c,n,[re(H(E),t.options.actions)],s,o),2),O=_[0],M=_[1];return c=M,h==null||h.push(c),O}case ir:{var E=p.get(c,n.data);if(!E)return[];var I=A(De(t,e,c,n,[re(H(E),t.options.actions)],s,o),2),R=I[0],U=I[1];return c=U,h==null||h.push(c),R}case He:{var S=br(p,c,n);return s==null||s(S,r,n),S}case Ye:{c=hr(c,n,[p],s?void 0:e),h==null||h.push(c);break}default:var T=ye(p,t.options.actions),D=T.exec;if(s)s(T,c,n);else if(D&&h){var z=h.length-1;T=g(g({},T),{exec:function(B){for(var oe=[],xe=1;xe<arguments.length;xe++)oe[xe-1]=arguments[xe];D.apply(void 0,C([h[z]],A(oe),!1))}})}return T}}function d(p){var m,w,S=[];try{for(var y=k(p),E=y.next();!E.done;E=y.next()){var _=E.value,O=u(_);O&&(S=S.concat(O))}}catch(M){m={error:M}}finally{try{E&&!E.done&&(w=y.return)&&w.call(y)}finally{if(m)throw m.error}}return a.forEach(function(M){s(M,c,n)}),a.length=0,S}var f=j(i.map(d));return[f,c]}const pi=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:Vn,after:kr,assign:Ar,cancel:Er,choose:hi,done:Ue,doneInvoke:Ce,error:we,escalate:di,forwardTo:li,getActionFunction:nt,initEvent:he,isActionObject:ci,log:ai,pure:ui,raise:gr,resolveActions:De,resolveLog:wr,resolveRaise:mr,resolveSend:yr,resolveStop:br,respond:si,send:ce,sendParent:Nt,sendTo:ni,sendUpdate:ii,start:Sr,stop:Tr,toActionObject:ye,toActionObjects:re,toActivityDefinition:it},Symbol.toStringTag,{value:"Module"}));var st=[],Ee=function(t,e){st.push(t);var r=e(t);return st.pop(),r},vi=function(t){return t(st[st.length-1])};function Or(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[ae]=function(){return this},e}function gi(t,e,r,n){var i,s=vr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],l=t.data?et(t.data,r,n):void 0,c=o?_t(o,t.id,l):Or(t.id);return c.meta=t,c}function _t(t,e,r){var n=Or(e);if(n.deferred=!0,te(t)){var i=n.state=Ee(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function mi(t){try{return typeof t.send=="function"}catch{return!1}}function yi(t){return mi(t)&&"id"in t}function wi(t){var e;return g((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[ae]=function(){return this},e),t)}var ot=function(t){return t.type==="atomic"||t.type==="final"};function Ir(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Me(t){return Ir(t).filter(function(e){return e.type!=="history"})}function xr(t){var e=[t];return ot(t)?e:e.concat(j(Me(t).map(xr)))}function Le(t,e){var r,n,i,s,o,l,c,h,a=new Set(t),u=Ut(a),d=new Set(e);try{for(var f=k(d),p=f.next();!p.done;p=f.next())for(var m=p.value,w=m.parent;w&&!d.has(w);)d.add(w),w=w.parent}catch(U){r={error:U}}finally{try{p&&!p.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}var S=Ut(d);try{for(var y=k(d),E=y.next();!E.done;E=y.next()){var m=E.value;if(m.type==="compound"&&(!S.get(m)||!S.get(m).length))u.get(m)?u.get(m).forEach(function(T){return d.add(T)}):m.initialStateNodes.forEach(function(T){return d.add(T)});else if(m.type==="parallel")try{for(var _=(o=void 0,k(Me(m))),O=_.next();!O.done;O=_.next()){var M=O.value;d.has(M)||(d.add(M),u.get(M)?u.get(M).forEach(function(T){return d.add(T)}):M.initialStateNodes.forEach(function(T){return d.add(T)}))}}catch(T){o={error:T}}finally{try{O&&!O.done&&(l=_.return)&&l.call(_)}finally{if(o)throw o.error}}}}catch(U){i={error:U}}finally{try{E&&!E.done&&(s=y.return)&&s.call(y)}finally{if(i)throw i.error}}try{for(var I=k(d),R=I.next();!R.done;R=I.next())for(var m=R.value,w=m.parent;w&&!d.has(w);)d.add(w),w=w.parent}catch(U){c={error:U}}finally{try{R&&!R.done&&(h=I.return)&&h.call(I)}finally{if(c)throw c.error}}return d}function Rr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(ot(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Rr(s,e)}),i}function Ut(t){var e,r,n=new Map;try{for(var i=k(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(l){e={error:l}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Ei(t,e){var r=Le([t],e);return Rr(t,Ut(r))}function je(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Si(t){return C([],A(new Set(j(C([],A(t.map(function(e){return e.ownEvents})),!1)))),!1)}function at(t,e){return e.type==="compound"?Me(e).some(function(r){return r.type==="final"&&je(t,r)}):e.type==="parallel"?Me(e).every(function(r){return at(t,r)}):!1}function Ti(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Pr(t){return new Set(j(t.map(function(e){return e.tags})))}function Nr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(x(t)||x(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Nr(t[i],e[i])})}function bi(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Ai(t,e){var r=t.exec,n=g(g({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var Z=function(){function t(e){var r=this,n;this.actions=[],this.activities=or,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||or,this.meta=Ti(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Si(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=he;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=he;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),x(e))return[e];var i=Object.keys(e);return i.concat.apply(i,C([],A(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=bt(e,["configuration","transitions","tags","machine"]);return g(g({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return xt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;L&&$(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),ki={deferEvents:!1},_r=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=g(g({},ki),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),Ct=new Map,Oi=0,ct={bookId:function(){return"x:".concat(Oi++)},register:function(t,e){return Ct.set(t,e),t},get:function(t){return Ct.get(t)},free:function(t){Ct.delete(t)}};function Dt(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;L||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function Ii(){var t=Dt();if(t&&"__xstate__"in t)return t.__xstate__}function xi(t){if(Dt()){var e=Ii();e&&e.register(t)}}function Ri(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var h=i.shift();r=t.transition(r,h,c),n.forEach(function(a){return a.next(r)})}s=!1}},l=wi({id:e.id,send:function(h){i.push(h),o()},getSnapshot:function(){return r},subscribe:function(h,a,u){var d=tt(h,a,u);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),c={parent:e.parent,self:l,id:e.id||"anonymous",observers:n};return r=t.start?t.start(c):r,l}var Mt={sync:!1,autoForward:!1},F;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(F||(F={}));var Pi=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=F.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(a,u){if(ge(a))return n.batch(a),n.state;var d=G(Pt(a,u));if(n.status===F.Stopped)return L||$(!1,'Event "'.concat(d.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
15
|
+
Event: `).concat(JSON.stringify(d.data))),n.state;if(n.status!==F.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(d.name,'" was sent to uninitialized service "').concat(n.machine.id,`". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.
|
|
16
|
+
Event: `).concat(JSON.stringify(d.data)));return n.scheduler.schedule(function(){n.forward(d);var f=n._nextState(d);n.update(f,d)}),n._state},this.sendTo=function(a,u,d){var f=n.parent&&(u===X.Parent||n.parent.id===u),p=f?n.parent:x(u)?n.children.get(u)||ct.get(u):Zn(u)?u:void 0;if(!p){if(!f)throw new Error("Unable to send event to child '".concat(u,"' from service '").concat(n.id,"'."));L||$(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(a.type));return}if("machine"in p){if(n.status!==F.Stopped||n.parent!==p||n.state.done){var m=g(g({},a),{name:a.name===Ot?"".concat(we(n.id)):a.name,origin:n.sessionId});!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([p,m]):p.send(m)}}else!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([p,a.data]):p.send(a.data)},this._exec=function(a,u,d,f){f===void 0&&(f=n.machine.options.actions);var p=a.exec||nt(a.type,f),m=N(p)?p:p?p.exec:a.exec;if(m)try{return m(u,d.data,n.machine.config.predictableActionArguments?{action:a,_event:d}:{action:a,state:n.state,_event:d})}catch(z){throw n.parent&&n.parent.send({type:"xstate.error",data:z}),z}switch(a.type){case de:var w=a;if(typeof w.delay=="number"){n.defer(w);return}else w.to?n.sendTo(w._event,w.to,d===he):n.send(w._event);break;case At:n.cancel(a.sendId);break;case ze:{if(n.status!==F.Running)return;var S=a.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[S.id||S.type])break;if(S.type===P.Invoke){var y=vr(S.src),E=n.machine.options.services?n.machine.options.services[y.type]:void 0,_=S.id,O=S.data;L||$(!("forward"in S),"`forward` property is deprecated (found in invocation of '".concat(S.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var M="autoForward"in S?S.autoForward:!!S.forward;if(!E){L||$(!1,"No service found for invocation '".concat(S.src,"' in machine '").concat(n.machine.id,"'."));return}var I=O?et(O,u,d):void 0;if(typeof E=="string")return;var R=N(E)?E(u,d.data,{data:I,src:y,meta:S.meta}):E;if(!R)return;var U=void 0;te(R)&&(R=I?R.withContext(I):R,U={autoForward:M}),n.spawn(R,_,U)}else n.spawnActivity(S);break}case He:{n.stopChild(a.activity.id);break}case We:var T=a.label,D=a.value;T?n.logger(T,D):n.logger(D);break;default:L||$(!1,"No implementation found for action type '".concat(a.type,"'"));break}};var i=g(g({},t.defaultOptions),r),s=i.clock,o=i.logger,l=i.parent,c=i.id,h=c!==void 0?c:e.id;this.id=h,this.logger=o,this.clock=s,this.parent=l,this.options=i,this.scheduler=new _r({deferEvents:this.options.deferEvents}),this.sessionId=ct.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:Ee(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return L||$(this.status!==F.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var s=k(e.actions),o=s.next();!o.done;o=s.next()){var l=o.value;this.exec(l,e,r)}}catch(c){n={error:c}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,o,l,c,h,a,u=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===he)&&this.options.execute)this.execute(this.state);else for(var d=void 0;d=this._outgoingQueue.shift();)d[0].send(d[1]);if(this.children.forEach(function(U){u.state.children[U.id]=U}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var f=k(this.eventListeners),p=f.next();!p.done;p=f.next()){var m=p.value;m(e.event)}}catch(U){n={error:U}}finally{try{p&&!p.done&&(i=f.return)&&i.call(f)}finally{if(n)throw n.error}}try{for(var w=k(this.listeners),S=w.next();!S.done;S=w.next()){var m=S.value;m(e,e.event)}}catch(U){s={error:U}}finally{try{S&&!S.done&&(o=w.return)&&o.call(w)}finally{if(s)throw s.error}}try{for(var y=k(this.contextListeners),E=y.next();!E.done;E=y.next()){var _=E.value;_(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(U){l={error:U}}finally{try{E&&!E.done&&(c=y.return)&&c.call(y)}finally{if(l)throw l.error}}if(this.state.done){var O=e.configuration.find(function(U){return U.type==="final"&&U.parent===u.machine}),M=O&&O.doneData?et(O.doneData,e.context,r):void 0;try{for(var I=k(this.doneListeners),R=I.next();!R.done;R=I.next()){var m=R.value;m(Ce(this.id,M))}}catch(U){h={error:U}}finally{try{R&&!R.done&&(a=I.return)&&a.call(I)}finally{if(h)throw h.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===F.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,s=tt(e,r,n);this.listeners.add(s.next),this.status!==F.NotStarted&&s.next(this.state);var o=function(){i.doneListeners.delete(o),i.stopListeners.delete(o),s.complete()};return this.status===F.Stopped?s.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){i.listeners.delete(s.next),i.doneListeners.delete(o),i.stopListeners.delete(o)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===F.Running)return this;this.machine._init(),ct.register(this.sessionId,this),this.initialized=!0,this.status=F.Running;var n=e===void 0?this.initialState:Ee(this,function(){return bi(e)?r.machine.resolveState(e):r.machine.resolveState(Z.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,he)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){N(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,s,o,l,c,h,a;try{for(var u=k(this.listeners),d=u.next();!d.done;d=u.next()){var f=d.value;this.listeners.delete(f)}}catch(I){e={error:I}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}try{for(var p=k(this.stopListeners),m=p.next();!m.done;m=p.next()){var f=m.value;f(),this.stopListeners.delete(f)}}catch(I){n={error:I}}finally{try{m&&!m.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}try{for(var w=k(this.contextListeners),S=w.next();!S.done;S=w.next()){var f=S.value;this.contextListeners.delete(f)}}catch(I){s={error:I}}finally{try{S&&!S.done&&(o=w.return)&&o.call(w)}finally{if(s)throw s.error}}try{for(var y=k(this.doneListeners),E=y.next();!E.done;E=y.next()){var f=E.value;this.doneListeners.delete(f)}}catch(I){l={error:I}}finally{try{E&&!E.done&&(c=y.return)&&c.call(y)}finally{if(l)throw l.error}}if(!this.initialized)return this;this.initialized=!1,this.status=F.Stopped,this._initialState=void 0;try{for(var _=k(Object.keys(this.delayedEventsMap)),O=_.next();!O.done;O=_.next()){var M=O.value;this.clock.clearTimeout(this.delayedEventsMap[M])}}catch(I){h={error:I}}finally{try{O&&!O.done&&(a=_.return)&&a.call(_)}finally{if(h)throw h.error}}this.scheduler.clear(),this.scheduler=new _r({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=G({type:"xstate.stop"}),i=Ee(e,function(){var s=j(C([],A(e.state.configuration),!1).sort(function(a,u){return u.order-a.order}).map(function(a){return re(a.onExit,e.machine.options.actions)})),o=A(De(e.machine,e.state,e.state.context,n,[s],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),l=o[0],c=o[1],h=new Z({value:e.state.value,context:c,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:l.filter(function(a){return a.type!==le&&(a.type!==de||!!a.to&&a.to!==X.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return h.changed=!0,h});e.update(i,n),e._stopChildren(),ct.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===F.NotStarted&&this.options.deferEvents)L||$(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,`" and are deferred. Make sure .start() is called for this service.
|
|
17
|
+
Event: `).concat(JSON.stringify(event)));else if(this.status!==F.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,l=!1,c=[],h=function(f){var p=G(f);r.forward(p),o=Ee(r,function(){return r.machine.transition(o,p,void 0,n||void 0)}),c.push.apply(c,C([],A(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(m){return Ai(m,o)})),!1)),l=l||!!o.changed};try{for(var a=k(e),u=a.next();!u.done;u=a.next()){var d=u.value;h(d)}}catch(f){i={error:f}}finally{try{u&&!u.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}o.changed=l,o.actions=c,r.update(o,G(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=G(e);if(i.name.indexOf(kt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(kt)===0}))throw i.data.data;var s=Ee(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=k(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,l=this.children.get(o);if(!l)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));l.send(e)}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==F.Running)return _t(e,r);if(lr(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(yi(e))return this.spawnActor(e,r);if(Xn(e))return this.spawnObservable(e,r);if(te(e))return this.spawnMachine(e,g(g({},n),{id:r}));if(Jn(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,g(g({},this.options),{parent:this,id:r.id||e.id})),s=g(g({},Mt),r);s.sync&&i.onTransition(function(l){n.send(Be,{state:l,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(l){n.removeChild(i.id),n.send(G(l,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Ri(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(c){s||(o=c,i.removeChild(r),i.send(G(Ce(r,c),{origin:r})))},function(c){if(!s){i.removeChild(r);var h=we(r,c);try{i.send(G(h,{origin:r}))}catch(a){ri(c,a,r),i.devTools&&i.devTools.send(h,i.state),i.machine.strict&&i.stop()}}});var l=(n={id:r,send:function(){},subscribe:function(c,h,a){var u=tt(c,h,a),d=!1;return e.then(function(f){d||(u.next(f),!d&&u.complete())},function(f){d||u.error(f)}),{unsubscribe:function(){return d=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[ae]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,l=new Set,c,h=function(d){c=d,l.forEach(function(f){return f(d)}),!s&&i.send(G(d,{origin:r}))},a;try{a=e(h,function(d){o.add(d)})}catch(d){this.send(we(r,d))}if(lr(a))return this.spawnPromise(a,r);var u=(n={id:r,send:function(d){return o.forEach(function(f){return f(d)})},subscribe:function(d){var f=tt(d);return l.add(f.next),{unsubscribe:function(){l.delete(f.next)}}},stop:function(){s=!0,N(a)&&a()},toJSON:function(){return{id:r}},getSnapshot:function(){return c}},n[ae]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(c){s=c,i.send(G(c,{origin:r}))},function(c){i.removeChild(r),i.send(G(we(r,c),{origin:r}))},function(){i.removeChild(r),i.send(G(Ce(r),{origin:r}))}),l=(n={id:r,send:function(){},subscribe:function(c,h,a){return e.subscribe(c,h,a)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[ae]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){L||$(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[ae]=function(){return this},n))},t.prototype.attachDev=function(){var e=Dt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(g(g({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:g({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}xi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[ae]=function(){return this},t.prototype.getSnapshot=function(){return this.status===F.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=Se,t}(),Ni=function(t){return x(t)?g(g({},Mt),{name:t}):g(g(g({},Mt),{name:ei()}),t)};function _i(t,e){var r=Ni(e);return vi(function(n){if(!L){var i=te(t)||N(t);$(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(te(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):_t(t,r.name)})}function Se(t,e){var r=new Pi(t,e);return r}function Ui(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ut(t){return g(g({type:Je},t),{toJSON:function(){t.onDone,t.onError;var e=bt(t,["onDone","onError"]);return g(g({},e),{type:Je,src:Ui(t.src)})}})}var Te="",Lt="#",$e="*",be={},Ae=function(t){return t[0]===Lt},Ci=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Di=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(x(s.target)||te(s.target))}),i=e===Te?"the transient event":"event '".concat(e,"'");$(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Mi=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ci(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:sr),this.id=this.config.id||C([this.machine.key],A(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,L||$(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?_e(this.config.states,function(h,a){var u,d=new t(h,{},void 0,{parent:s,key:a});return Object.assign(s.idMap,g((u={},u[d.id]=d,u),d.idMap)),d}):be;var l=0;function c(h){var a,u;h.order=l++;try{for(var d=k(Ir(h)),f=d.next();!f.done;f=d.next()){var p=f.value;c(p)}}catch(m){a={error:m}}finally{try{f&&!f.done&&(u=d.return)&&u.call(d)}finally{if(a)throw a.error}}}c(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(h){var a=h.event;return a===Te}):Te in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=H(this.config.entry||this.config.onEntry).map(function(h){return ye(h)}),this.onExit=H(this.config.exit||this.config.onExit).map(function(h){return ye(h)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=H(this.config.invoke).map(function(h,a){var u,d;if(te(h)){var f=rt(s.id,a);return s.machine.options.services=g((u={},u[f]=h,u),s.machine.options.services),ut({src:f,id:f})}else if(x(h.src)){var f=h.id||rt(s.id,a);return ut(g(g({},h),{id:f,src:h.src}))}else if(te(h.src)||N(h.src)){var f=h.id||rt(s.id,a);return s.machine.options.services=g((d={},d[f]=h.src,d),s.machine.options.services),ut(g(g({id:f},h),{src:f}))}else{var p=h.src;return ut(g(g({id:rt(s.id,a)},h),{src:p}))}}),this.activities=H(this.config.activities).concat(this.invoke).map(function(h){return it(h)}),this.transition=this.transition.bind(this),this.tags=H(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||xr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,l=n.services,c=n.delays;return new t(this.config,{actions:g(g({},i),e.actions),activities:g(g({},s),e.activities),guards:g(g({},o),e.guards),services:g(g({},l),e.services),delays:g(g({},c),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:_e(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Te,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===$e});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var l=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,c=kr(l,e.id);return e.onEntry.push(ce(c,{delay:s})),e.onExit.push(Er(c)),c},i=ge(r)?r.map(function(s,o){var l=n(s.delay,o);return g(g({},s),{event:l})}):j(Object.keys(r).map(function(s,o){var l=r[s],c=x(l)?{target:l}:l,h=isNaN(+s)?s:+s,a=n(h,o);return H(c).map(function(u){return g(g({},u),{event:a,delay:h})})}));return i.map(function(s){var o=s.delay;return g(g({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof Z?e.value:Ne(e,this.delimiter);if(x(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),l=[this];return l.push.apply(l,C([],A(j(o.map(function(c){return n.getStateNode(c).getStateNodes(i[c])}))),!1)),l},t.prototype.handles=function(e){var r=ar(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof Z?e:Z.create(e),n=Array.from(Le([],this.getStateNodes(r.value)));return new Z(g(g({},r),{value:this.resolve(r.value),configuration:n,done:at(n,this),tags:Pr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var l=k(Object.keys(e)),c=l.next();!c.done;c=l.next()){var h=c.value,a=e[h];if(a){var u=this.getStateNode(h),d=u._transition(a,r,n);d&&(o[h]=d)}}}catch(y){i={error:y}}finally{try{c&&!c.done&&(s=l.return)&&s.call(l)}finally{if(i)throw i.error}}var f=Object.keys(o).map(function(y){return o[y]}),p=j(f.map(function(y){return y.transitions})),m=f.some(function(y){return y.transitions.length>0});if(!m)return this.next(r,n);var w=j(f.map(function(y){return y.entrySet})),S=j(Object.keys(o).map(function(y){return o[y].configuration}));return{transitions:p,entrySet:w,exitSet:j(f.map(function(y){return y.exitSet})),configuration:S,source:r,actions:j(Object.keys(o).map(function(y){return o[y].actions}))}},t.prototype._transition=function(e,r,n){return x(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,G(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,l=[],c=[],h;try{for(var a=k(this.getCandidates(o)),u=a.next();!u.done;u=a.next()){var d=u.value,f=d.cond,p=d.in,m=e.context,w=p?x(p)&&Ae(p)?e.matches(Ne(this.getStateNodeById(p).path,this.delimiter)):xt(Ne(p,this.delimiter),Hn(this.path.slice(0,-2))(e.value)):!0,S=!1;try{S=!f||pr(this.machine,f,m,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(f.name||f.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
+
`).concat(O.message))}if(S&&w){d.target!==void 0&&(c=d.target),l.push.apply(l,C([],A(d.actions),!1)),h=d;break}}}catch(O){n={error:O}}finally{try{u&&!u.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}if(h){if(!c.length)return{transitions:[h],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:l};var y=j(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),E=!!h.internal,_=[];return E||c.forEach(function(O){_.push.apply(_,C([],A(s.getExternalReentryNodes(O)),!1))}),{transitions:[h],entrySet:_,exitSet:E?[]:[this],configuration:y,source:e,actions:l}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=A(e.order>this.order?[e,this]:[this,e],2),i=n[0],s=n[1];i&&i!==s;)r.push(i),i=i.parent;return i!==s?[]:(r.push(s),r)},t.prototype.getActions=function(e,r,n,i,s,o,l){var c,h,a,u,d=this,f=Le([],o?this.getStateNodes(o.value):[this]);try{for(var p=k(e),m=p.next();!m.done;m=p.next()){var w=m.value;(!je(f,w)||je(n.entrySet,w.parent))&&n.entrySet.push(w)}}catch(T){c={error:T}}finally{try{m&&!m.done&&(h=p.return)&&h.call(p)}finally{if(c)throw c.error}}try{for(var S=k(f),y=S.next();!y.done;y=S.next()){var w=y.value;(!je(e,w)||je(n.exitSet,w.parent))&&n.exitSet.push(w)}}catch(T){a={error:T}}finally{try{y&&!y.done&&(u=S.return)&&u.call(S)}finally{if(a)throw a.error}}var E=j(n.entrySet.map(function(T){var D=[];if(T.type!=="final")return D;var z=T.parent;if(!z.parent)return D;D.push(Ue(T.id,T.doneData),Ue(z.id,T.doneData?et(T.doneData,i,s):void 0));var B=z.parent;return B.type==="parallel"&&Me(B).every(function(oe){return at(n.configuration,oe)})&&D.push(Ue(B.id)),D}));n.exitSet.sort(function(T,D){return D.order-T.order}),n.entrySet.sort(function(T,D){return T.order-D.order});var _=new Set(n.entrySet),O=new Set(n.exitSet),M=Array.from(_).map(function(T){var D=T.onEntry,z=T.activities.map(function(B){return Sr(B)});return re(l?C(C([],A(D),!1),A(z),!1):C(C([],A(z),!1),A(D),!1),d.machine.options.actions)}).concat([E.map(gr)]),I=Array.from(O).map(function(T){return re(C(C([],A(T.onExit),!1),A(T.activities.map(function(D){return Tr(D)})),!1),d.machine.options.actions)}),R=I.concat([re(n.actions,this.machine.options.actions)]).concat(M);if(r){var U=re(j(C([],A(e),!1).sort(function(T,D){return D.order-T.order}).map(function(T){return T.onExit})),this.machine.options.actions).filter(function(T){return T.type!==le&&(T.type!==de||!!T.to&&T.to!==X.Internal)});return R.concat([U])}return R},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=G(r),o;if(e instanceof Z)o=n===void 0?e:this.resolveState(Z.from(e,n));else{var l=x(e)?this.resolve(Xe(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(Z.from(l,c))}if(!L&&s.name===$e)throw new Error("An event cannot have the wildcard type ('".concat($e,"')"));if(this.strict&&!this.events.includes(s.name)&&!Wn(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var h=this._transition(o.value,o,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:o,actions:[]},a=Le([],this.getStateNodes(o.value)),u=h.configuration.length?Le(a,h.configuration):a;return h.configuration=C([],A(u),!1),this.resolveTransition(h,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,C([],A(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,l,c,h,a=this;s===void 0&&(s=he);var u=e.configuration,d=!r||e.transitions.length>0,f=d?e.configuration:r?r.configuration:[],p=at(f,this),m=d?Ei(this.machine,u):void 0,w=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,S=this.getActions(new Set(f),p,e,n,s,r,i),y=r?g({},r.activities):{};try{for(var E=k(S),_=E.next();!_.done;_=E.next()){var O=_.value;try{for(var M=(c=void 0,k(O)),I=M.next();!I.done;I=M.next()){var R=I.value;R.type===ze?y[R.activity.id||R.activity.type]=R:R.type===He&&(y[R.activity.id||R.activity.type]=!1)}}catch(K){c={error:K}}finally{try{I&&!I.done&&(h=M.return)&&h.call(M)}finally{if(c)throw c.error}}}}catch(K){o={error:K}}finally{try{_&&!_.done&&(l=E.return)&&l.call(E)}finally{if(o)throw o.error}}var U=A(De(this,r,n,s,S,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),T=U[0],D=U[1],z=A(Bn(T,function(K){return K.type===le||K.type===de&&K.to===X.Internal}),2),B=z[0],oe=z[1],xe=T.filter(function(K){var Pe;return K.type===ze&&((Pe=K.activity)===null||Pe===void 0?void 0:Pe.type)===Je}),gs=xe.reduce(function(K,Pe){return K[Pe.activity.id]=gi(Pe.activity,a.machine,D,s),K},r?g({},r.children):{}),St=new Z({value:m||r.value,context:D,_event:s,_sessionid:r?r._sessionid:null,historyValue:m?w?Qn(w,m):void 0:r?r.historyValue:void 0,history:!m||e.source?r:void 0,actions:m?oe:[],activities:m?y:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:gs,done:p,tags:Pr(f),machine:this}),Mn=n!==D;St.changed=s.name===Be||Mn;var Re=St.history;Re&&delete Re.history;var Ln=!p&&(this._transient||u.some(function(K){return K._transient}));if(!d&&(!Ln||s.name===Te))return St;var Q=St;if(!p)for(Ln&&(Q=this.resolveRaisedTransition(Q,{type:tr},s,i));B.length;){var ms=B.shift();Q=this.resolveRaisedTransition(Q,ms._event,s,i)}var ys=Q.changed||(Re?!!Q.actions.length||Mn||typeof Re.value!=typeof Q.value||!Nr(Q.value,Re.value):void 0);return Q.changed=ys,Q.history=Re,Q},t.prototype.getStateNode=function(e){if(Ae(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Ae(e)?e.slice(Lt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Ae(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Rt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||be;switch(this.type){case"parallel":return _e(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):be});case"compound":if(x(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?_e(e,function(s,o){return s?n.getStateNode(o).resolve(s):be}):this.initialStateValue||{};default:return e||be}},t.prototype.getResolvedPath=function(e){if(Ae(e)){var r=this.machine.idMap[e.slice(Lt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Rt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=cr(this.states,function(n){return n.initialStateValue||be},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=ot(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:C([],A(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;x(r.target)?e=Ae(r.target)?Xe(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(ot(this))return[this];if(this.type==="compound"&&!this.initial)return L||$(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=Ze(this.initialStateValue);return j(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=A(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:cr(this.states,function(r,n){if(!e)return r.historyValue();var i=x(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?j(Ze(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=Yn(n.path,"states")(e).current;return x(s)?[n.getStateNode(s)]:j(Ze(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=j(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var l=k(Object.keys(s)),c=l.next();!c.done;c=l.next()){var h=c.value,a=s[h];if(a.states)try{for(var u=(n=void 0,k(a.events)),d=u.next();!d.done;d=u.next()){var f=d.value;o.add("".concat(f))}}catch(p){n={error:p}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(n)throw n.error}}}}catch(p){e={error:p}}finally{try{c&&!c.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!x(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(l){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
+
`).concat(l.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=ti(e.target),i="internal"in e?e.internal:n?n.some(function(c){return x(c)&&c[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),l=g(g({},e),{actions:re(H(e.actions)),cond:fr(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return g(g({},l),{target:l.target?l.target.map(function(c){return"#".concat(c.id)}):void 0,source:"#".concat(r.id)})}});return l},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=$e,l=s[o],c=l===void 0?[]:l,h=bt(s,[typeof o=="symbol"?o:o+""]);i=j(Object.keys(h).map(function(y){!L&&y===Te&&$(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var E=me(y,h[y]);return L||Di(n,y,E),E}).concat(me($e,c)))}var a=this.config.always?me("",this.config.always):[],u=this.config.onDone?me(String(Ue(this.id)),this.config.onDone):[];L||$(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=j(this.invoke.map(function(y){var E=[];return y.onDone&&E.push.apply(E,C([],A(me(String(Ce(y.id)),y.onDone)),!1)),y.onError&&E.push.apply(E,C([],A(me(String(we(y.id)),y.onError)),!1)),E})),f=this.after,p=j(C(C(C(C([],A(u),!1),A(d),!1),A(i),!1),A(a),!1).map(function(y){return H(y).map(function(E){return n.formatTransition(E)})}));try{for(var m=k(f),w=m.next();!w.done;w=m.next()){var S=w.value;p.push(S)}}catch(y){e={error:y}}finally{try{w&&!w.done&&(r=m.return)&&r.call(m)}finally{if(e)throw e.error}}return p},t}(),Ur=!1;function ue(t,e){return!L&&!t.predictableActionArguments&&!Ur&&(Ur=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Mi(t,e)}var b=Ar,q=ce;/*! js-cookie v3.0.1 | MIT */function lt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var Li={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function jt(t,e){function r(i,s,o){if(typeof document!="undefined"){o=lt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var l="";for(var c in o)o[c]&&(l+="; "+c,o[c]!==!0&&(l+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+l}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},l=0;l<s.length;l++){var c=s[l].split("="),h=c.slice(1).join("=");try{var a=decodeURIComponent(c[0]);if(o[a]=t.read(h,a),i===a)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",lt({},s,{expires:-1}))},withAttributes:function(i){return jt(this.converter,lt({},this.attributes,i))},withConverter:function(i){return jt(lt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var $t=jt(Li,{path:"/"});function Cr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ji(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){if(this instanceof n){var i=[null];i.push.apply(i,arguments);var s=Function.bind.apply(e,i);return new s}return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}function $i(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],l={},c=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(a){return l[a.toLowerCase()]},has:function(a){return a.toLowerCase()in l}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,u,d){s.push(u=u.toLowerCase()),o.push([u,d]),l[u]=l[u]?l[u]+","+d:d}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}const Dr=ji(Object.freeze(Object.defineProperty({__proto__:null,default:$i},Symbol.toStringTag,{value:"Module"})));var Fi=self.fetch||(self.fetch=Dr.default||Dr);const ke=Cr(Fi),Oe="nhostRefreshToken",Fe="nhostRefreshTokenId",fe="nhostRefreshTokenExpiresAt",Mr=3,Lr=300,Ft=5,qt=0,Gt=1,Y=10,Ie=20;let qe=class extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Gt,message:e.message}):(this.name=e.error,this.error=e)}};const ne={status:Y,error:"invalid-email",message:"Email is incorrectly formatted"},jr={status:Y,error:"invalid-mfa-type",message:"MFA type is invalid"},$r={status:Y,error:"invalid-mfa-code",message:"MFA code is invalid"},dt={status:Y,error:"invalid-password",message:"Password is incorrectly formatted"},Vt={status:Y,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Fr={status:Y,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},qr={status:Y,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Gr={status:Y,error:"no-refresh-token",message:"No refresh token has been provided"},Vr={status:Ie,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},W={status:Ie,error:"already-signed-in",message:"User is already signed in"},Kr={status:Ie,error:"unauthenticated-user",message:"User is not authenticated"},qi={status:Ie,error:"user-not-anonymous",message:"User is not anonymous"},zr={status:Ie,error:"unverified-user",message:"Email needs verification"},Hr={status:Y,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Yr={status:Gt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},ht={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function Gi(t){return new TextEncoder().encode(t)}function pe(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Kt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let l=0;l<i.length;l++)o[l]=i.charCodeAt(l);return s}function Wr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Jr(t){const{id:e}=t;return{...t,id:Kt(e),transports:t.transports}}function Br(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let V=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function Vi({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new V("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new V("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new V("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new V("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new V("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(s=>s.type==="public-key").length===0?new V('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new V("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(Br(s)){if(i.rp.id!==s)return new V(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new V(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new V("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new V("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Ki{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const ft=new Ki;async function Qr(t){if(!Wr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Kt(t.challenge),user:{...t.user,id:Gi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Jr)}};e.signal=ft.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(c){throw Vi({error:c,options:e})}finally{ft.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,l={id:n,rawId:pe(i),response:{attestationObject:pe(s.attestationObject),clientDataJSON:pe(s.clientDataJSON)},type:o,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof s.getTransports=="function"&&(l.transports=s.getTransports()),l}function zi(t){return new TextDecoder("utf-8").decode(t)}async function Hi(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function Yi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new V("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new V("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new V("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Br(i)){if(n.rpId!==i)return new V(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new V(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new V("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Wi(t,e=!1){var r,n;if(!Wr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Jr));const s={...t,challenge:Kt(t.challenge),allowCredentials:i},o={};if(e){if(!await Hi())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=ft.createNewAbortSignal();let l;try{l=await navigator.credentials.get(o)}catch(f){throw Yi({error:f,options:o})}finally{ft.reset()}if(!l)throw new Error("Authentication was not completed");const{id:c,rawId:h,response:a,type:u}=l;let d;return a.userHandle&&(d=zi(a.userHandle)),{id:c,rawId:pe(h),response:{authenticatorData:pe(a.authenticatorData),clientDataJSON:pe(a.clientDataJSON),signature:pe(a.signature),userHandle:d},type:u,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:l.authenticatorAttachment}}const pt=typeof window!="undefined",vt=new Map,Ji=t=>{var e;return pt&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=vt.get(t))!=null?e:null},Bi=(t,e)=>{pt&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?vt.set(t,e):vt.has(t)&&vt.delete(t)},Xr=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return r=>{var n;return pt&&(n=$t.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},Zr=(t,e)=>{if(t==="localStorage"||t==="web")return Bi;if(t==="cookie")return(r,n)=>{pt&&(n?$t.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):$t.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},Ge=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ie=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},gt=()=>typeof window!="undefined",en=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await ke(t,s);if(!o.ok){const l=await o.json();return Promise.reject({error:l})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:qt,error:"network"};return Promise.reject({error:o})}},ee=async(t,e,r)=>en(t,"POST",{token:r,body:e}),tn=(t,e)=>en(t,"GET",{token:e}),zt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},J=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),l=new URLSearchParams(o.search);let c=Object.fromEntries(l);r.startsWith("/")&&(c={...s,...c});let h=i.pathname;return o.pathname.length>1&&(h+=o.pathname.slice(1)),{...n,redirectTo:zt(o.origin+h,c)}};function Ve(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Ht(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const se=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),mt=t=>!!t&&typeof t=="string"&&t.length>=Mr,Yt=t=>!!t&&typeof t=="string",rn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),nn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const l=Xr(r,n),c=Zr(r,n),h=async(a,u,d)=>(await ee(`${t}${a}`,u,d)).data;return ue({schema:{context:{},events:{},services:{}},tsTypes:{},context:ht,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:q("SIGNED_IN"),reportSignedOut:q("SIGNED_OUT"),reportTokenChanged:q("TOKEN_CHANGED"),incrementTokenImportAttempts:b({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:b(()=>(c(fe,null),c(Oe,null),c(Fe,null),{...ht})),clearContextExceptRefreshToken:b(({refreshToken:{value:a}})=>(c(fe,null),{...ht,refreshToken:{value:a}})),saveSession:b({user:(a,{data:u})=>{var d;return((d=u==null?void 0:u.session)==null?void 0:d.user)||null},accessToken:(a,{data:u})=>{if(u.session){const{accessTokenExpiresIn:d,accessToken:f}=u.session,p=new Date(Date.now()+d*1e3);return c(fe,p.toISOString()),{value:f,expiresAt:p}}return c(fe,null),{value:null,expiresAt:null}},refreshToken:(a,{data:u})=>{var d,f;const p=((d=u.session)==null?void 0:d.refreshToken)||null,m=((f=u.session)==null?void 0:f.refreshTokenId)||null;return p&&c(Oe,p),m&&c(Fe,m),{value:p}}}),savePATSession:b({user:(a,{data:u})=>{var d;return((d=u==null?void 0:u.session)==null?void 0:d.user)||null},accessToken:(a,{data:u})=>{if(u.session){const{accessTokenExpiresIn:d,accessToken:f}=u.session,p=new Date(Date.now()+d*1e3);return c(fe,p.toISOString()),{value:f,expiresAt:p}}return c(fe,null),{value:null,expiresAt:null}},refreshToken:(a,{data:u})=>{var d,f;const p=((d=u.session)==null?void 0:d.refreshToken)||null,m=((f=u.session)==null?void 0:f.refreshTokenId)||null;return p&&c(Oe,p),m&&c(Fe,m),{value:p,isPAT:!0}}}),saveMfaTicket:b({mfa:(a,u)=>{var d;return(d=u.data)==null?void 0:d.mfa}}),resetTimer:b({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:b({refreshTimer:(a,u)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:b({errors:({errors:a},{data:{error:u}})=>({...a,authentication:u})}),resetErrors:b({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:b({errors:({errors:a},{data:{error:u}})=>({...a,registration:u})}),destroyRefreshToken:b({refreshToken:a=>(c(Oe,null),c(Fe,null),{value:null})}),cleanUrl:()=>{o&&Ve("refreshToken")&&(Ht("refreshToken"),Ht("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage(a.refreshToken.value)}catch{}}},guards:{isAnonymous:(a,u)=>{var d;return!!((d=a.user)!=null&&d.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.refreshToken.value&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var u;return!!((u=a.refreshToken)!=null&&u.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:u}=a.accessToken;return u?a.refreshTimer.lastAttempt?a.refreshTimer.attempts>Ft?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3:i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3?!0:u.getTime()-Date.now()-1e3*Lr<=0:!1},shouldRetryImportToken:(a,u)=>a.importTokenAttempts<Ft&&(u.data.error.status===qt||u.data.error.status>=500),unverified:(a,{data:{error:u}})=>u.status===401&&(u.message==="Email is not verified"||u.error==="unverified-user"),hasSession:(a,u)=>{var d;return!!((d=u.data)!=null&&d.session)},hasMfaTicket:(a,u)=>{var d;return!!((d=u.data)!=null&&d.mfa)}},services:{signInPassword:(a,{email:u,password:d})=>se(u)?mt(d)?h("/signin/email-password",{email:u,password:d}):Promise.reject({error:dt}):Promise.reject({error:ne}),signInPAT:(a,{pat:u})=>h("/signin/pat",{personalAccessToken:u}),passwordlessSms:(a,{phoneNumber:u,options:d})=>{var f;return Yt(u)?(f=a.user)!=null&&f.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:u,options:J(e,d)},a.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:u,options:J(e,d)}):Promise.reject({error:Vt})},passwordlessSmsOtp:(a,{phoneNumber:u,otp:d})=>Yt(u)?h("/signin/passwordless/sms/otp",{phoneNumber:u,otp:d}):Promise.reject({error:Vt}),passwordlessEmail:(a,{email:u,options:d})=>{var f;return se(u)?(f=a.user)!=null&&f.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:u,options:J(e,d)},a.accessToken.value):h("/signin/passwordless/email",{email:u,options:J(e,d)}):Promise.reject({error:ne})},signInAnonymous:a=>h("/signin/anonymous"),signInMfaTotp:(a,u)=>{var d;const f=u.ticket||((d=a.mfa)==null?void 0:d.ticket);return f?rn(f)?h("/signin/mfa/totp",{ticket:f,otp:u.otp}):Promise.reject({error:Fr}):Promise.reject({error:qr})},signInSecurityKeyEmail:async(a,{email:u})=>{if(!se(u))throw new qe(ne);const d=await h("/signin/webauthn",{email:u});let f;try{f=await Wi(d)}catch(p){throw new qe(p)}return h("/signin/webauthn/verify",{email:u,credential:f})},refreshToken:async(a,u)=>{const d=u.type==="TRY_TOKEN"?u.token:a.refreshToken.value;return{session:await h("/token",{refreshToken:d}),error:null}},signout:(a,u)=>h("/signout",{refreshToken:a.refreshToken.value,all:!!u.all}),signUpEmailPassword:async(a,{email:u,password:d,options:f})=>{var p;return se(u)?mt(d)?(p=a.user)!=null&&p.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:u,password:d,options:J(e,f)},a.accessToken.value):h("/signup/email-password",{email:u,password:d,options:J(e,f)}):Promise.reject({error:dt}):Promise.reject({error:ne})},signUpSecurityKey:async(a,{email:u,options:d})=>{if(!se(u))return Promise.reject({error:ne});const f=d==null?void 0:d.nickname;f&&delete d.nickname;const p=await h("/signup/webauthn",{email:u,options:d});let m;try{m=await Qr(p)}catch(w){throw new qe(w)}return h("/signup/webauthn/verify",{credential:m,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:f}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let u=null;if(o){const f=Ve("refreshToken")||null;if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(p){u=p.error}else{const p=Ve("error");if(p)return Promise.reject({session:null,error:{status:Y,error:p,message:Ve("errorDescription")||p}})}}const d=await l(Oe);if(d)try{return{session:await h("/token",{refreshToken:d}),error:null}}catch(f){u=f.error}return u?Promise.reject({error:u,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},sn=({backendUrl:t,clientUrl:e,interpreter:r})=>ue({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:n=>ne}),saveRequestError:b({error:(n,{data:{error:i}})=>i}),reportError:q(n=>({type:"ERROR",error:n.error})),reportSuccess:q("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!se(i)},services:{requestChange:async(n,{email:i,options:s})=>(await ee(`${t}/user/email/change`,{newEmail:i,options:J(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),on=({backendUrl:t,interpreter:e})=>ue({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:b({error:r=>dt}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:q(r=>({type:"ERROR",error:r.error})),reportSuccess:q("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!mt(n)},services:{requestChange:(r,{password:n,ticket:i})=>ee(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ue({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:b({error:r=>jr}),saveInvalidMfaCodeError:b({error:r=>$r}),saveError:b({error:(r,{data:{error:n}})=>n}),saveGeneration:b({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:q((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:q("SUCCESS"),reportGeneratedSuccess:q("GENERATED"),reportGeneratedError:q(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await tn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>ee(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),an=({backendUrl:t,clientUrl:e})=>ue({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:r=>ne}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:q(r=>({type:"ERROR",error:r.error})),reportSuccess:q("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!se(n)},services:{requestChange:(r,{email:n,options:i})=>ee(`${t}/user/password/reset`,{email:n,options:J(e,i)})}}),cn=({backendUrl:t,clientUrl:e})=>ue({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:b({error:r=>ne}),saveRequestError:b({error:(r,{data:{error:n}})=>n}),reportError:q(r=>({type:"ERROR",error:r.error})),reportSuccess:q("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!se(n)},services:{request:async(r,{email:n,options:i})=>(await ee(`${t}/user/email/send-verification-email`,{email:n,options:J(e,i)})).data}});class Wt{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:l,...c}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=nn({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:l}),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",h=>{var a;const u=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&h.data!==u&&this.interpreter.send("TRY_TOKEN",{token:h.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const l=this.machine.withContext(o);this._interpreter||(this._interpreter=n||Se(l,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(l.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class un extends Wt{constructor({...e}){super({...e,autoSignIn:gt()&&e.autoSignIn,autoRefreshToken:gt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=un,ln=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await ee(`${t}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await Qr(n)}catch(o){throw new qe(o)}const{data:s}=await ee(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},dn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),hn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Zi=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),es=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),fn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),pn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),vn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:W,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),gn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,error:W,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),Jt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:W,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),mn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:W,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),yn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,error:W,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),wn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:W,user:null,accessToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),Bt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:W,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),En=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:W,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),Sn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:Kr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),Qt=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:W,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(l=>{l.matches("registration.incomplete.failed")?i({accessToken:null,error:l.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):l.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):l.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:l.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:l.context.user})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:W,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),ts=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await ee(`${t}/pat`,{expiresAt:r.toUTCString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1,data:null}}};class bn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:l=!0}){var c;this.url=e,this._client=new Wt({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:l,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ie(await Tn(r,n,i)):ie(await Qt(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await vn(r);return{...ie(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=zt(`${this._client.backendUrl}/signin/provider/${n}`,J(this._client.clientUrl,i));return gt()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await gn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:zr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ie(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await mn(r,e.email);return{...ie(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await Jt(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await En(r,e.phoneNumber,e.otp);return{...ie(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Bt(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await yn(r,e.otp,e.ticket);return{...ie(n),mfa:null}}return{error:Yr,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await wn(r,e);return ie(n)}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await Sn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=Se(an(this._client)).start(),{error:i}=await fn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=Se(on(this._client)).start(),{error:i}=await hn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=Se(cn(this._client)).start(),{error:i}=await pn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=Se(sn(this._client)).start(),{error:i}=await dn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Jt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await Bt(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await Qt(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await ln(this._client,e);return{error:r,key:n}}async createPAT(e,r){return ts(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(Ge(s))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,Ge(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?$n(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Gr});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:Vr});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:Hr}):o.event.type==="TOKEN_CHANGED"&&n({session:Ge(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return Ge((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var rs=typeof self=="object"?self.FormData:window.FormData;const An=Cr(rs),ns=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},kn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:l}={})=>{const c={};i&&(c["x-nhost-file-id"]=i),s&&(c["x-nhost-bucket-id"]=s),n&&(c["x-nhost-file-name"]=ns(n)),o&&(c["x-hasura-admin-secret"]=o),r&&(c.Authorization=`Bearer ${r}`);const h=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{const a=await ke(h,{method:"POST",headers:c,body:e});return a.ok?{fileMetadata:await a.json(),error:null}:{error:{status:a.status,message:await a.text(),error:a.statusText},fileMetadata:null}}catch(a){return{error:{status:0,message:a.message,error:a.message},fileMetadata:null}}return new Promise(a=>{let u=new XMLHttpRequest;u.responseType="json",u.onload=()=>u.status<200&&u.status>=300?a({fileMetadata:null,error:{error:u.statusText,message:u.statusText,status:u.status}}):a({fileMetadata:u.response,error:null}),u.onerror=()=>a({fileMetadata:null,error:{error:u.statusText,message:u.statusText,status:u.status}}),l&&u.upload.addEventListener("progress",l,!1),u.open("POST",h,!0),Object.entries(c).forEach(([d,f])=>{u.setRequestHeader(d,f)}),u.send(e)})};class On{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return kn(this.url,r,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await ke(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await ke(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}function Xt(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}class In{constructor({url:e,adminSecret:r}){this.url=e,this.api=new On({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new An,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Xt(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,...n}=e,{presignedUrl:i,error:s}=await this.api.getPresignedUrl(e);if(s)return{presignedUrl:null,error:s};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const o=Xt(i.url,n);return{presignedUrl:{...i,url:o},error:null}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const yt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},xn=()=>ue({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...yt},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:b({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:b({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:b({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:b({progress:t=>null,loaded:t=>0}),resetContext:b(t=>yt),addFile:b({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new An;i.append("file",n);let s=0;return kn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const l=o.total?Math.round(o.loaded*n.size/o.total):0,c=l-s;s=l,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(l*100/o.total):0,loaded:l,additions:c})}}).then(({fileMetadata:o,error:l})=>{if(l&&r({type:"UPLOAD_ERROR",error:l}),o){const{id:c,bucketId:h}=o;r({type:"UPLOAD_DONE",id:c,bucketId:h})}}),()=>{}}}}),{pure:Zt,sendParent:wt}=pi,is=()=>ue({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:b((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:b({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:b({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:b({loaded:t=>0}),startProgress:b({progress:t=>0}),resetProgress:b({progress:t=>null}),addItem:b((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,l)=>o+l.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>_i(xn().withConfig({actions:{sendProgress:wt((l,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:wt("UPLOAD_DONE"),sendError:wt("UPLOAD_ERROR"),sendDestroy:wt("REMOVE")}}).withContext({...yt,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:b({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:Zt(t=>t.files.map(e=>q({type:"DESTROY"},{to:e.id}))),upload:Zt((t,e)=>t.files.map(r=>q(e,{to:r.id}))),cancel:Zt(t=>t.files.map(e=>q({type:"CANCEL"},{to:e.id})))}}),ss=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),os=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),as=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Et(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const s=n.match(as);if(s!=null&&s.groups){const{protocol:o,host:l,port:c}=s.groups,h=ls(e);return h||(l==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${o||"http"}://localhost:${c||1337}/v1/${e}`):c?`${o||"https"}://local.${e}.nhost.run:${c}/v1`:`${o||"https"}://local.${e}.nhost.run/v1`)}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${n}.${e}.${i}.nhost.run/v1`}function cs(){return typeof window!="undefined"}function us(){return typeof process!="undefined"&&process.env}function ls(t){return cs()||!us()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function ds(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Rn(t){const e="subdomain"in t||"backendUrl"in t?Et(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new bn({url:e,...t})}function Pn(t){const e="subdomain"in t||"backendUrl"in t?Et(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Nn({url:e,...t})}class Nn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,l;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s=ds(this.url,e);try{const c=await ke(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let h;return(l=c.headers.get("content-type"))!=null&&l.includes("application/json")?h=await c.json():h=await c.text(),{res:{data:h,status:c.status,statusText:c.statusText},error:null}}catch(c){const h=c;return{res:null,error:{message:h.message,status:h.name==="AbortError"?0:500,error:h.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function hs(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function _n(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function fs(t){if(typeof t=="string"){let r;try{const n=ve.parse(t);r=_n(n)}catch{}return{query:t,operationName:r}}const e=_n(t);return{query:ve.print(t),operationName:e}}class ps{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=hs(e,n,i),{headers:o,...l}=i||{},{query:c,operationName:h}=fs(s.document);try{const a=await ke(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...o},...l});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:u,errors:d}=await a.json();return d?{data:null,error:d}:typeof u!="object"||Array.isArray(u)||u===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:u,error:null}}catch(a){const u=a;return{data:null,error:{message:u.message,status:u.name==="AbortError"?0:500,error:u.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Un(t){const e="subdomain"in t||"backendUrl"in t?Et(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new ps({url:e,...t})}function Cn(t){const e="subdomain"in t||"backendUrl"in t?Et(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new In({url:e,...t})}const vs=t=>new Dn(t);class Dn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:l,start:c=!0,...h}){this.auth=Rn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...h}),this.storage=Cn({adminSecret:o,...h}),this.functions=Pn({adminSecret:o,...h}),this.graphql=Un({adminSecret:o,...h}),this.auth.onAuthStateChanged((a,u)=>{a==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(a=>{const u=a==null?void 0:a.accessToken;this.storage.setAccessToken(u),this.functions.setAccessToken(u),this.graphql.setAccessToken(u)}),this._adminSecret=o,this.devTools=l}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}v.AuthClient=Wt,v.AuthClientSSR=Xi,v.AuthCookieClient=un,v.CodifiedError=qe,v.EMAIL_NEEDS_VERIFICATION=zr,v.HasuraAuthClient=bn,v.HasuraStorageApi=On,v.HasuraStorageClient=In,v.INITIAL_FILE_CONTEXT=yt,v.INITIAL_MACHINE_CONTEXT=ht,v.INVALID_EMAIL_ERROR=ne,v.INVALID_MFA_CODE_ERROR=$r,v.INVALID_MFA_TICKET_ERROR=Fr,v.INVALID_MFA_TYPE_ERROR=jr,v.INVALID_PASSWORD_ERROR=dt,v.INVALID_PHONE_NUMBER_ERROR=Vt,v.INVALID_REFRESH_TOKEN=Hr,v.INVALID_SIGN_IN_METHOD=Yr,v.MIN_PASSWORD_LENGTH=Mr,v.NETWORK_ERROR_CODE=qt,v.NHOST_JWT_EXPIRES_AT_KEY=fe,v.NHOST_REFRESH_TOKEN_ID_KEY=Fe,v.NHOST_REFRESH_TOKEN_KEY=Oe,v.NO_MFA_TICKET_ERROR=qr,v.NO_REFRESH_TOKEN=Gr,v.NhostClient=Dn,v.NhostFunctionsClient=Nn,v.OTHER_ERROR_CODE=Gt,v.REFRESH_TOKEN_MAX_ATTEMPTS=Ft,v.STATE_ERROR_CODE=Ie,v.TOKEN_REFRESHER_RUNNING_ERROR=Vr,v.TOKEN_REFRESH_MARGIN=Lr,v.USER_ALREADY_SIGNED_IN=W,v.USER_NOT_ANONYMOUS=qi,v.USER_UNAUTHENTICATED=Kr,v.VALIDATION_ERROR_CODE=Y,v.activateMfaPromise=es,v.addSecurityKeyPromise=ln,v.appendImageTransformationParameters=Xt,v.changeEmailPromise=dn,v.changePasswordPromise=hn,v.createAuthClient=Rn,v.createAuthMachine=nn,v.createChangeEmailMachine=sn,v.createChangePasswordMachine=on,v.createEnableMfaMachine=Qi,v.createFileUploadMachine=xn,v.createFunctionsClient=Pn,v.createGraphqlClient=Un,v.createMultipleFilesUploadMachine=is,v.createNhostClient=vs,v.createResetPasswordMachine=an,v.createSendVerificationEmailMachine=cn,v.createStorageClient=Cn,v.encodeQueryParameters=zt,v.generateQrCodePromise=Zi,v.getAuthenticationResult=ie,v.getFetch=tn,v.getParameterByName=Ve,v.getSession=Ge,v.isBrowser=gt,v.isValidEmail=se,v.isValidPassword=mt,v.isValidPhoneNumber=Yt,v.isValidTicket=rn,v.localStorageGetter=Xr,v.localStorageSetter=Zr,v.postFetch=ee,v.removeParameterFromWindow=Ht,v.resetPasswordPromise=fn,v.rewriteRedirectTo=J,v.sendVerificationEmailPromise=pn,v.signInAnonymousPromise=vn,v.signInEmailPasswordPromise=gn,v.signInEmailPasswordlessPromise=Jt,v.signInEmailSecurityKeyPromise=mn,v.signInMfaTotpPromise=yn,v.signInPATPromise=wn,v.signInSmsPasswordlessOtpPromise=En,v.signInSmsPasswordlessPromise=Bt,v.signOutPromise=Sn,v.signUpEmailPasswordPromise=Qt,v.signUpEmailSecurityKeyPromise=Tn,v.uploadFilePromise=ss,v.uploadMultipleFilesPromise=os,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
|
|
20
20
|
//# sourceMappingURL=nhost-js.umd.js.map
|