@nhost/nhost-js 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/graphql.d.ts +2 -2
- package/dist/clients/graphql.d.ts.map +1 -1
- package/dist/clients/nhost.d.ts +5 -5
- package/dist/clients/nhost.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +55 -56
- package/dist/index.esm.js.map +1 -1
- package/dist/utils/types.d.ts +1 -3
- package/dist/utils/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/umd/nhost-js.umd.js +7 -9
- package/umd/nhost-js.umd.js.map +1 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(g,Se){typeof exports=="object"&&typeof module<"u"?Se(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],Se):(g=typeof globalThis<"u"?globalThis:g||self,Se(g["@nhost/nhost-js"]={},g.graphql))})(this,function(g,Se){"use strict";function At(t){this.message=t}At.prototype=new Error,At.prototype.name="InvalidCharacterError";var or=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new At("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,o=0,s="";n=e.charAt(o++);~n&&(r=i%4?64*r+n:n,i++%4)?s+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function $n(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(or(r).replace(/(.)/g,function(n,i){var o=i.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(e)}catch{return or(e)}}function ze(t){this.message=t}function Bn(t,e){if(typeof t!="string")throw new ze("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse($n(t.split(".")[r]))}catch(n){throw new ze("Invalid token specified: "+n.message)}}ze.prototype=new Error,ze.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,12 +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 w=function(){return w=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},w.apply(this,arguments)};function It(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 j(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 D(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function V(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}var B;(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"})(B||(B={}));var ie;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ie||(ie={}));var Qe=B.Start,Ye=B.Stop,me=B.Raise,ge=B.Send,xt=B.Cancel,fr=B.NullEvent,We=B.Assign,Xn=B.After,Zn=B.DoneState,Xe=B.Log,hr=B.Init,Ze=B.Invoke,ei=B.ErrorExecution,Rt=B.ErrorPlatform,Pt=B.ErrorCustom,et=B.Update,pr=B.Choose,vr=B.Pure;const ti=Object.freeze(Object.defineProperty({__proto__:null,after:Xn,assign:We,cancel:xt,choose:pr,doneState:Zn,error:Pt,errorExecution:ei,errorPlatform:Rt,init:hr,invoke:Ze,log:Xe,nullEvent:fr,pure:vr,raise:me,send:ge,start:Qe,stop:Ye,update:et},Symbol.toStringTag,{value:"Module"}));var yr=".",mr={},Ut="xstate.guard",ri="",H=process.env.NODE_ENV==="production",tt;function Nt(t,e,r){r===void 0&&(r=yr);var n=Ne(t,r),i=Ne(e,r);return L(i)?L(n)?i===n:!1:L(n)?n in i:Object.keys(n).every(function(o){return o in i?Nt(n[o],i[o]):!1})}function gr(t){try{return L(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 Dt(t,e){try{return be(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function ni(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Ne(t,e){if(ni(t))return t.value;if(be(t))return rt(t);if(typeof t!="string")return t;var r=Dt(t,e);return rt(r)}function rt(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 De(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];r[o]=e(t[o],o,t,i)}return r}function wr(t,e,r){var n,i,o={};try{for(var s=j(Object.keys(t)),u=s.next();!u.done;u=s.next()){var f=u.value,h=t[f];r(h)&&(o[f]=e(h,f,t))}}catch(l){n={error:l}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var ii=function(t){return function(e){var r,n,i=e;try{for(var o=j(t),s=o.next();!s.done;s=o.next()){var u=s.value;i=i[u]}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function oi(t,e){return function(r){var n,i,o=r;try{for(var s=j(t),u=s.next();!u.done;u=s.next()){var f=u.value;o=o[e][f]}}catch(h){n={error:h}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}}function nt(t){if(!t)return[[]];if(L(t))return[[t]];var e=K(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:nt(t[r]).map(function(i){return[r].concat(i)})}));return e}function K(t){var e;return(e=[]).concat.apply(e,V([],D(t),!1))}function Er(t){return be(t)?t:[t]}function te(t){return t===void 0?[]:Er(t)}function it(t,e,r){var n,i;if(q(t))return t(e,r.data);var o={};try{for(var s=j(Object.keys(t)),u=s.next();!u.done;u=s.next()){var f=u.value,h=t[f];q(h)?o[f]=h(e,r.data):o[f]=h}}catch(l){n={error:l}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function si(t){return/^(done|error)\./.test(t)}function Sr(t){return!!(t instanceof Promise||t!==null&&(q(t)||typeof t=="object")&&q(t.then))}function ai(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function ci(t,e){var r,n,i=D([[],[]],2),o=i[0],s=i[1];try{for(var u=j(t),f=u.next();!f.done;f=u.next()){var h=f.value;e(h)?o.push(h):s.push(h)}}catch(l){r={error:l}}finally{try{f&&!f.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[o,s]}function br(t,e){return De(t.states,function(r,n){if(r){var i=(L(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:br(r,i)}}})}function ui(t,e){return{current:e,states:br(t,e)}}function Tr(t,e,r,n){H||J(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(o,s){var u,f,h=s.assignment,l={state:n,action:s,_event:e},c={};if(q(h))c=h(o,e.data,l);else try{for(var d=j(Object.keys(h)),p=d.next();!p.done;p=d.next()){var y=p.value,g=h[y];c[y]=q(g)?g(o,e.data,l):g}}catch(m){u={error:m}}finally{try{p&&!p.done&&(f=d.return)&&f.call(d)}finally{if(u)throw u.error}}return Object.assign({},o,c)},t);return i}var J=function(){};H||(J=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 be(t){return Array.isArray(t)}function q(t){return typeof t=="function"}function L(t){return typeof t=="string"}function Ar(t,e){if(t)return L(t)?{type:Ut,name:t,predicate:e?e[t]:void 0}:q(t)?{type:Ut,name:t.name,predicate:t}:t}function li(t){try{return"subscribe"in t&&q(t.subscribe)}catch{return!1}}var he=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();tt={},tt[he]=function(){return this},tt[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function di(t){return!!t&&typeof t.send=="function"}var fi=function(){var t=0;return function(){return t++,t.toString(16)}}();function Ct(t,e){return L(t)||typeof t=="number"?w({type:t},e):t}function W(t,e){if(!L(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Ct(t);return w({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function Te(t,e){var r=Er(e).map(function(n){return typeof n>"u"||typeof n=="string"||ae(n)?{target:n,event:t}:w(w({},n),{event:t})});return r}function hi(t){if(!(t===void 0||t===ri))return te(t)}function pi(t,e,r){if(!H){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 Or(t,e,r,n,i){var o=t.options.guards,s={state:i,cond:e,_event:n};if(e.type===Ut)return((o==null?void 0:o[e.name])||e.predicate)(r,n.data,s);var u=o==null?void 0:o[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,s)}function kr(t){return typeof t=="string"?{type:t}:t}function ot(t,e,r){var n=function(){},i=typeof t=="object",o=i?t:null;return{next:((i?t.next:t)||n).bind(o),error:((i?t.error:e)||n).bind(o),complete:((i?t.complete:r)||n).bind(o)}}function st(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=W({type:hr});function at(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(L(t)||typeof t=="number"){var n=at(t,e);q(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(q(t))r={type:t.name||t.toString(),exec:t};else{var n=at(t.type,e);if(q(n))r=w(w({},t),{exec:n});else if(n){var i=n.type||t.type;r=w(w(w({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=be(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function ct(t){var e=Ae(t);return w(w({id:L(t)?t:e.id},e),{type:e.type})}function _r(t){return L(t)?{type:me,event:t}:pe(t,{to:ie.Internal})}function Ir(t){return{type:me,_event:W(t.event)}}function pe(t,e){return{to:e?e.to:void 0,type:ge,event:q(t)?t:Ct(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:q(t)?t.name:gr(t)}}function xr(t,e,r,n){var i={_event:r},o=W(q(t.event)?t.event(e,r.data,i):t.event),s;if(L(t.delay)){var u=n&&n[t.delay];s=q(u)?u(e,r.data,i):u}else s=q(t.delay)?t.delay(e,r.data,i):t.delay;var f=q(t.to)?t.to(e,r.data,i):t.to;return w(w({},t),{to:f,_event:o,event:o.data,delay:s})}function Mt(t,e){return pe(t,w(w({},e),{to:ie.Parent}))}function vi(t,e,r){return pe(e,w(w({},r),{to:t}))}function yi(){return Mt(et)}function mi(t,e){return pe(t,w(w({},e),{to:function(r,n,i){var o=i._event;return o.origin}}))}var gi=function(t,e){return{context:t,event:e}};function wi(t,e){return t===void 0&&(t=gi),{type:Xe,label:e,expr:t}}var Rr=function(t,e,r){return w(w({},t),{value:L(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Pr=function(t){return{type:xt,sendId:t}};function Ur(t){var e=ct(t);return{type:B.Start,activity:e,exec:void 0}}function Nr(t){var e=q(t)?t:ct(t);return{type:B.Stop,activity:e,exec:void 0}}function Dr(t,e,r){var n=q(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,o={type:B.Stop,activity:i};return o}var Cr=function(t){return{type:We,assignment:t}};function Ei(t){return typeof t=="object"&&"type"in t}function Mr(t,e){var r=e?"#".concat(e):"";return"".concat(B.After,"(").concat(t,")").concat(r)}function Ce(t,e){var r="".concat(B.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Me(t,e){var r="".concat(B.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat(B.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Si(t){return{type:B.Pure,get:t}}function bi(t,e){if(!H&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=typeof r=="function"?r.apply(void 0,V([],D(n),!1)):r;if(!o)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return o}}return pe(function(n,i){return i},w(w({},e),{to:t}))}function Ti(t,e){return Mt(function(r,n,i){return{type:Pt,data:q(t)?t(r,n,i):t}},w(w({},e),{to:ie.Parent}))}function Ai(t){return{type:B.Choose,conds:t}}var Oi=function(t){var e,r,n=[];try{for(var i=j(t),o=i.next();!o.done;o=i.next())for(var s=o.value,u=0;u<s.length;){if(s[u].type===We){n.push(s[u]),s.splice(u,1);continue}u++}}catch(f){e={error:f}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function je(t,e,r,n,i,o,s){s===void 0&&(s=!1);var u=s?[]:Oi(i),f=u.length?Tr(r,n,u,e):r,h=s?[r]:void 0,l=[];function c(y){var g;switch(y.type){case me:return Ir(y);case ge:var m=xr(y,f,n,t.options.delays);return H||J(!L(y.delay)||typeof m.delay=="number","No delay reference for delay expression '".concat(y.delay,"' was found on machine '").concat(t.id,"'")),o&&m.to!==ie.Internal&&l.push(m),m;case Xe:{var T=Rr(y,f,n);return o==null||o(T,f,n),T}case pr:{var b=y,A=(g=b.conds.find(function(G){var a=Ar(G.cond,t.options.guards);return!a||Or(t,a,f,n,o?void 0:e)}))===null||g===void 0?void 0:g.actions;if(!A)return[];var P=D(je(t,e,f,n,[ce(te(A),t.options.actions)],o,s),2),R=P[0],$=P[1];return f=$,h==null||h.push(f),R}case vr:{var A=y.get(f,n.data);if(!A)return[];var x=D(je(t,e,f,n,[ce(te(A),t.options.actions)],o,s),2),_=x[0],C=x[1];return f=C,h==null||h.push(f),_}case Ye:{var T=Dr(y,f,n);return o==null||o(T,r,n),T}case We:{f=Tr(f,n,[y],o?void 0:e),h==null||h.push(f);break}default:var k=Ae(y,t.options.actions),I=k.exec;if(o)o(k,f,n);else if(I&&h){var F=h.length-1;k=w(w({},k),{exec:function(G){for(var a=[],v=1;v<arguments.length;v++)a[v-1]=arguments[v];I.apply(void 0,V([h[F]],D(a),!1))}})}return k}}function d(y){var g,m,T=[];try{for(var b=j(y),A=b.next();!A.done;A=b.next()){var P=A.value,R=c(P);R&&(T=T.concat(R))}}catch($){g={error:$}}finally{try{A&&!A.done&&(m=b.return)&&m.call(b)}finally{if(g)throw g.error}}return l.forEach(function($){o($,f,n)}),l.length=0,T}var p=K(i.map(d));return[p,f]}const ki=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:ti,after:Mr,assign:Cr,cancel:Pr,choose:Ai,done:Ce,doneInvoke:Me,error:Oe,escalate:Ti,forwardTo:bi,getActionFunction:at,initEvent:we,isActionObject:Ei,log:wi,pure:Si,raise:_r,resolveActions:je,resolveLog:Rr,resolveRaise:Ir,resolveSend:xr,resolveStop:Dr,respond:mi,send:pe,sendParent:Mt,sendTo:vi,sendUpdate:yi,start:Ur,stop:Nr,toActionObject:Ae,toActionObjects:ce,toActivityDefinition:ct},Symbol.toStringTag,{value:"Module"}));var ut=[],ke=function(t,e){ut.push(t);var r=e(t);return ut.pop(),r},_i=function(t){return t(ut[ut.length-1])};function jr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[he]=function(){return this},e}function Ii(t,e,r,n){var i,o=kr(t.src),s=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[o.type],u=t.data?it(t.data,r,n):void 0,f=s?jt(s,t.id,u):jr(t.id);return f.meta=t,f}function jt(t,e,r){var n=jr(e);if(n.deferred=!0,ae(t)){var i=n.state=ke(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function xi(t){try{return typeof t.send=="function"}catch{return!1}}function Ri(t){return xi(t)&&"id"in t}function Pi(t){var e;return w((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[he]=function(){return this},e),t)}var lt=function(t){return t.type==="atomic"||t.type==="final"};function Lr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Le(t){return Lr(t).filter(function(e){return e.type!=="history"})}function $r(t){var e=[t];return lt(t)?e:e.concat(K(Le(t).map($r)))}function $e(t,e){var r,n,i,o,s,u,f,h,l=new Set(t),c=Lt(l),d=new Set(e);try{for(var p=j(d),y=p.next();!y.done;y=p.next())for(var g=y.value,m=g.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(C){r={error:C}}finally{try{y&&!y.done&&(n=p.return)&&n.call(p)}finally{if(r)throw r.error}}var T=Lt(d);try{for(var b=j(d),A=b.next();!A.done;A=b.next()){var g=A.value;if(g.type==="compound"&&(!T.get(g)||!T.get(g).length))c.get(g)?c.get(g).forEach(function(k){return d.add(k)}):g.initialStateNodes.forEach(function(k){return d.add(k)});else if(g.type==="parallel")try{for(var P=(s=void 0,j(Le(g))),R=P.next();!R.done;R=P.next()){var $=R.value;d.has($)||(d.add($),c.get($)?c.get($).forEach(function(k){return d.add(k)}):$.initialStateNodes.forEach(function(k){return d.add(k)}))}}catch(k){s={error:k}}finally{try{R&&!R.done&&(u=P.return)&&u.call(P)}finally{if(s)throw s.error}}}}catch(C){i={error:C}}finally{try{A&&!A.done&&(o=b.return)&&o.call(b)}finally{if(i)throw i.error}}try{for(var x=j(d),_=x.next();!_.done;_=x.next())for(var g=_.value,m=g.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(C){f={error:C}}finally{try{_&&!_.done&&(h=x.return)&&h.call(x)}finally{if(f)throw f.error}}return d}function Fr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(lt(n))return n.key}else return{}}var i={};return r.forEach(function(o){i[o.key]=Fr(o,e)}),i}function Lt(t){var e,r,n=new Map;try{for(var i=j(t),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Ui(t,e){var r=$e([t],e);return Fr(t,Lt(r))}function Fe(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ni(t){return V([],D(new Set(K(V([],D(t.map(function(e){return e.ownEvents})),!1)))),!1)}function dt(t,e){return e.type==="compound"?Le(e).some(function(r){return r.type==="final"&&Fe(t,r)}):e.type==="parallel"?Le(e).every(function(r){return dt(t,r)}):!1}function Di(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Br(t){return new Set(K(t.map(function(e){return e.tags})))}function qr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(L(t)||L(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return qr(t[i],e[i])})}function Ci(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Mi(t,e){var r=t.exec,n=w(w({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=mr,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||mr,this.meta=Di(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 Ni(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=we;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=we;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="."),L(e))return[e];var i=Object.keys(e);return i.concat.apply(i,V([],D(i.map(function(o){return n.toStrings(e[o],r).map(function(s){return o+r+s})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=It(e,["configuration","transitions","tags","machine"]);return w(w({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Nt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;H&&J(!!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}(),ji={deferEvents:!1},Vr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=w(w({},ji),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,Li=0,ft={bookId:function(){return"x:".concat(Li++)},register:function(t,e){return $t.set(t,e),t},get:function(t){return $t.get(t)},free:function(t){$t.delete(t)}};function Ft(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;H||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 $i(){var t=Ft();if(t&&"__xstate__"in t)return t.__xstate__}function Fi(t){if(Ft()){var e=$i();e&&e.register(t)}}function Bi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],o=!1,s=function(){if(!o){for(o=!0;i.length>0;){var h=i.shift();r=t.transition(r,h,f),n.forEach(function(l){return l.next(r)})}o=!1}},u=Pi({id:e.id,send:function(h){i.push(h),s()},getSnapshot:function(){return r},subscribe:function(h,l,c){var d=ot(h,l,c);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),f={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(f):r,u}var Bt={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 qi=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(l,c){if(be(l))return n.batch(l),n.state;var d=W(Ct(l,c));if(n.status===Q.Stopped)return H||J(!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(
|
|
16
|
-
Event: `).concat(JSON.stringify(
|
|
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,o,s=r.state,u=!1,f=[],h=function(p){var y=W(p);r.forward(y),s=ke(r,function(){return r.machine.transition(s,y,void 0,n||void 0)}),f.push.apply(f,V([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(g){return Mi(g,s)})),!1)),u=u||!!s.changed};try{for(var l=j(e),c=l.next();!c.done;c=l.next()){var d=c.value;h(d)}}catch(p){i={error:p}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(i)throw i.error}}s.changed=u,s.actions=f,r.update(s,W(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=W(e);if(i.name.indexOf(Rt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(Rt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=j(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,u=this.children.get(s);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));u.send(e)}}catch(f){r={error:f}}finally{try{o&&!o.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),q(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Q.Running)return jt(e,r);if(Sr(e))return this.spawnPromise(Promise.resolve(e),r);if(q(e))return this.spawnCallback(e,r);if(Ri(e))return this.spawnActor(e,r);if(li(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,w(w({},n),{id:r}));if(ai(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,w(w({},this.options),{parent:this,id:r.id||e.id})),o=w(w({},Bt),r);o.sync&&i.onTransition(function(u){n.send(et,{state:u,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(W(u,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Bi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(f){o||(s=f,i.removeChild(r),i.send(W(Me(r,f),{origin:r})))},function(f){if(!o){i.removeChild(r);var h=Oe(r,f);try{i.send(W(h,{origin:r}))}catch(l){pi(f,l,r),i.devTools&&i.devTools.send(h,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(f,h,l){var c=ot(f,h,l),d=!1;return e.then(function(p){d||(c.next(p),!d&&c.complete())},function(p){d||c.error(p)}),{unsubscribe:function(){return d=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,u=new Set,f,h=function(d){f=d,u.forEach(function(p){return p(d)}),!o&&i.send(W(d,{origin:r}))},l;try{l=e(h,function(d){s.add(d)})}catch(d){this.send(Oe(r,d))}if(Sr(l))return this.spawnPromise(l,r);var c=(n={id:r,send:function(d){return s.forEach(function(p){return p(d)})},subscribe:function(d){var p=ot(d);return u.add(p.next),{unsubscribe:function(){u.delete(p.next)}}},stop:function(){o=!0,q(l)&&l()},toJSON:function(){return{id:r}},getSnapshot:function(){return f}},n[he]=function(){return this},n);return this.children.set(r,c),c},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(f){o=f,i.send(W(f,{origin:r}))},function(f){i.removeChild(r),i.send(W(Oe(r,f),{origin:r}))},function(){i.removeChild(r),i.send(W(Me(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(f,h,l){return e.subscribe(f,h,l)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[he]=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){H||J(!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[he]=function(){return this},n))},t.prototype.attachDev=function(){var e=Ft();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(w(w({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:w({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Fi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[he]=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=_e,t}(),Vi=function(t){return L(t)?w(w({},Bt),{name:t}):w(w(w({},Bt),{name:fi()}),t)};function Gi(t,e){var r=Vi(e);return _i(function(n){if(!H){var i=ae(t)||q(t);J(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):jt(t,r.name)})}function _e(t,e){var r=new qi(t,e);return r}function Hi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return w(w({type:Ze},t),{toJSON:function(){t.onDone,t.onError;var e=It(t,["onDone","onError"]);return w(w({},e),{type:Ze,src:Hi(t.src)})}})}var Ie="",qt="#",Be="*",xe={},Re=function(t){return t[0]===qt},Ki=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},zi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");J(!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.")},Ji=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;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(Ki(),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:yr),this.id=this.config.id||V([this.machine.key],D(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:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,H||J(!("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?De(this.config.states,function(h,l){var c,d=new t(h,{},void 0,{parent:o,key:l});return Object.assign(o.idMap,w((c={},c[d.id]=d,c),d.idMap)),d}):xe;var u=0;function f(h){var l,c;h.order=u++;try{for(var d=j(Lr(h)),p=d.next();!p.done;p=d.next()){var y=p.value;f(y)}}catch(g){l={error:g}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}}f(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 l=h.event;return l===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(h){return Ae(h)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(h){return Ae(h)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(h,l){var c,d;if(ae(h)){var p=st(o.id,l);return o.machine.options.services=w((c={},c[p]=h,c),o.machine.options.services),ht({src:p,id:p})}else if(L(h.src)){var p=h.id||st(o.id,l);return ht(w(w({},h),{id:p,src:h.src}))}else if(ae(h.src)||q(h.src)){var p=h.id||st(o.id,l);return o.machine.options.services=w((d={},d[p]=h.src,d),o.machine.options.services),ht(w(w({id:p},h),{src:p}))}else{var y=h.src;return ht(w(w({id:st(o.id,l)},h),{src:y}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(h){return ct(h)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||$r(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,u=n.services,f=n.delays;return new t(this.config,{actions:w(w({},i),e.actions),activities:w(w({},o),e.activities),guards:w(w({},s),e.guards),services:w(w({},u),e.services),delays:w(w({},f),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return q(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:De(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===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Be});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var u=q(o)?"".concat(e.id,":delay[").concat(s,"]"):o,f=Mr(u,e.id);return e.onEntry.push(pe(f,{delay:o})),e.onExit.push(Pr(f)),f},i=be(r)?r.map(function(o,s){var u=n(o.delay,s);return w(w({},o),{event:u})}):K(Object.keys(r).map(function(o,s){var u=r[o],f=L(u)?{target:u}:u,h=isNaN(+o)?o:+o,l=n(h,s);return te(f).map(function(c){return w(w({},c),{event:l,delay:h})})}));return i.map(function(o){var s=o.delay;return w(w({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:Ne(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),u=[this];return u.push.apply(u,V([],D(K(s.map(function(f){return n.getStateNode(f).getStateNodes(i[f])}))),!1)),u},t.prototype.handles=function(e){var r=gr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(w(w({},r),{value:this.resolve(r.value),configuration:n,done:dt(n,this),tags:Br(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var u=j(Object.keys(e)),f=u.next();!f.done;f=u.next()){var h=f.value,l=e[h];if(l){var c=this.getStateNode(h),d=c._transition(l,r,n);d&&(s[h]=d)}}}catch(b){i={error:b}}finally{try{f&&!f.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}var p=Object.keys(s).map(function(b){return s[b]}),y=K(p.map(function(b){return b.transitions})),g=p.some(function(b){return b.transitions.length>0});if(!g)return this.next(r,n);var m=K(p.map(function(b){return b.entrySet})),T=K(Object.keys(s).map(function(b){return s[b].configuration}));return{transitions:y,entrySet:m,exitSet:K(p.map(function(b){return b.exitSet})),configuration:T,source:r,actions:K(Object.keys(s).map(function(b){return s[b].actions}))}},t.prototype._transition=function(e,r,n){return L(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,W(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,u=[],f=[],h;try{for(var l=j(this.getCandidates(s)),c=l.next();!c.done;c=l.next()){var d=c.value,p=d.cond,y=d.in,g=e.context,m=y?L(y)&&Re(y)?e.matches(Ne(this.getStateNodeById(y).path,this.delimiter)):Nt(Ne(y,this.delimiter),ii(this.path.slice(0,-2))(e.value)):!0,T=!1;try{T=!p||Or(this.machine,p,g,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(p.name||p.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
|
|
18
|
-
`).concat(R.message))}if(T&&m){d.target!==void 0&&(f=d.target),u.push.apply(u,V([],D(d.actions),!1)),h=d;break}}}catch(R){n={error:R}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}if(h){if(!f.length)return{transitions:[h],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var b=K(f.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!h.internal,P=[];return A||f.forEach(function(R){P.push.apply(P,V([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[h],entrySet:P,exitSet:A?[]:[this],configuration:b,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,u){var f,h,l,c,d=this,p=$e([],s?this.getStateNodes(s.value):[this]);try{for(var y=j(e),g=y.next();!g.done;g=y.next()){var m=g.value;(!Fe(p,m)||Fe(n.entrySet,m.parent))&&n.entrySet.push(m)}}catch(k){f={error:k}}finally{try{g&&!g.done&&(h=y.return)&&h.call(y)}finally{if(f)throw f.error}}try{for(var T=j(p),b=T.next();!b.done;b=T.next()){var m=b.value;(!Fe(e,m)||Fe(n.exitSet,m.parent))&&n.exitSet.push(m)}}catch(k){l={error:k}}finally{try{b&&!b.done&&(c=T.return)&&c.call(T)}finally{if(l)throw l.error}}var A=K(n.entrySet.map(function(k){var I=[];if(k.type!=="final")return I;var F=k.parent;if(!F.parent)return I;I.push(Ce(k.id,k.doneData),Ce(F.id,k.doneData?it(k.doneData,i,o):void 0));var G=F.parent;return G.type==="parallel"&&Le(G).every(function(a){return dt(n.configuration,a)})&&I.push(Ce(G.id)),I}));n.exitSet.sort(function(k,I){return I.order-k.order}),n.entrySet.sort(function(k,I){return k.order-I.order});var P=new Set(n.entrySet),R=new Set(n.exitSet),$=Array.from(P).map(function(k){var I=k.onEntry,F=k.activities.map(function(G){return Ur(G)});return ce(u?V(V([],D(I),!1),D(F),!1):V(V([],D(F),!1),D(I),!1),d.machine.options.actions)}).concat([A.map(_r)]),x=Array.from(R).map(function(k){return ce(V(V([],D(k.onExit),!1),D(k.activities.map(function(I){return Nr(I)})),!1),d.machine.options.actions)}),_=x.concat([ce(n.actions,this.machine.options.actions)]).concat($);if(r){var C=ce(K(V([],D(e),!1).sort(function(k,I){return I.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return _.concat([C])}return _},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=W(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=L(e)?this.resolve(rt(this.getResolvedPath(e))):this.resolve(e),f=n??this.machine.context;s=this.resolveState(oe.from(u,f))}if(!H&&o.name===Be)throw new Error("An event cannot have the wildcard type ('".concat(Be,"')"));if(this.strict&&!this.events.includes(o.name)&&!si(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var h=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},l=$e([],this.getStateNodes(s.value)),c=h.configuration.length?$e(l,h.configuration):l;return h.configuration=V([],D(c),!1),this.resolveTransition(h,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,V([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,u,f,h,l=this;o===void 0&&(o=we);var c=e.configuration,d=!r||e.transitions.length>0,p=d?e.configuration:r?r.configuration:[],y=dt(p,this),g=d?Ui(this.machine,c):void 0,m=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,T=this.getActions(new Set(p),y,e,n,o,r,i),b=r?w({},r.activities):{};try{for(var A=j(T),P=A.next();!P.done;P=A.next()){var R=P.value;try{for(var $=(f=void 0,j(R)),x=$.next();!x.done;x=$.next()){var _=x.value;_.type===Qe?b[_.activity.id||_.activity.type]=_:_.type===Ye&&(b[_.activity.id||_.activity.type]=!1)}}catch(Z){f={error:Z}}finally{try{x&&!x.done&&(h=$.return)&&h.call($)}finally{if(f)throw f.error}}}}catch(Z){s={error:Z}}finally{try{P&&!P.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}var C=D(je(this,r,n,o,T,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=C[0],I=C[1],F=D(ci(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),G=F[0],a=F[1],v=k.filter(function(Z){var Ue;return Z.type===Qe&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Ze}),S=v.reduce(function(Z,Ue){return Z[Ue.activity.id]=Ii(Ue.activity,l.machine,I,o),Z},r?w({},r.children):{}),M=new oe({value:g||r.value,context:I,_event:o,_sessionid:r?r._sessionid:null,historyValue:g?m?ui(m,g):void 0:r?r.historyValue:void 0,history:!g||e.source?r:void 0,actions:g?a:[],activities:g?b:r?r.activities:{},events:[],configuration:p,transitions:e.transitions,children:S,done:y,tags:Br(p),machine:this}),U=n!==I;M.changed=o.name===et||U;var O=M.history;O&&delete O.history;var ee=!y&&(this._transient||c.some(function(Z){return Z._transient}));if(!d&&(!ee||o.name===Ie))return M;var z=M;if(!y)for(ee&&(z=this.resolveRaisedTransition(z,{type:fr},o,i));G.length;){var fe=G.shift();z=this.resolveRaisedTransition(z,fe._event,o,i)}var No=z.changed||(O?!!z.actions.length||U||typeof O.value!=typeof z.value||!qr(z.value,O.value):void 0);return z.changed=No,z.history=O,z},t.prototype.getStateNode=function(e){if(Re(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=Re(e)?e.slice(qt.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"&&Re(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Dt(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||xe;switch(this.type){case"parallel":return De(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):xe});case"compound":if(L(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?De(e,function(o,s){return o?n.getStateNode(s).resolve(o):xe}):this.initialStateValue||{};default:return e||xe}},t.prototype.getResolvedPath=function(e){if(Re(e)){var r=this.machine.idMap[e.slice(qt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Dt(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=wr(this.states,function(n){return n.initialStateValue||xe},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=lt(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:V([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,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;L(r.target)?e=Re(r.target)?rt(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(lt(this))return[this];if(this.type==="compound"&&!this.initial)return H||J(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=nt(this.initialStateValue);return K(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(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 o=this.getStateNode(n);if(o.type==="history")return o.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:wr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(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?K(nt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=oi(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:K(nt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=K(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 o=this.states,s=new Set(this.ownEvents);if(o)try{for(var u=j(Object.keys(o)),f=u.next();!f.done;f=u.next()){var h=f.value,l=o[h];if(l.states)try{for(var c=(n=void 0,j(l.events)),d=c.next();!d.done;d=c.next()){var p=d.value;s.add("".concat(p))}}catch(y){n={error:y}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}}catch(y){e={error:y}}finally{try{f&&!f.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},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(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=hi(e.target),i="internal"in e?e.internal:n?n.some(function(f){return L(f)&&f[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=w(w({},e),{actions:ce(te(e.actions)),cond:Ar(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return w(w({},u),{target:u.target?u.target.map(function(f){return"#".concat(f.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 o=this.config.on,s=Be,u=o[s],f=u===void 0?[]:u,h=It(o,[typeof s=="symbol"?s:s+""]);i=K(Object.keys(h).map(function(b){!H&&b===Ie&&J(!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 A=Te(b,h[b]);return H||zi(n,b,A),A}).concat(Te(Be,f)))}var l=this.config.always?Te("",this.config.always):[],c=this.config.onDone?Te(String(Ce(this.id)),this.config.onDone):[];H||J(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=K(this.invoke.map(function(b){var A=[];return b.onDone&&A.push.apply(A,V([],D(Te(String(Me(b.id)),b.onDone)),!1)),b.onError&&A.push.apply(A,V([],D(Te(String(Oe(b.id)),b.onError)),!1)),A})),p=this.after,y=K(V(V(V(V([],D(c),!1),D(d),!1),D(i),!1),D(l),!1).map(function(b){return te(b).map(function(A){return n.formatTransition(A)})}));try{for(var g=j(p),m=g.next();!m.done;m=g.next()){var T=m.value;y.push(T)}}catch(b){e={error:b}}finally{try{m&&!m.done&&(r=g.return)&&r.call(g)}finally{if(e)throw e.error}}return y},t}(),Gr=!1;function ve(t,e){return!H&&!t.predictableActionArguments&&!Gr&&(Gr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Ji(t,e)}var N=Cr,Y=pe;/*! js-cookie v3.0.1 | MIT */function pt(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 Qi={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 Vt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=pt({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in s)s[f]&&(u+="; "+f,s[f]!==!0&&(u+="="+s[f].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var f=o[u].split("="),h=f.slice(1).join("=");try{var l=decodeURIComponent(f[0]);if(s[l]=t.read(h,l),i===l)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",pt({},o,{expires:-1}))},withAttributes:function(i){return Vt(this.converter,pt({},this.attributes,i))},withConverter:function(i){return Vt(pt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Gt=Vt(Qi,{path:"/"}),Yi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ht={exports:{}};(function(t,e){var r=typeof self<"u"?self:Yi,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(a){return a&&h.indexOf(Object.prototype.toString.call(a))>-1};function c(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function d(a){return typeof a!="string"&&(a=String(a)),a}function p(a){var v={next:function(){var S=a.shift();return{done:S===void 0,value:S}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function y(a){this.map={},a instanceof y?a.forEach(function(v,S){this.append(S,v)},this):Array.isArray(a)?a.forEach(function(v){this.append(v[0],v[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(v){this.append(v,a[v])},this)}y.prototype.append=function(a,v){a=c(a),v=d(v);var S=this.map[a];this.map[a]=S?S+", "+v:v},y.prototype.delete=function(a){delete this.map[c(a)]},y.prototype.get=function(a){return a=c(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(c(a))},y.prototype.set=function(a,v){this.map[c(a)]=d(v)},y.prototype.forEach=function(a,v){for(var S in this.map)this.map.hasOwnProperty(S)&&a.call(v,this.map[S],S,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(v,S){a.push(S)}),p(a)},y.prototype.values=function(){var a=[];return this.forEach(function(v){a.push(v)}),p(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(v,S){a.push([S,v])}),p(a)},u.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function g(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function m(a){return new Promise(function(v,S){a.onload=function(){v(a.result)},a.onerror=function(){S(a.error)}})}function T(a){var v=new FileReader,S=m(v);return v.readAsArrayBuffer(a),S}function b(a){var v=new FileReader,S=m(v);return v.readAsText(a),S}function A(a){for(var v=new Uint8Array(a),S=new Array(v.length),M=0;M<v.length;M++)S[M]=String.fromCharCode(v[M]);return S.join("")}function P(a){if(a.slice)return a.slice(0);var v=new Uint8Array(a.byteLength);return v.set(new Uint8Array(a)),v.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&f(a)?(this._bodyArrayBuffer=P(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||l(a))?this._bodyArrayBuffer=P(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(T)}),this.text=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(C)}),this.json=function(){return this.text().then(JSON.parse)},this}var $=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function x(a){var v=a.toUpperCase();return $.indexOf(v)>-1?v:a}function _(a,v){v=v||{};var S=v.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,v.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!S&&a._bodyInit!=null&&(S=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new y(v.headers)),this.method=x(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function C(a){var v=new FormData;return a.trim().split("&").forEach(function(S){if(S){var M=S.split("="),U=M.shift().replace(/\+/g," "),O=M.join("=").replace(/\+/g," ");v.append(decodeURIComponent(U),decodeURIComponent(O))}}),v}function k(a){var v=new y,S=a.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(M){var U=M.split(":"),O=U.shift().trim();if(O){var ee=U.join(":").trim();v.append(O,ee)}}),v}R.call(_.prototype);function I(a,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new y(v.headers),this.url=v.url||"",this._initBody(a)}R.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},I.error=function(){var a=new I(null,{status:0,statusText:""});return a.type="error",a};var F=[301,302,303,307,308];I.redirect=function(a,v){if(F.indexOf(v)===-1)throw new RangeError("Invalid status code");return new I(null,{status:v,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(v,S){this.message=v,this.name=S;var M=Error(v);this.stack=M.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function G(a,v){return new Promise(function(S,M){var U=new _(a,v);if(U.signal&&U.signal.aborted)return M(new s.DOMException("Aborted","AbortError"));var O=new XMLHttpRequest;function ee(){O.abort()}O.onload=function(){var z={status:O.status,statusText:O.statusText,headers:k(O.getAllResponseHeaders()||"")};z.url="responseURL"in O?O.responseURL:z.headers.get("X-Request-URL");var fe="response"in O?O.response:O.responseText;S(new I(fe,z))},O.onerror=function(){M(new TypeError("Network request failed"))},O.ontimeout=function(){M(new TypeError("Network request failed"))},O.onabort=function(){M(new s.DOMException("Aborted","AbortError"))},O.open(U.method,U.url,!0),U.credentials==="include"?O.withCredentials=!0:U.credentials==="omit"&&(O.withCredentials=!1),"responseType"in O&&u.blob&&(O.responseType="blob"),U.headers.forEach(function(z,fe){O.setRequestHeader(fe,z)}),U.signal&&(U.signal.addEventListener("abort",ee),O.onreadystatechange=function(){O.readyState===4&&U.signal.removeEventListener("abort",ee)}),O.send(typeof U._bodyInit>"u"?null:U._bodyInit)})}return G.polyfill=!0,o.fetch||(o.fetch=G,o.Headers=y,o.Request=_,o.Response=I),s.Headers=y,s.Request=_,s.Response=I,s.fetch=G,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Ht,Ht.exports);const Kt=Wi(Ht.exports),qe="nhostRefreshToken",Ve="nhostRefreshTokenExpiresAt",Hr=3,Kr=300,zt=5,Jt=0,Qt=1,re=10,Pe=20;class Ge 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:Qt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},zr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},Jr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},vt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},Yt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Yr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Wr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Xr={status:Pe,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:Pe,error:"already-signed-in",message:"User is already signed in"},Zr={status:Pe,error:"unauthenticated-user",message:"User is not authenticated"},Xi={status:Pe,error:"user-not-anonymous",message:"User is not anonymous"},en={status:Pe,error:"unverified-user",message:"Email needs verification"},tn={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},rn={status:Qt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},yt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function Zi(t){return new TextEncoder().encode(t)}function Ee(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 Wt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function nn(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function on(t){const{id:e}=t;return{...t,id:Wt(e),transports:t.transports}}function sn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let X=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function eo({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 X("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 X("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 X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(sn(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${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 X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class to{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const mt=new to;async function an(t){if(!nn())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Wt(t.challenge),user:{...t.user,id:Zi(t.user.id)},excludeCredentials:t.excludeCredentials.map(on)}};e.signal=mt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(f){throw eo({error:f,options:e})}finally{mt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function ro(t){return new TextDecoder("utf-8").decode(t)}async function no(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function io({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 X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(sn(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function oo(t,e=!1){var r,n;if(!nn())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(on));const o={...t,challenge:Wt(t.challenge),allowCredentials:i},s={};if(e){if(!await no())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');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=mt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(p){throw io({error:p,options:s})}finally{mt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:f,rawId:h,response:l,type:c}=u;let d;return l.userHandle&&(d=ro(l.userHandle)),{id:f,rawId:Ee(h),response:{authenticatorData:Ee(l.authenticatorData),clientDataJSON:Ee(l.clientDataJSON),signature:Ee(l.signature),userHandle:d},type:c,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const gt=typeof window<"u",wt=new Map,so=t=>gt&&typeof localStorage<"u"?localStorage.getItem(t):wt.get(t)??null,ao=(t,e)=>{gt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?wt.set(t,e):wt.has(t)&&wt.delete(t)},cn=(t,e)=>{if(t==="localStorage"||t==="web")return so;if(t==="cookie")return r=>gt?Gt.get(r)??null: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}`)},un=(t,e)=>{if(t==="localStorage"||t==="web")return ao;if(t==="cookie")return(r,n)=>{gt&&(n?Gt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Gt.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,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.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,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=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},ye=({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},Et=()=>typeof window<"u",ln=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Kt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.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 s={message:"Network Error",status:Jt,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>ln(t,"POST",{token:r,body:e}),dn=(t,e)=>ln(t,"GET",{token:e}),Xt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(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),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let f=Object.fromEntries(u);r.startsWith("/")&&(f={...o,...f});let h=i.pathname;return s.pathname.length>1&&(h+=s.pathname.slice(1)),{...n,redirectTo:Xt(s.origin+h,f)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")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>"u")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 o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=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,}))$/),St=t=>!!t&&typeof t=="string"&&t.length>=Hr,er=t=>!!t&&typeof t=="string",fn=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),hn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=cn(r,n),f=un(r,n),h=async(l,c,d)=>(await le(`${t}${l}`,c,d)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:yt,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:Y("SIGNED_IN"),reportSignedOut:Y("SIGNED_OUT"),reportTokenChanged:Y("TOKEN_CHANGED"),incrementTokenImportAttempts:N({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:N(()=>(f(Ve,null),f(qe,null),{...yt})),clearContextExceptRefreshToken:N(({refreshToken:{value:l}})=>(f(Ve,null),{...yt,refreshToken:{value:l}})),saveSession:N({user:(l,{data:c})=>{var d;return((d=c==null?void 0:c.session)==null?void 0:d.user)||null},accessToken:(l,{data:c})=>{if(c.session){const{accessTokenExpiresIn:d,accessToken:p}=c.session,y=new Date(Date.now()+d*1e3);return f(Ve,y.toISOString()),{value:p,expiresAt:y}}return f(Ve,null),{value:null,expiresAt:null}},refreshToken:(l,{data:c})=>{var d;const p=((d=c.session)==null?void 0:d.refreshToken)||null;return p&&f(qe,p),{value:p}}}),saveMfaTicket:N({mfa:(l,c)=>{var d;return(d=c.data)==null?void 0:d.mfa}}),resetTimer:N({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:N({refreshTimer:(l,c)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:N({errors:({errors:l},{data:{error:c}})=>({...l,authentication:c})}),resetErrors:N({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:N({errors:({errors:l},{data:{error:c}})=>({...l,registration:c})}),destroyRefreshToken:N({refreshToken:l=>(f(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Zt("refreshToken"),Zt("type"))},broadcastToken:l=>{if(s)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isAnonymous:(l,c)=>{var d;return!!((d=l.user)!=null&&d.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{const{expiresAt:c}=l.accessToken;return c?l.refreshTimer.lastAttempt?l.refreshTimer.attempts>zt?!1:Date.now()-l.refreshTimer.lastAttempt.getTime()>Math.pow(2,l.refreshTimer.attempts-1)*5e3:i&&Date.now()-l.refreshTimer.startedAt.getTime()>i*1e3?!0:c.getTime()-Date.now()-1e3*Kr<=0:!1},shouldRetryImportToken:(l,c)=>l.importTokenAttempts<zt&&(c.data.error.status===Jt||c.data.error.status>=500),unverified:(l,{data:{error:c}})=>c.status===401&&(c.message==="Email is not verified"||c.error==="unverified-user"),hasSession:(l,c)=>{var d;return!!((d=c.data)!=null&&d.session)},hasMfaTicket:(l,c)=>{var d;return!!((d=c.data)!=null&&d.mfa)}},services:{signInPassword:(l,{email:c,password:d})=>de(c)?St(d)?h("/signin/email-password",{email:c,password:d}):Promise.reject({error:vt}):Promise.reject({error:ue}),passwordlessSms:(l,{phoneNumber:c,options:d})=>{var p;return er(c)?(p=l.user)!=null&&p.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:c,options:ne(e,d)},l.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:c,options:ne(e,d)}):Promise.reject({error:Yt})},passwordlessSmsOtp:(l,{phoneNumber:c,otp:d})=>er(c)?h("/signin/passwordless/sms/otp",{phoneNumber:c,otp:d}):Promise.reject({error:Yt}),passwordlessEmail:(l,{email:c,options:d})=>{var p;return de(c)?(p=l.user)!=null&&p.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:c,options:ne(e,d)},l.accessToken.value):h("/signin/passwordless/email",{email:c,options:ne(e,d)}):Promise.reject({error:ue})},signInAnonymous:l=>h("/signin/anonymous"),signInMfaTotp:(l,c)=>{var d;const p=c.ticket||((d=l.mfa)==null?void 0:d.ticket);return p?fn(p)?h("/signin/mfa/totp",{ticket:p,otp:c.otp}):Promise.reject({error:Qr}):Promise.reject({error:Yr})},signInSecurityKeyEmail:async(l,{email:c})=>{if(!de(c))throw new Ge(ue);const d=await h("/signin/webauthn",{email:c});let p;try{p=await oo(d)}catch(y){throw new Ge(y)}return h("/signin/webauthn/verify",{email:c,credential:p})},refreshToken:async(l,c)=>{const d=c.type==="TRY_TOKEN"?c.token:l.refreshToken.value;return{session:await h("/token",{refreshToken:d}),error:null}},signout:(l,c)=>h("/signout",{refreshToken:l.refreshToken.value,all:!!c.all}),signUpEmailPassword:async(l,{email:c,password:d,options:p})=>{var y;return de(c)?St(d)?(y=l.user)!=null&&y.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:c,password:d,options:ne(e,p)},l.accessToken.value):h("/signup/email-password",{email:c,password:d,options:ne(e,p)}):Promise.reject({error:vt}):Promise.reject({error:ue})},signUpSecurityKey:async(l,{email:c,options:d})=>{if(!de(c))return Promise.reject({error:ue});const p=d==null?void 0:d.nickname;p&&delete d.nickname;const y=await h("/signup/webauthn",{email:c,options:d});let g;try{g=await an(y)}catch(m){throw new Ge(m)}return h("/signup/webauthn/verify",{credential:g,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:p}})},importRefreshToken:async l=>{if(l.user&&l.refreshToken.value&&l.accessToken.value&&l.accessToken.expiresAt)return{session:{accessToken:l.accessToken.value,accessTokenExpiresIn:l.accessToken.expiresAt.getTime()-Date.now(),refreshToken:l.refreshToken.value,user:l.user},error:null};let c=null;if(s){const p=Ke("refreshToken")||null;if(p)try{return{session:await h("/token",{refreshToken:p}),error:null}}catch(y){c=y.error}else{const y=Ke("error");if(y)return Promise.reject({session:null,error:{status:re,error:y,message:Ke("errorDescription")||y}})}}const d=await u(qe);if(d)try{return{session:await h("/token",{refreshToken:d}),error:null}}catch(p){c=p.error}return c?Promise.reject({error:c,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>Math.pow(2,l-1)*5e3}})},pn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({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:N({error:n=>ue}),saveRequestError:N({error:(n,{data:{error:i}})=>i}),reportError:Y(n=>({type:"ERROR",error:n.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),vn=({backendUrl:t,interpreter:e})=>ve({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:N({error:r=>vt}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!St(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),co=({backendUrl:t,interpreter:e})=>ve({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:N({error:r=>zr}),saveInvalidMfaCodeError:N({error:r=>Jr}),saveError:N({error:(r,{data:{error:n}})=>n}),saveGeneration:N({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:Y((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS"),reportGeneratedSuccess:Y("GENERATED"),reportGeneratedError:Y(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 dn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),yn=({backendUrl:t,clientUrl:e})=>ve({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:N({error:r=>ue}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),mn=({backendUrl:t,clientUrl:e})=>ve({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:N({error:r=>ue}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let tr=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...f}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=hn({...f,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",h=>{var l;const c=(l=this.interpreter)==null?void 0:l.getSnapshot().context.refreshToken.value;this.interpreter&&h.data!==c&&this.interpreter.send("TRY_TOKEN",{token:h.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||_e(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(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 gn extends tr{constructor({...e}){super({...e,autoSignIn:Et()&&e.autoSignIn,autoRefreshToken:Et()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const uo=gn,wn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await an(n)}catch(s){throw new Ge(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},En=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})})}),Sn=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})})}),lo=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:""})})}),fo=(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})})}),bn=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})})}),Tn=(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})})}),An=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,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})})}),On=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),rr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),kn=(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:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),_n=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),nr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),In=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),xn=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:Zr});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})})}),ir=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.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})})}),Rn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class Pn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var f;this.url=e,this._client=new tr({backendUrl:e,clientUrl:typeof window<"u"&&((f=window.location)==null?void 0:f.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await Rn(r,n,i)):ye(await ir(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await An(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Xt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return Et()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await On(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:en}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await kn(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await rr(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await In(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await nr(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await _n(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:rn,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await xn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=_e(yn(this._client)).start(),{error:i}=await bn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=_e(vn(this._client)).start(),{error:i}=await Sn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=_e(mn(this._client)).start(),{error:i}=await Tn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=_e(pn(this._client)).start(),{error:i}=await En(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 rr(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await nr(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await ir(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await wn(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:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});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:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});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;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Wn(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:Wr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Xr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:tn}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((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(o=>{if(!o.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 Un=typeof self=="object"?self.FormData:window.FormData,ho=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function po(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var or={exports:{}};(function(t,e){var r=typeof self<"u"?self:ho,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(a){return a&&h.indexOf(Object.prototype.toString.call(a))>-1};function c(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function d(a){return typeof a!="string"&&(a=String(a)),a}function p(a){var v={next:function(){var S=a.shift();return{done:S===void 0,value:S}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function y(a){this.map={},a instanceof y?a.forEach(function(v,S){this.append(S,v)},this):Array.isArray(a)?a.forEach(function(v){this.append(v[0],v[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(v){this.append(v,a[v])},this)}y.prototype.append=function(a,v){a=c(a),v=d(v);var S=this.map[a];this.map[a]=S?S+", "+v:v},y.prototype.delete=function(a){delete this.map[c(a)]},y.prototype.get=function(a){return a=c(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(c(a))},y.prototype.set=function(a,v){this.map[c(a)]=d(v)},y.prototype.forEach=function(a,v){for(var S in this.map)this.map.hasOwnProperty(S)&&a.call(v,this.map[S],S,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(v,S){a.push(S)}),p(a)},y.prototype.values=function(){var a=[];return this.forEach(function(v){a.push(v)}),p(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(v,S){a.push([S,v])}),p(a)},u.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function g(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function m(a){return new Promise(function(v,S){a.onload=function(){v(a.result)},a.onerror=function(){S(a.error)}})}function T(a){var v=new FileReader,S=m(v);return v.readAsArrayBuffer(a),S}function b(a){var v=new FileReader,S=m(v);return v.readAsText(a),S}function A(a){for(var v=new Uint8Array(a),S=new Array(v.length),M=0;M<v.length;M++)S[M]=String.fromCharCode(v[M]);return S.join("")}function P(a){if(a.slice)return a.slice(0);var v=new Uint8Array(a.byteLength);return v.set(new Uint8Array(a)),v.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&f(a)?(this._bodyArrayBuffer=P(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||l(a))?this._bodyArrayBuffer=P(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(T)}),this.text=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(C)}),this.json=function(){return this.text().then(JSON.parse)},this}var $=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function x(a){var v=a.toUpperCase();return $.indexOf(v)>-1?v:a}function _(a,v){v=v||{};var S=v.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,v.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!S&&a._bodyInit!=null&&(S=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new y(v.headers)),this.method=x(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function C(a){var v=new FormData;return a.trim().split("&").forEach(function(S){if(S){var M=S.split("="),U=M.shift().replace(/\+/g," "),O=M.join("=").replace(/\+/g," ");v.append(decodeURIComponent(U),decodeURIComponent(O))}}),v}function k(a){var v=new y,S=a.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(M){var U=M.split(":"),O=U.shift().trim();if(O){var ee=U.join(":").trim();v.append(O,ee)}}),v}R.call(_.prototype);function I(a,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new y(v.headers),this.url=v.url||"",this._initBody(a)}R.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},I.error=function(){var a=new I(null,{status:0,statusText:""});return a.type="error",a};var F=[301,302,303,307,308];I.redirect=function(a,v){if(F.indexOf(v)===-1)throw new RangeError("Invalid status code");return new I(null,{status:v,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,v){this.message=a,this.name=v;var S=Error(a);this.stack=S.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function G(a,v){return new Promise(function(S,M){var U=new _(a,v);if(U.signal&&U.signal.aborted)return M(new s.DOMException("Aborted","AbortError"));var O=new XMLHttpRequest;function ee(){O.abort()}O.onload=function(){var z={status:O.status,statusText:O.statusText,headers:k(O.getAllResponseHeaders()||"")};z.url="responseURL"in O?O.responseURL:z.headers.get("X-Request-URL");var fe="response"in O?O.response:O.responseText;S(new I(fe,z))},O.onerror=function(){M(new TypeError("Network request failed"))},O.ontimeout=function(){M(new TypeError("Network request failed"))},O.onabort=function(){M(new s.DOMException("Aborted","AbortError"))},O.open(U.method,U.url,!0),U.credentials==="include"?O.withCredentials=!0:U.credentials==="omit"&&(O.withCredentials=!1),"responseType"in O&&u.blob&&(O.responseType="blob"),U.headers.forEach(function(z,fe){O.setRequestHeader(fe,z)}),U.signal&&(U.signal.addEventListener("abort",ee),O.onreadystatechange=function(){O.readyState===4&&U.signal.removeEventListener("abort",ee)}),O.send(typeof U._bodyInit>"u"?null:U._bodyInit)})}return G.polyfill=!0,o.fetch||(o.fetch=G,o.Headers=y,o.Request=_,o.Response=I),s.Headers=y,s.Request=_,s.Response=I,s.fetch=G,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(or,or.exports);const sr=po(or.exports),vo=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},Nn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const f={};i&&(f["x-nhost-file-id"]=i),o&&(f["x-nhost-bucket-id"]=o),n&&(f["x-nhost-file-name"]=vo(n)),s&&(f["x-hasura-admin-secret"]=s),r&&(f.Authorization=`Bearer ${r}`);const h=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const l=await sr(h,{method:"POST",headers:f,body:e});return l.ok?{fileMetadata:await l.json(),error:null}:{error:{status:l.status,message:await l.text(),error:l.statusText},fileMetadata:null}}catch(l){return{error:{status:0,message:l.message,error:l.message},fileMetadata:null}}return new Promise(l=>{console.log("NOOOOOOO");let c=new XMLHttpRequest;c.responseType="json",c.onload=()=>c.status<200&&c.status>=300?l({fileMetadata:null,error:{error:c.statusText,message:c.statusText,status:c.status}}):l({fileMetadata:c.response,error:null}),c.onerror=()=>l({fileMetadata:null,error:{error:c.statusText,message:c.statusText,status:c.status}}),u&&c.upload.addEventListener("progress",u,!1),c.open("POST",h,!0),Object.entries(f).forEach(([d,p])=>{c.setRequestHeader(d,p)}),c.send(e)})};class Dn{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return Nn(this.url,r,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await sr(`${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 sr(`${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}`}}}const Cn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Mn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Dn({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new Un,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Cn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}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 bt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},jn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...bt},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:N({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:N({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:N({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:N({progress:t=>null,loaded:t=>0}),resetContext:N(t=>bt),addFile:N({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 Un;i.append("file",n);let o=0;return Nn(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:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,f=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:f})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:f,bucketId:h}=s;r({type:"UPLOAD_DONE",id:f,bucketId:h})}}),()=>{}}}}),{pure:ar,sendParent:Tt}=ki,yo=()=>ve({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:N((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:N({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:N({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:N({loaded:t=>0}),startProgress:N({progress:t=>0}),resetProgress:N({progress:t=>null}),addItem:N((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Gi(jn().withConfig({actions:{sendProgress:Tt((u,{additions:f})=>({type:"UPLOAD_PROGRESS",additions:f})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...bt,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:N({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:ar(t=>t.files.map(e=>Y({type:"DESTROY"},{to:e.id}))),upload:ar((t,e)=>t.files.map(r=>Y(e,{to:r.id}))),cancel:ar(t=>t.files.map(e=>Y({type:"CANCEL"},{to:e.id})))}}),mo=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})})}),go=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 o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),wo=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function At(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 o=n.match(wo);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:f=1337}=o.groups,h=bo(e);return h||`${s}://${u}:${f}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function Eo(){return typeof window<"u"}function So(){return typeof process<"u"&&process.env}function bo(t){return Eo()||!So()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Ln(t){const e="subdomain"in t||"backendUrl"in t?At(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Pn({url:e,...t})}function $n(t){const e="subdomain"in t||"backendUrl"in t?At(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Fn({url:e,...t})}class Fn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Kt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.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}`}:{}}}var cr={},Bn={},Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});var To=function(){function t(e){this.value=e}return t}();Ot.EnumType=To;var kt={};Object.defineProperty(kt,"__esModule",{value:!0});var Ao=function(){function t(e){this.value=e}return t.prototype.toJSON=function(){return"$"+this.value},t}();kt.VariableType=Ao,function(t){Object.defineProperty(t,"__esModule",{value:!0});var e=Ot,r=kt;t.configFields=["__args","__alias","__aliasFor","__variables","__directives","__on","__all_on","__typeName","__name"];function n(c){if(c instanceof e.EnumType)return c.value;if(c instanceof r.VariableType)return"$"+c.value;if(typeof c!="object"||c===null)return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(function(p){return n(p)}).join(", ")+"]";var d=Object.keys(c).map(function(p){return p+": "+n(c[p])}).join(", ");return"{"+d+"}"}function i(c){var d=[];for(var p in c)d.push(p+": "+n(c[p]));return d.join(", ")}function o(c){var d=[];for(var p in c)d.push("$"+p+": "+c[p]);return d.join(", ")}function s(c){var d=Object.keys(c)[0],p=c[d];if(typeof p=="boolean"||typeof p=="object"&&Object.keys(p).length===0)return d;if(typeof p=="object"){var y=[];for(var g in p){var m=n(p[g]).replace(/"/g,"");y.push(g+": "+m)}return d+"("+y.join(", ")+")"}else throw new Error("Unsupported type for directive: "+typeof p+`. Types allowed: object, boolean.
|
|
20
|
-
`+("Offending object: "+JSON.stringify(c)))}function u(c){return Array(c*4+1).join(" ")}function f(c,d){return t.configFields.indexOf(c)==-1&&d.indexOf(c)==-1}function h(c,d,p,y){Object.keys(c).filter(function(g){return f(g,y.ignoreFields)}).forEach(function(g){var m=c[g];if(typeof m=="object"){if(Array.isArray(m)&&(m=m.find(function(F){return F&&typeof F=="object"}),!m)){p.push([""+g,d]);return}var T=Object.keys(m).filter(function(F){return f(F,y.ignoreFields)}).length,b=T>0,A=typeof m.__args=="object"&&Object.keys(m.__args).length>0,P=typeof m.__directives=="object",R=m.__all_on instanceof Array,$=typeof m.__on=="object",x=""+g;if(typeof m.__name=="string"&&(x=x+" "+m.__name),typeof m.__aliasFor=="string"&&(x=x+": "+m.__aliasFor),typeof m.__variables=="object"&&Object.keys(m.__variables).length>0)x=x+" ("+o(m.__variables)+")";else if(A||P){var _="",C="";P&&(C=Object.entries(m.__directives).map(function(F){var G;return"@"+s((G={},G[F[0]]=F[1],G))}).join(" ")),A&&(_="("+i(m.__args)+")");var k=P&&A?" ":"";x=x+" "+_+k+C}if(p.push([x+(b||$||R?" {":""),d]),h(m,d+1,p,y),R&&m.__all_on.forEach(function(F){p.push(["..."+F,d+1])}),$){var I=m.__on instanceof Array?m.__on:[m.__on];I.forEach(function(F){var G=F.__typeName;p.push(["... on "+G+" {",d+1]),h(F,d+2,p,y),p.push(["}",d+1])})}(b||$||R)&&p.push(["}",d])}else(y.includeFalsyKeys===!0||m)&&p.push([""+g,d])})}function l(c,d){if(d===void 0&&(d={}),!c||typeof c!="object")throw new Error("query object not specified");if(Object.keys(c).length==0)throw new Error("query object has no data");d.ignoreFields instanceof Array||(d.ignoreFields=[]);var p=[];h(c,0,p,d);var y="";return p.forEach(function(g){var m=g[0],T=g[1];d.pretty?(y&&(y+=`
|
|
21
|
-
`),y+=u(T)+m):(y&&(y+=" "),y+=m)}),y}t.jsonToGraphQLQuery=l}(Bn),function(t){function e(i){for(var o in i)Object.prototype.hasOwnProperty.call(t,o)||(t[o]=i[o])}Object.defineProperty(t,"__esModule",{value:!0}),e(Bn);var r=Ot;t.EnumType=r.EnumType;var n=kt;t.VariableType=n.VariableType}(cr);const Oo=(t,e)=>t.introspection.__schema.types.find(r=>Object.entries(e).every(([n,i])=>r[n]===i)),qn=(t,e)=>{var r;const n=(r=t.introspection.__schema[`${e.toLowerCase()}Type`])==null?void 0:r.name;if(!n)return null;const i=Oo(t,{kind:"OBJECT",name:n});if(!i)throw new Error(`Could not find the root operation type for ${e}`);return i},Vn=(t,e)=>{var r;if(!t)return[];const n=qn(t,e);return((r=n==null?void 0:n.fields)==null?void 0:r.map(i=>i.name))??[]},Gn=(t,e)=>{const r=t.introspection.__schema.types.find(n=>"name"in n&&e&&"name"in e&&n.name===e.name);if(!r)throw new Error("Could not find type");return r},ko=(t,e)=>{var r,n;const i=(n=(r=e==null?void 0:e.args)==null?void 0:r.find(o=>o.name===t))==null?void 0:n.type;if(!i)throw new Error(`Could not determine the type of the argument ${t}`);return i},_o=(t,e,r)=>{var n,i;const o="type"in r?r.type:r,s=Gn(t,ze(t,o));return s.kind==="OBJECT"||s.kind==="INTERFACE"?((n=s.fields)==null?void 0:n.find(f=>f.name===e))||null:s.kind==="INPUT_OBJECT"&&((i=s==null?void 0:s.inputFields)==null?void 0:i.find(f=>f.name===e))||null},Io=(t,e,r)=>{var n;const i=qn(t,e),o=(n=i==null?void 0:i.fields)==null?void 0:n.find(s=>s.name===r);if(!o)throw new Error(`Could not find root operation ${r}`);return o},ze=(t,e)=>{var r;if("type"in e)return ze(t,e.type);if(e.kind==="NON_NULL"||e.kind==="LIST")return ze(t,e.ofType);const n=(r=t.introspection.__schema.types)==null?void 0:r.find(i=>"name"in i&&i.name===e.name);if(!n)throw new Error("not found");return n},ur=(t,e)=>{var r;if(e.kind==="NON_NULL")return`${ur(t,e.ofType)}!`;if(e.kind==="LIST")return`[${ur(t,e.ofType)}]`;const n=(r=t.introspection.__schema.types)==null?void 0:r.find(i=>"name"in i&&i.name===e.name);if(!n)throw new Error(`Could not find type ${e.name}`);if(!("name"in n))throw new Error(`Could not determine GraphQL type name for ${e.name}`);return n.name},lr=(t,e=!0,r,n={},i={},o="")=>{var s;const u={},f=e!==!0&&e.select||{},h=e!==!0&&e.variables||{},l={},c=e!==!0&&e.on;if(c&&(u.__typename=!0,u.__on=Object.keys(c).map(d=>{const p=o?`${o}_on_${d}`:`on_${d}`,{query:y,variables:g,variablesValues:m}=lr(t,c[d],Gn(t,{kind:"OBJECT",name:d}),n,i,p);return n={...n,...g},i={...i,...m},{__typeName:d,...y}})),"type"in r&&Object.keys(h).forEach(d=>{const p=o?`${o}_${d}`:d;n[p]=ur(t,ko(d,r)),l[d]=new cr.VariableType(p),i[d]=h[d]}),Object.keys(f).length===0){const d=ze(t,r);d.kind==="OBJECT"&&((s=d.fields)==null||s.forEach(p=>{const y=ze(t,p.type);(y.kind==="SCALAR"||y.kind==="ENUM")&&(u[p.name]=!0)}))}else Object.entries(f).forEach(([d,p])=>{const y=o?`${o}_${d}`:d,g=_o(t,d,r);if(!g)throw new Error(`Field ${d} is not defined`);const{query:m,variables:T,variablesValues:b}=lr(t,p,g,n,i,y);u[d]=m,n={...n,...T},i={...i,...b}});return{query:{...u,__args:l},variables:n,variablesValues:i}},Hn=(t,e,r,n={})=>{if(!t)throw new Error("Schema is not defined");const{query:i,variables:o,variablesValues:s}=lr(t,n,Io(t,e,r));return{query:cr.jsonToGraphQLQuery({[e.toLowerCase()]:{__variables:o,[r]:i}},{pretty:!0}),variables:s}};function xo(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Kn(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 Ro(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Kn(n)}catch{}return{query:t,operationName:r}}const e=Kn(t);return{query:Se.print(t),operationName:e}}class Po{constructor(e){const{url:r,adminSecret:n,schema:i}=e;this._url=r,this.accessToken=null,this.adminSecret=n,this.query=Vn(i,"Query").reduce((o,s)=>(o[s]=async u=>{const{query:f,variables:h}=Hn(i,"Query",s,u),{data:l,error:c}=await this.request(f,h);if(c)throw"message"in c?new Error(c.message):new Error(c[0].message);return l[s]},o),{}),this.mutation=Vn(i,"Mutation").reduce((o,s)=>(o[s]=async u=>{const{query:f,variables:h}=Hn(i,"Mutation",s,u),{data:l,error:c}=await this.request(f,h);if(c)throw"message"in c?new Error(c.message):new Error(c[0].message);return l[s]},o),{})}async request(e,...r){const[n,i]=r,o=xo(e,n,i),{headers:s,...u}=i||{},{query:f,operationName:h}=Ro(o.document);try{const l=await Kt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:f,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!l.ok)return{data:null,error:{error:l.statusText,message:l.statusText,status:l.status}};const{data:c,errors:d}=await l.json();return d?{data:null,error:d}:typeof c!="object"||Array.isArray(c)||c===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:c,error:null}}catch(l){const c=l;return{data:null,error:{message:c.message,status:c.name==="AbortError"?0:500,error:c.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 zn(t){const e="subdomain"in t||"backendUrl"in t?At(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Po({url:e,...t})}function Jn(t){const e="subdomain"in t||"backendUrl"in t?At(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Mn({url:e,...t})}const Uo=t=>new Qn(t);class Qn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:f=!0,schema:h,...l}){this.auth=Ln({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:f,...l}),this.storage=Jn({adminSecret:s,...l}),this.functions=$n({adminSecret:s,...l}),this.graphql=zn({adminSecret:s,schema:h,...l}),this.auth.onAuthStateChanged((c,d)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const d=c==null?void 0:c.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}E.AuthClient=tr,E.AuthClientSSR=uo,E.AuthCookieClient=gn,E.CodifiedError=Ge,E.EMAIL_NEEDS_VERIFICATION=en,E.HasuraAuthClient=Pn,E.HasuraStorageApi=Dn,E.HasuraStorageClient=Mn,E.INITIAL_FILE_CONTEXT=bt,E.INITIAL_MACHINE_CONTEXT=yt,E.INVALID_EMAIL_ERROR=ue,E.INVALID_MFA_CODE_ERROR=Jr,E.INVALID_MFA_TICKET_ERROR=Qr,E.INVALID_MFA_TYPE_ERROR=zr,E.INVALID_PASSWORD_ERROR=vt,E.INVALID_PHONE_NUMBER_ERROR=Yt,E.INVALID_REFRESH_TOKEN=tn,E.INVALID_SIGN_IN_METHOD=rn,E.MIN_PASSWORD_LENGTH=Hr,E.NETWORK_ERROR_CODE=Jt,E.NHOST_JWT_EXPIRES_AT_KEY=Ve,E.NHOST_REFRESH_TOKEN_KEY=qe,E.NO_MFA_TICKET_ERROR=Yr,E.NO_REFRESH_TOKEN=Wr,E.NhostClient=Qn,E.NhostFunctionsClient=Fn,E.OTHER_ERROR_CODE=Qt,E.REFRESH_TOKEN_MAX_ATTEMPTS=zt,E.STATE_ERROR_CODE=Pe,E.TOKEN_REFRESHER_RUNNING_ERROR=Xr,E.TOKEN_REFRESH_MARGIN=Kr,E.USER_ALREADY_SIGNED_IN=se,E.USER_NOT_ANONYMOUS=Xi,E.USER_UNAUTHENTICATED=Zr,E.VALIDATION_ERROR_CODE=re,E.activateMfaPromise=fo,E.addSecurityKeyPromise=wn,E.appendImageTransformationParameters=Cn,E.changeEmailPromise=En,E.changePasswordPromise=Sn,E.createAuthClient=Ln,E.createAuthMachine=hn,E.createChangeEmailMachine=pn,E.createChangePasswordMachine=vn,E.createEnableMfaMachine=co,E.createFileUploadMachine=jn,E.createFunctionsClient=$n,E.createGraphqlClient=zn,E.createMultipleFilesUploadMachine=yo,E.createNhostClient=Uo,E.createResetPasswordMachine=yn,E.createSendVerificationEmailMachine=mn,E.createStorageClient=Jn,E.encodeQueryParameters=Xt,E.generateQrCodePromise=lo,E.getAuthenticationResult=ye,E.getFetch=dn,E.getParameterByName=Ke,E.getSession=He,E.isBrowser=Et,E.isValidEmail=de,E.isValidPassword=St,E.isValidPhoneNumber=er,E.isValidTicket=fn,E.localStorageGetter=cn,E.localStorageSetter=un,E.postFetch=le,E.removeParameterFromWindow=Zt,E.resetPasswordPromise=bn,E.rewriteRedirectTo=ne,E.sendVerificationEmailPromise=Tn,E.signInAnonymousPromise=An,E.signInEmailPasswordPromise=On,E.signInEmailPasswordlessPromise=rr,E.signInEmailSecurityKeyPromise=kn,E.signInMfaTotpPromise=_n,E.signInSmsPasswordlessOtpPromise=In,E.signInSmsPasswordlessPromise=nr,E.signOutPromise=xn,E.signUpEmailPasswordPromise=ir,E.signUpEmailSecurityKeyPromise=Rn,E.uploadFilePromise=mo,E.uploadMultipleFilesPromise=go,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
|
|
14
|
+
***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},m.apply(this,arguments)};function Ot(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 M(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 D(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function F(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}var $;(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"})($||($={}));var ie;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ie||(ie={}));var Ye=$.Start,We=$.Stop,me=$.Raise,ge=$.Send,kt=$.Cancel,sr=$.NullEvent,Je=$.Assign,Fn=$.After,qn=$.DoneState,Qe=$.Log,ar=$.Init,Xe=$.Invoke,Gn=$.ErrorExecution,xt=$.ErrorPlatform,It=$.ErrorCustom,Ze=$.Update,cr=$.Choose,ur=$.Pure;const Vn=Object.freeze(Object.defineProperty({__proto__:null,after:Fn,assign:Je,cancel:kt,choose:cr,doneState:qn,error:It,errorExecution:Gn,errorPlatform:xt,init:ar,invoke:Xe,log:Qe,nullEvent:sr,pure:ur,raise:me,send:ge,start:Ye,stop:We,update:Ze},Symbol.toStringTag,{value:"Module"}));var lr=".",dr={},Rt="xstate.guard",Hn="",G=process.env.NODE_ENV==="production",et;function Pt(t,e,r){r===void 0&&(r=lr);var n=De(t,r),i=De(e,r);return L(i)?L(n)?i===n:!1:L(n)?n in i:Object.keys(n).every(function(o){return o in i?Pt(n[o],i[o]):!1})}function hr(t){try{return L(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 _t(t,e){try{return Te(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function Kn(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function De(t,e){if(Kn(t))return t.value;if(Te(t))return tt(t);if(typeof t!="string")return t;var r=_t(t,e);return tt(r)}function tt(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 Ne(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];r[o]=e(t[o],o,t,i)}return r}function fr(t,e,r){var n,i,o={};try{for(var s=M(Object.keys(t)),u=s.next();!u.done;u=s.next()){var d=u.value,f=t[d];r(f)&&(o[d]=e(f,d,t))}}catch(c){n={error:c}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var zn=function(t){return function(e){var r,n,i=e;try{for(var o=M(t),s=o.next();!s.done;s=o.next()){var u=s.value;i=i[u]}}catch(d){r={error:d}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function Yn(t,e){return function(r){var n,i,o=r;try{for(var s=M(t),u=s.next();!u.done;u=s.next()){var d=u.value;o=o[e][d]}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}}function rt(t){if(!t)return[[]];if(L(t))return[[t]];var e=V(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:rt(t[r]).map(function(i){return[r].concat(i)})}));return e}function V(t){var e;return(e=[]).concat.apply(e,F([],D(t),!1))}function pr(t){return Te(t)?t:[t]}function te(t){return t===void 0?[]:pr(t)}function nt(t,e,r){var n,i;if(B(t))return t(e,r.data);var o={};try{for(var s=M(Object.keys(t)),u=s.next();!u.done;u=s.next()){var d=u.value,f=t[d];B(f)?o[d]=f(e,r.data):o[d]=f}}catch(c){n={error:c}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function Wn(t){return/^(done|error)\./.test(t)}function vr(t){return!!(t instanceof Promise||t!==null&&(B(t)||typeof t=="object")&&B(t.then))}function Jn(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function Qn(t,e){var r,n,i=D([[],[]],2),o=i[0],s=i[1];try{for(var u=M(t),d=u.next();!d.done;d=u.next()){var f=d.value;e(f)?o.push(f):s.push(f)}}catch(c){r={error:c}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[o,s]}function yr(t,e){return Ne(t.states,function(r,n){if(r){var i=(L(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:yr(r,i)}}})}function Xn(t,e){return{current:e,states:yr(t,e)}}function mr(t,e,r,n){G||z(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(o,s){var u,d,f=s.assignment,c={state:n,action:s,_event:e},l={};if(B(f))l=f(o,e.data,c);else try{for(var h=M(Object.keys(f)),y=h.next();!y.done;y=h.next()){var v=y.value,w=f[v];l[v]=B(w)?w(o,e.data,c):w}}catch(T){u={error:T}}finally{try{y&&!y.done&&(d=h.return)&&d.call(h)}finally{if(u)throw u.error}}return Object.assign({},o,l)},t);return i}var z=function(){};G||(z=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 Te(t){return Array.isArray(t)}function B(t){return typeof t=="function"}function L(t){return typeof t=="string"}function gr(t,e){if(t)return L(t)?{type:Rt,name:t,predicate:e?e[t]:void 0}:B(t)?{type:Rt,name:t.name,predicate:t}:t}function Zn(t){try{return"subscribe"in t&&B(t.subscribe)}catch{return!1}}var fe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();et={},et[fe]=function(){return this},et[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function ei(t){return!!t&&typeof t.send=="function"}var ti=function(){var t=0;return function(){return t++,t.toString(16)}}();function Ut(t,e){return L(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!L(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Ut(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function be(t,e){var r=pr(e).map(function(n){return typeof n>"u"||typeof n=="string"||ae(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function ri(t){if(!(t===void 0||t===Hn))return te(t)}function ni(t,e,r){if(!G){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 wr(t,e,r,n,i){var o=t.options.guards,s={state:i,cond:e,_event:n};if(e.type===Rt)return((o==null?void 0:o[e.name])||e.predicate)(r,n.data,s);var u=o==null?void 0:o[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,s)}function Er(t){return typeof t=="string"?{type:t}:t}function it(t,e,r){var n=function(){},i=typeof t=="object",o=i?t:null;return{next:((i?t.next:t)||n).bind(o),error:((i?t.error:e)||n).bind(o),complete:((i?t.complete:r)||n).bind(o)}}function ot(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=Q({type:ar});function st(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(L(t)||typeof t=="number"){var n=st(t,e);B(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(B(t))r={type:t.name||t.toString(),exec:t};else{var n=st(t.type,e);if(B(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=Te(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function at(t){var e=Ae(t);return m(m({id:L(t)?t:e.id},e),{type:e.type})}function Sr(t){return L(t)?{type:me,event:t}:pe(t,{to:ie.Internal})}function Tr(t){return{type:me,_event:Q(t.event)}}function pe(t,e){return{to:e?e.to:void 0,type:ge,event:B(t)?t:Ut(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:B(t)?t.name:hr(t)}}function br(t,e,r,n){var i={_event:r},o=Q(B(t.event)?t.event(e,r.data,i):t.event),s;if(L(t.delay)){var u=n&&n[t.delay];s=B(u)?u(e,r.data,i):u}else s=B(t.delay)?t.delay(e,r.data,i):t.delay;var d=B(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:d,_event:o,event:o.data,delay:s})}function Dt(t,e){return pe(t,m(m({},e),{to:ie.Parent}))}function ii(t,e,r){return pe(e,m(m({},r),{to:t}))}function oi(){return Dt(Ze)}function si(t,e){return pe(t,m(m({},e),{to:function(r,n,i){var o=i._event;return o.origin}}))}var ai=function(t,e){return{context:t,event:e}};function ci(t,e){return t===void 0&&(t=ai),{type:Qe,label:e,expr:t}}var Ar=function(t,e,r){return m(m({},t),{value:L(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Or=function(t){return{type:kt,sendId:t}};function kr(t){var e=at(t);return{type:$.Start,activity:e,exec:void 0}}function xr(t){var e=B(t)?t:at(t);return{type:$.Stop,activity:e,exec:void 0}}function Ir(t,e,r){var n=B(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,o={type:$.Stop,activity:i};return o}var Rr=function(t){return{type:Je,assignment:t}};function ui(t){return typeof t=="object"&&"type"in t}function Pr(t,e){var r=e?"#".concat(e):"";return"".concat($.After,"(").concat(t,")").concat(r)}function Ce(t,e){var r="".concat($.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Me(t,e){var r="".concat($.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat($.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function li(t){return{type:$.Pure,get:t}}function di(t,e){if(!G&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=typeof r=="function"?r.apply(void 0,F([],D(n),!1)):r;if(!o)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return o}}return pe(function(n,i){return i},m(m({},e),{to:t}))}function hi(t,e){return Dt(function(r,n,i){return{type:It,data:B(t)?t(r,n,i):t}},m(m({},e),{to:ie.Parent}))}function fi(t){return{type:$.Choose,conds:t}}var pi=function(t){var e,r,n=[];try{for(var i=M(t),o=i.next();!o.done;o=i.next())for(var s=o.value,u=0;u<s.length;){if(s[u].type===Je){n.push(s[u]),s.splice(u,1);continue}u++}}catch(d){e={error:d}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function Le(t,e,r,n,i,o,s){s===void 0&&(s=!1);var u=s?[]:pi(i),d=u.length?mr(r,n,u,e):r,f=s?[r]:void 0,c=[];function l(v){var w;switch(v.type){case me:return Tr(v);case ge:var T=br(v,d,n,t.options.delays);return G||z(!L(v.delay)||typeof T.delay=="number","No delay reference for delay expression '".concat(v.delay,"' was found on machine '").concat(t.id,"'")),o&&T.to!==ie.Internal&&c.push(T),T;case Qe:{var O=Ar(v,d,n);return o==null||o(O,d,n),O}case cr:{var S=v,A=(w=S.conds.find(function(K){var a=gr(K.cond,t.options.guards);return!a||wr(t,a,d,n,o?void 0:e)}))===null||w===void 0?void 0:w.actions;if(!A)return[];var N=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),R=N[0],q=N[1];return d=q,f==null||f.push(d),R}case ur:{var A=v.get(d,n.data);if(!A)return[];var P=D(Le(t,e,d,n,[ce(te(A),t.options.actions)],o,s),2),I=P[0],j=P[1];return d=j,f==null||f.push(d),I}case We:{var O=Ir(v,d,n);return o==null||o(O,r,n),O}case Je:{d=mr(d,n,[v],o?void 0:e),f==null||f.push(d);break}default:var k=Ae(v,t.options.actions),x=k.exec;if(o)o(k,d,n);else if(x&&f){var J=f.length-1;k=m(m({},k),{exec:function(K){for(var a=[],p=1;p<arguments.length;p++)a[p-1]=arguments[p];x.apply(void 0,F([f[J]],D(a),!1))}})}return k}}function h(v){var w,T,O=[];try{for(var S=M(v),A=S.next();!A.done;A=S.next()){var N=A.value,R=l(N);R&&(O=O.concat(R))}}catch(q){w={error:q}}finally{try{A&&!A.done&&(T=S.return)&&T.call(S)}finally{if(w)throw w.error}}return c.forEach(function(q){o(q,d,n)}),c.length=0,O}var y=V(i.map(h));return[y,d]}const vi=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:Vn,after:Pr,assign:Rr,cancel:Or,choose:fi,done:Ce,doneInvoke:Me,error:Oe,escalate:hi,forwardTo:di,getActionFunction:st,initEvent:we,isActionObject:ui,log:ci,pure:li,raise:Sr,resolveActions:Le,resolveLog:Ar,resolveRaise:Tr,resolveSend:br,resolveStop:Ir,respond:si,send:pe,sendParent:Dt,sendTo:ii,sendUpdate:oi,start:kr,stop:xr,toActionObject:Ae,toActionObjects:ce,toActivityDefinition:at},Symbol.toStringTag,{value:"Module"}));var ct=[],ke=function(t,e){ct.push(t);var r=e(t);return ct.pop(),r},yi=function(t){return t(ct[ct.length-1])};function _r(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[fe]=function(){return this},e}function mi(t,e,r,n){var i,o=Er(t.src),s=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[o.type],u=t.data?nt(t.data,r,n):void 0,d=s?Nt(s,t.id,u):_r(t.id);return d.meta=t,d}function Nt(t,e,r){var n=_r(e);if(n.deferred=!0,ae(t)){var i=n.state=ke(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function gi(t){try{return typeof t.send=="function"}catch{return!1}}function wi(t){return gi(t)&&"id"in t}function Ei(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[fe]=function(){return this},e),t)}var ut=function(t){return t.type==="atomic"||t.type==="final"};function Ur(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function je(t){return Ur(t).filter(function(e){return e.type!=="history"})}function Dr(t){var e=[t];return ut(t)?e:e.concat(V(je(t).map(Dr)))}function $e(t,e){var r,n,i,o,s,u,d,f,c=new Set(t),l=Ct(c),h=new Set(e);try{for(var y=M(h),v=y.next();!v.done;v=y.next())for(var w=v.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){r={error:j}}finally{try{v&&!v.done&&(n=y.return)&&n.call(y)}finally{if(r)throw r.error}}var O=Ct(h);try{for(var S=M(h),A=S.next();!A.done;A=S.next()){var w=A.value;if(w.type==="compound"&&(!O.get(w)||!O.get(w).length))l.get(w)?l.get(w).forEach(function(k){return h.add(k)}):w.initialStateNodes.forEach(function(k){return h.add(k)});else if(w.type==="parallel")try{for(var N=(s=void 0,M(je(w))),R=N.next();!R.done;R=N.next()){var q=R.value;h.has(q)||(h.add(q),l.get(q)?l.get(q).forEach(function(k){return h.add(k)}):q.initialStateNodes.forEach(function(k){return h.add(k)}))}}catch(k){s={error:k}}finally{try{R&&!R.done&&(u=N.return)&&u.call(N)}finally{if(s)throw s.error}}}}catch(j){i={error:j}}finally{try{A&&!A.done&&(o=S.return)&&o.call(S)}finally{if(i)throw i.error}}try{for(var P=M(h),I=P.next();!I.done;I=P.next())for(var w=I.value,T=w.parent;T&&!h.has(T);)h.add(T),T=T.parent}catch(j){d={error:j}}finally{try{I&&!I.done&&(f=P.return)&&f.call(P)}finally{if(d)throw d.error}}return h}function Nr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(ut(n))return n.key}else return{}}var i={};return r.forEach(function(o){i[o.key]=Nr(o,e)}),i}function Ct(t){var e,r,n=new Map;try{for(var i=M(t),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Si(t,e){var r=$e([t],e);return Nr(t,Ct(r))}function Be(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ti(t){return F([],D(new Set(V(F([],D(t.map(function(e){return e.ownEvents})),!1)))),!1)}function lt(t,e){return e.type==="compound"?je(e).some(function(r){return r.type==="final"&&Be(t,r)}):e.type==="parallel"?je(e).every(function(r){return lt(t,r)}):!1}function bi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Cr(t){return new Set(V(t.map(function(e){return e.tags})))}function Mr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(L(t)||L(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Mr(t[i],e[i])})}function Ai(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Oi(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=dr,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||dr,this.meta=bi(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 Ti(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=we;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=we;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="."),L(e))return[e];var i=Object.keys(e);return i.concat.apply(i,F([],D(i.map(function(o){return n.toStrings(e[o],r).map(function(s){return o+r+s})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=Ot(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Pt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;G&&z(!!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},Lr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},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}(),Mt=new Map,xi=0,dt={bookId:function(){return"x:".concat(xi++)},register:function(t,e){return Mt.set(t,e),t},get:function(t){return Mt.get(t)},free:function(t){Mt.delete(t)}};function Lt(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;G||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=Lt();if(t&&"__xstate__"in t)return t.__xstate__}function Ri(t){if(Lt()){var e=Ii();e&&e.register(t)}}function Pi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],o=!1,s=function(){if(!o){for(o=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,d),n.forEach(function(c){return c.next(r)})}o=!1}},u=Ei({id:e.id,send:function(f){i.push(f),s()},getSnapshot:function(){return r},subscribe:function(f,c,l){var h=it(f,c,l);return n.add(h),h.next(r),{unsubscribe:function(){n.delete(h)}}}}),d={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(d):r,u}var jt={sync:!1,autoForward:!1},Y;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Y||(Y={}));var _i=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=Y.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(c,l){if(Te(c))return n.batch(c),n.state;var h=Q(Ut(c,l));if(n.status===Y.Stopped)return G||z(!1,'Event "'.concat(h.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(h.data))),n.state;if(n.status!==Y.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(h.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(h.data)));return n.scheduler.schedule(function(){n.forward(h);var y=n._nextState(h);n.update(y,h)}),n._state},this.sendTo=function(c,l,h){var y=n.parent&&(l===ie.Parent||n.parent.id===l),v=y?n.parent:L(l)?n.children.get(l)||dt.get(l):ei(l)?l:void 0;if(!v){if(!y)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));G||z(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(c.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var w=m(m({},c),{name:c.name===It?"".concat(Oe(n.id)):c.name,origin:n.sessionId});!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,w]):v.send(w)}}else!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,c.data]):v.send(c.data)},this._exec=function(c,l,h,y){y===void 0&&(y=n.machine.options.actions);var v=c.exec||st(c.type,y),w=B(v)?v:v?v.exec:c.exec;if(w)try{return w(l,h.data,n.machine.config.predictableActionArguments?{action:c,_event:h}:{action:c,state:n.state,_event:h})}catch(J){throw n.parent&&n.parent.send({type:"xstate.error",data:J}),J}switch(c.type){case ge:var T=c;if(typeof T.delay=="number"){n.defer(T);return}else T.to?n.sendTo(T._event,T.to,h===we):n.send(T._event);break;case kt:n.cancel(c.sendId);break;case Ye:{if(n.status!==Y.Running)return;var O=c.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[O.id||O.type])break;if(O.type===$.Invoke){var S=Er(O.src),A=n.machine.options.services?n.machine.options.services[S.type]:void 0,N=O.id,R=O.data;G||z(!("forward"in O),"`forward` property is deprecated (found in invocation of '".concat(O.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var q="autoForward"in O?O.autoForward:!!O.forward;if(!A){G||z(!1,"No service found for invocation '".concat(O.src,"' in machine '").concat(n.machine.id,"'."));return}var P=R?nt(R,l,h):void 0;if(typeof A=="string")return;var I=B(A)?A(l,h.data,{data:P,src:S,meta:O.meta}):A;if(!I)return;var j=void 0;ae(I)&&(I=P?I.withContext(P):I,j={autoForward:q}),n.spawn(I,N,j)}else n.spawnActivity(O);break}case We:{n.stopChild(c.activity.id);break}case Qe:var k=c.label,x=c.value;k?n.logger(k,x):n.logger(x);break;default:G||z(!1,"No implementation found for action type '".concat(c.type,"'"));break}};var i=m(m({},t.defaultOptions),r),o=i.clock,s=i.logger,u=i.parent,d=i.id,f=d!==void 0?d:e.id;this.id=f,this.logger=s,this.clock=o,this.parent=u,this.options=i,this.scheduler=new Lr({deferEvents:this.options.deferEvents}),this.sessionId=dt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:ke(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return G||z(this.status!==Y.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 o=M(e.actions),s=o.next();!s.done;s=o.next()){var u=s.value;this.exec(u,e,r)}}catch(d){n={error:d}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,o,s,u,d,f,c,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===we)&&this.options.execute)this.execute(this.state);else for(var h=void 0;h=this._outgoingQueue.shift();)h[0].send(h[1]);if(this.children.forEach(function(j){l.state.children[j.id]=j}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var y=M(this.eventListeners),v=y.next();!v.done;v=y.next()){var w=v.value;w(e.event)}}catch(j){n={error:j}}finally{try{v&&!v.done&&(i=y.return)&&i.call(y)}finally{if(n)throw n.error}}try{for(var T=M(this.listeners),O=T.next();!O.done;O=T.next()){var w=O.value;w(e,e.event)}}catch(j){o={error:j}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.contextListeners),A=S.next();!A.done;A=S.next()){var N=A.value;N(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(j){u={error:j}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(this.state.done){var R=e.configuration.find(function(j){return j.type==="final"&&j.parent===l.machine}),q=R&&R.doneData?nt(R.doneData,e.context,r):void 0;try{for(var P=M(this.doneListeners),I=P.next();!I.done;I=P.next()){var w=I.value;w(Me(this.id,q))}}catch(j){f={error:j}}finally{try{I&&!I.done&&(c=P.return)&&c.call(P)}finally{if(f)throw f.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Y.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,o=it(e,r,n);this.listeners.add(o.next),this.status!==Y.NotStarted&&o.next(this.state);var s=function(){i.doneListeners.delete(s),i.stopListeners.delete(s),o.complete()};return this.status===Y.Stopped?o.complete():(this.onDone(s),this.onStop(s)),{unsubscribe:function(){i.listeners.delete(o.next),i.doneListeners.delete(s),i.stopListeners.delete(s)}}},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===Y.Running)return this;this.machine._init(),dt.register(this.sessionId,this),this.initialized=!0,this.status=Y.Running;var n=e===void 0?this.initialState:ke(this,function(){return Ai(e)?r.machine.resolveState(e):r.machine.resolveState(oe.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,we)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){B(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,o,s,u,d,f,c;try{for(var l=M(this.listeners),h=l.next();!h.done;h=l.next()){var y=h.value;this.listeners.delete(y)}}catch(P){e={error:P}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=M(this.stopListeners),w=v.next();!w.done;w=v.next()){var y=w.value;y(),this.stopListeners.delete(y)}}catch(P){n={error:P}}finally{try{w&&!w.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var T=M(this.contextListeners),O=T.next();!O.done;O=T.next()){var y=O.value;this.contextListeners.delete(y)}}catch(P){o={error:P}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.doneListeners),A=S.next();!A.done;A=S.next()){var y=A.value;this.doneListeners.delete(y)}}catch(P){u={error:P}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Y.Stopped,this._initialState=void 0;try{for(var N=M(Object.keys(this.delayedEventsMap)),R=N.next();!R.done;R=N.next()){var q=R.value;this.clock.clearTimeout(this.delayedEventsMap[q])}}catch(P){f={error:P}}finally{try{R&&!R.done&&(c=N.return)&&c.call(N)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Lr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=Q({type:"xstate.stop"}),i=ke(e,function(){var o=V(F([],D(e.state.configuration),!1).sort(function(c,l){return l.order-c.order}).map(function(c){return ce(c.onExit,e.machine.options.actions)})),s=D(Le(e.machine,e.state,e.state.context,n,[o],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),u=s[0],d=s[1],f=new oe({value:e.state.value,context:d,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:u.filter(function(c){return c.type!==me&&(c.type!==ge||!!c.to&&c.to!==ie.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return f.changed=!0,f});e.update(i,n),e._stopChildren(),dt.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===Y.NotStarted&&this.options.deferEvents)G||z(!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!==Y.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,o,s=r.state,u=!1,d=[],f=function(y){var v=Q(y);r.forward(v),s=ke(r,function(){return r.machine.transition(s,v,void 0,n||void 0)}),d.push.apply(d,F([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(w){return Oi(w,s)})),!1)),u=u||!!s.changed};try{for(var c=M(e),l=c.next();!l.done;l=c.next()){var h=l.value;f(h)}}catch(y){i={error:y}}finally{try{l&&!l.done&&(o=c.return)&&o.call(c)}finally{if(i)throw i.error}}s.changed=u,s.actions=d,r.update(s,Q(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=Q(e);if(i.name.indexOf(xt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(xt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=M(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,u=this.children.get(s);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));u.send(e)}}catch(d){r={error:d}}finally{try{o&&!o.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),B(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return Nt(e,r);if(vr(e))return this.spawnPromise(Promise.resolve(e),r);if(B(e))return this.spawnCallback(e,r);if(wi(e))return this.spawnActor(e,r);if(Zn(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,m(m({},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,m(m({},this.options),{parent:this,id:r.id||e.id})),o=m(m({},jt),r);o.sync&&i.onTransition(function(u){n.send(Ze,{state:u,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Pi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(d){o||(s=d,i.removeChild(r),i.send(Q(Me(r,d),{origin:r})))},function(d){if(!o){i.removeChild(r);var f=Oe(r,d);try{i.send(Q(f,{origin:r}))}catch(c){ni(d,c,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(d,f,c){var l=it(d,f,c),h=!1;return e.then(function(y){h||(l.next(y),!h&&l.complete())},function(y){h||l.error(y)}),{unsubscribe:function(){return h=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[fe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,u=new Set,d,f=function(h){d=h,u.forEach(function(y){return y(h)}),!o&&i.send(Q(h,{origin:r}))},c;try{c=e(f,function(h){s.add(h)})}catch(h){this.send(Oe(r,h))}if(vr(c))return this.spawnPromise(c,r);var l=(n={id:r,send:function(h){return s.forEach(function(y){return y(h)})},subscribe:function(h){var y=it(h);return u.add(y.next),{unsubscribe:function(){u.delete(y.next)}}},stop:function(){o=!0,B(c)&&c()},toJSON:function(){return{id:r}},getSnapshot:function(){return d}},n[fe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(d){o=d,i.send(Q(d,{origin:r}))},function(d){i.removeChild(r),i.send(Q(Oe(r,d),{origin:r}))},function(){i.removeChild(r),i.send(Q(Me(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(d,f,c){return e.subscribe(d,f,c)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[fe]=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){G||z(!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[fe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Lt();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(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Ri(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[fe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===Y.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=xe,t}(),Ui=function(t){return L(t)?m(m({},jt),{name:t}):m(m(m({},jt),{name:ti()}),t)};function Di(t,e){var r=Ui(e);return yi(function(n){if(!G){var i=ae(t)||B(t);z(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(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 xe(t,e){var r=new _i(t,e);return r}function Ni(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return m(m({type:Xe},t),{toJSON:function(){t.onDone,t.onError;var e=Ot(t,["onDone","onError"]);return m(m({},e),{type:Xe,src:Ni(t.src)})}})}var Ie="",$t="#",Fe="*",Re={},Pe=function(t){return t[0]===$t},Ci=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Mi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");z(!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.")},Li=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;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:lr),this.id=this.config.id||F([this.machine.key],D(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:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,G||z(!("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?Ne(this.config.states,function(f,c){var l,h=new t(f,{},void 0,{parent:o,key:c});return Object.assign(o.idMap,m((l={},l[h.id]=h,l),h.idMap)),h}):Re;var u=0;function d(f){var c,l;f.order=u++;try{for(var h=M(Ur(f)),y=h.next();!y.done;y=h.next()){var v=y.value;d(v)}}catch(w){c={error:w}}finally{try{y&&!y.done&&(l=h.return)&&l.call(h)}finally{if(c)throw c.error}}}d(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(f){var c=f.event;return c===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(f){return Ae(f)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(f){return Ae(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(f,c){var l,h;if(ae(f)){var y=ot(o.id,c);return o.machine.options.services=m((l={},l[y]=f,l),o.machine.options.services),ht({src:y,id:y})}else if(L(f.src)){var y=f.id||ot(o.id,c);return ht(m(m({},f),{id:y,src:f.src}))}else if(ae(f.src)||B(f.src)){var y=f.id||ot(o.id,c);return o.machine.options.services=m((h={},h[y]=f.src,h),o.machine.options.services),ht(m(m({id:y},f),{src:y}))}else{var v=f.src;return ht(m(m({id:ot(o.id,c)},f),{src:v}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(f){return at(f)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Dr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,u=n.services,d=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},o),e.activities),guards:m(m({},s),e.guards),services:m(m({},u),e.services),delays:m(m({},d),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return B(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:Ne(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===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Fe});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var u=B(o)?"".concat(e.id,":delay[").concat(s,"]"):o,d=Pr(u,e.id);return e.onEntry.push(pe(d,{delay:o})),e.onExit.push(Or(d)),d},i=Te(r)?r.map(function(o,s){var u=n(o.delay,s);return m(m({},o),{event:u})}):V(Object.keys(r).map(function(o,s){var u=r[o],d=L(u)?{target:u}:u,f=isNaN(+o)?o:+o,c=n(f,s);return te(d).map(function(l){return m(m({},l),{event:c,delay:f})})}));return i.map(function(o){var s=o.delay;return m(m({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:De(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),u=[this];return u.push.apply(u,F([],D(V(s.map(function(d){return n.getStateNode(d).getStateNodes(i[d])}))),!1)),u},t.prototype.handles=function(e){var r=hr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(m(m({},r),{value:this.resolve(r.value),configuration:n,done:lt(n,this),tags:Cr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var u=M(Object.keys(e)),d=u.next();!d.done;d=u.next()){var f=d.value,c=e[f];if(c){var l=this.getStateNode(f),h=l._transition(c,r,n);h&&(s[f]=h)}}}catch(S){i={error:S}}finally{try{d&&!d.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}var y=Object.keys(s).map(function(S){return s[S]}),v=V(y.map(function(S){return S.transitions})),w=y.some(function(S){return S.transitions.length>0});if(!w)return this.next(r,n);var T=V(y.map(function(S){return S.entrySet})),O=V(Object.keys(s).map(function(S){return s[S].configuration}));return{transitions:v,entrySet:T,exitSet:V(y.map(function(S){return S.exitSet})),configuration:O,source:r,actions:V(Object.keys(s).map(function(S){return s[S].actions}))}},t.prototype._transition=function(e,r,n){return L(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,Q(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,u=[],d=[],f;try{for(var c=M(this.getCandidates(s)),l=c.next();!l.done;l=c.next()){var h=l.value,y=h.cond,v=h.in,w=e.context,T=v?L(v)&&Pe(v)?e.matches(De(this.getStateNodeById(v).path,this.delimiter)):Pt(De(v,this.delimiter),zn(this.path.slice(0,-2))(e.value)):!0,O=!1;try{O=!y||wr(this.machine,y,w,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(y.name||y.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
|
|
18
|
+
`).concat(R.message))}if(O&&T){h.target!==void 0&&(d=h.target),u.push.apply(u,F([],D(h.actions),!1)),f=h;break}}}catch(R){n={error:R}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}if(f){if(!d.length)return{transitions:[f],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var S=V(d.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!f.internal,N=[];return A||d.forEach(function(R){N.push.apply(N,F([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[f],entrySet:N,exitSet:A?[]:[this],configuration:S,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,u){var d,f,c,l,h=this,y=$e([],s?this.getStateNodes(s.value):[this]);try{for(var v=M(e),w=v.next();!w.done;w=v.next()){var T=w.value;(!Be(y,T)||Be(n.entrySet,T.parent))&&n.entrySet.push(T)}}catch(k){d={error:k}}finally{try{w&&!w.done&&(f=v.return)&&f.call(v)}finally{if(d)throw d.error}}try{for(var O=M(y),S=O.next();!S.done;S=O.next()){var T=S.value;(!Be(e,T)||Be(n.exitSet,T.parent))&&n.exitSet.push(T)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(l=O.return)&&l.call(O)}finally{if(c)throw c.error}}var A=V(n.entrySet.map(function(k){var x=[];if(k.type!=="final")return x;var J=k.parent;if(!J.parent)return x;x.push(Ce(k.id,k.doneData),Ce(J.id,k.doneData?nt(k.doneData,i,o):void 0));var K=J.parent;return K.type==="parallel"&&je(K).every(function(a){return lt(n.configuration,a)})&&x.push(Ce(K.id)),x}));n.exitSet.sort(function(k,x){return x.order-k.order}),n.entrySet.sort(function(k,x){return k.order-x.order});var N=new Set(n.entrySet),R=new Set(n.exitSet),q=Array.from(N).map(function(k){var x=k.onEntry,J=k.activities.map(function(K){return kr(K)});return ce(u?F(F([],D(x),!1),D(J),!1):F(F([],D(J),!1),D(x),!1),h.machine.options.actions)}).concat([A.map(Sr)]),P=Array.from(R).map(function(k){return ce(F(F([],D(k.onExit),!1),D(k.activities.map(function(x){return xr(x)})),!1),h.machine.options.actions)}),I=P.concat([ce(n.actions,this.machine.options.actions)]).concat(q);if(r){var j=ce(V(F([],D(e),!1).sort(function(k,x){return x.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return I.concat([j])}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=Q(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=L(e)?this.resolve(tt(this.getResolvedPath(e))):this.resolve(e),d=n??this.machine.context;s=this.resolveState(oe.from(u,d))}if(!G&&o.name===Fe)throw new Error("An event cannot have the wildcard type ('".concat(Fe,"')"));if(this.strict&&!this.events.includes(o.name)&&!Wn(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var f=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},c=$e([],this.getStateNodes(s.value)),l=f.configuration.length?$e(c,f.configuration):c;return f.configuration=F([],D(l),!1),this.resolveTransition(f,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,F([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,u,d,f,c=this;o===void 0&&(o=we);var l=e.configuration,h=!r||e.transitions.length>0,y=h?e.configuration:r?r.configuration:[],v=lt(y,this),w=h?Si(this.machine,l):void 0,T=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,O=this.getActions(new Set(y),v,e,n,o,r,i),S=r?m({},r.activities):{};try{for(var A=M(O),N=A.next();!N.done;N=A.next()){var R=N.value;try{for(var q=(d=void 0,M(R)),P=q.next();!P.done;P=q.next()){var I=P.value;I.type===Ye?S[I.activity.id||I.activity.type]=I:I.type===We&&(S[I.activity.id||I.activity.type]=!1)}}catch(Z){d={error:Z}}finally{try{P&&!P.done&&(f=q.return)&&f.call(q)}finally{if(d)throw d.error}}}}catch(Z){s={error:Z}}finally{try{N&&!N.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}var j=D(Le(this,r,n,o,O,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=j[0],x=j[1],J=D(Qn(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),K=J[0],a=J[1],p=k.filter(function(Z){var Ue;return Z.type===Ye&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Xe}),E=p.reduce(function(Z,Ue){return Z[Ue.activity.id]=mi(Ue.activity,c.machine,x,o),Z},r?m({},r.children):{}),C=new oe({value:w||r.value,context:x,_event:o,_sessionid:r?r._sessionid:null,historyValue:w?T?Xn(T,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?a:[],activities:w?S:r?r.activities:{},events:[],configuration:y,transitions:e.transitions,children:E,done:v,tags:Cr(y),machine:this}),_=n!==x;C.changed=o.name===Ze||_;var b=C.history;b&&delete b.history;var ee=!v&&(this._transient||l.some(function(Z){return Z._transient}));if(!h&&(!ee||o.name===Ie))return C;var H=C;if(!v)for(ee&&(H=this.resolveRaisedTransition(H,{type:sr},o,i));K.length;){var he=K.shift();H=this.resolveRaisedTransition(H,he._event,o,i)}var yo=H.changed||(b?!!H.actions.length||_||typeof b.value!=typeof H.value||!Mr(H.value,b.value):void 0);return H.changed=yo,H.history=b,H},t.prototype.getStateNode=function(e){if(Pe(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=Pe(e)?e.slice($t.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"&&Pe(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=_t(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||Re;switch(this.type){case"parallel":return Ne(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):Re});case"compound":if(L(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?Ne(e,function(o,s){return o?n.getStateNode(s).resolve(o):Re}):this.initialStateValue||{};default:return e||Re}},t.prototype.getResolvedPath=function(e){if(Pe(e)){var r=this.machine.idMap[e.slice($t.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return _t(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=fr(this.states,function(n){return n.initialStateValue||Re},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=ut(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:F([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,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;L(r.target)?e=Pe(r.target)?tt(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(ut(this))return[this];if(this.type==="compound"&&!this.initial)return G||z(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=rt(this.initialStateValue);return V(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(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 o=this.getStateNode(n);if(o.type==="history")return o.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:fr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(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?V(rt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=Yn(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:V(rt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=V(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 o=this.states,s=new Set(this.ownEvents);if(o)try{for(var u=M(Object.keys(o)),d=u.next();!d.done;d=u.next()){var f=d.value,c=o[f];if(c.states)try{for(var l=(n=void 0,M(c.events)),h=l.next();!h.done;h=l.next()){var y=h.value;s.add("".concat(y))}}catch(v){n={error:v}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},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(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
+
`).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=ri(e.target),i="internal"in e?e.internal:n?n.some(function(d){return L(d)&&d[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=m(m({},e),{actions:ce(te(e.actions)),cond:gr(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(d){return"#".concat(d.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 o=this.config.on,s=Fe,u=o[s],d=u===void 0?[]:u,f=Ot(o,[typeof s=="symbol"?s:s+""]);i=V(Object.keys(f).map(function(S){!G&&S===Ie&&z(!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 A=be(S,f[S]);return G||Mi(n,S,A),A}).concat(be(Fe,d)))}var c=this.config.always?be("",this.config.always):[],l=this.config.onDone?be(String(Ce(this.id)),this.config.onDone):[];G||z(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=V(this.invoke.map(function(S){var A=[];return S.onDone&&A.push.apply(A,F([],D(be(String(Me(S.id)),S.onDone)),!1)),S.onError&&A.push.apply(A,F([],D(be(String(Oe(S.id)),S.onError)),!1)),A})),y=this.after,v=V(F(F(F(F([],D(l),!1),D(h),!1),D(i),!1),D(c),!1).map(function(S){return te(S).map(function(A){return n.formatTransition(A)})}));try{for(var w=M(y),T=w.next();!T.done;T=w.next()){var O=T.value;v.push(O)}}catch(S){e={error:S}}finally{try{T&&!T.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),jr=!1;function ve(t,e){return!G&&!t.predictableActionArguments&&!jr&&(jr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Li(t,e)}var U=Rr,W=pe;/*! js-cookie v3.0.1 | MIT */function ft(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 ji={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 Bt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=ft({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var d in s)s[d]&&(u+="; "+d,s[d]!==!0&&(u+="="+s[d].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var d=o[u].split("="),f=d.slice(1).join("=");try{var c=decodeURIComponent(d[0]);if(s[c]=t.read(f,c),i===c)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",ft({},o,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,ft({},this.attributes,i))},withConverter:function(i){return Bt(ft({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Ft=Bt(ji,{path:"/"}),$i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt={exports:{}};(function(t,e){var r=typeof self<"u"?self:$i,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(p,E){this.message=p,this.name=E;var C=Error(p);this.stack=C.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(qt,qt.exports);const Gt=Bi(qt.exports),qe="nhostRefreshToken",Ge="nhostRefreshTokenExpiresAt",$r=3,Br=300,Vt=5,Ht=0,Kt=1,re=10,_e=20;class Ve 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:Kt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},Fr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},qr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},pt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},zt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Gr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Vr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Hr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Kr={status:_e,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:_e,error:"already-signed-in",message:"User is already signed in"},zr={status:_e,error:"unauthenticated-user",message:"User is not authenticated"},Fi={status:_e,error:"user-not-anonymous",message:"User is not anonymous"},Yr={status:_e,error:"unverified-user",message:"Email needs verification"},Wr={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Jr={status:Kt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},vt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qi(t){return new TextEncoder().encode(t)}function Ee(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 Yt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function Qr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Xr(t){const{id:e}=t;return{...t,id:Yt(e),transports:t.transports}}function Zr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class X extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Gi({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 X("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 X("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 X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(Zr(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${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 X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Vi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Vi;async function en(t){if(!Qr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Yt(t.challenge),user:{...t.user,id:qi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Xr)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(d){throw Gi({error:d,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function Hi(t){return new TextDecoder("utf-8").decode(t)}async function Ki(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function zi({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 X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Zr(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Yi(t,e=!1){var r,n;if(!Qr())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(Xr));const o={...t,challenge:Yt(t.challenge),allowCredentials:i},s={};if(e){if(!await Ki())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');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=yt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(y){throw zi({error:y,options:s})}finally{yt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:d,rawId:f,response:c,type:l}=u;let h;return c.userHandle&&(h=Hi(c.userHandle)),{id:d,rawId:Ee(f),response:{authenticatorData:Ee(c.authenticatorData),clientDataJSON:Ee(c.clientDataJSON),signature:Ee(c.signature),userHandle:h},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const mt=typeof window<"u",gt=new Map,Wi=t=>mt&&typeof localStorage<"u"?localStorage.getItem(t):gt.get(t)??null,Ji=(t,e)=>{mt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?gt.set(t,e):gt.has(t)&>.delete(t)},tn=(t,e)=>{if(t==="localStorage"||t==="web")return Wi;if(t==="cookie")return r=>mt?Ft.get(r)??null: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}`)},rn=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return(r,n)=>{mt&&(n?Ft.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Ft.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,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.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,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=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},ye=({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},wt=()=>typeof window<"u",nn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Gt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.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 s={message:"Network Error",status:Ht,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>nn(t,"POST",{token:r,body:e}),on=(t,e)=>nn(t,"GET",{token:e}),Wt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(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),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let d=Object.fromEntries(u);r.startsWith("/")&&(d={...o,...d});let f=i.pathname;return s.pathname.length>1&&(f+=s.pathname.slice(1)),{...n,redirectTo:Wt(s.origin+f,d)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")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 Jt(t){var e;if(typeof window>"u")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 o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=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,}))$/),Et=t=>!!t&&typeof t=="string"&&t.length>=$r,Qt=t=>!!t&&typeof t=="string",sn=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),an=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=tn(r,n),d=rn(r,n),f=async(c,l,h)=>(await le(`${t}${c}`,l,h)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:vt,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:W("SIGNED_IN"),reportSignedOut:W("SIGNED_OUT"),reportTokenChanged:W("TOKEN_CHANGED"),incrementTokenImportAttempts:U({importTokenAttempts:({importTokenAttempts:c})=>c+1}),clearContext:U(()=>(d(Ge,null),d(qe,null),{...vt})),clearContextExceptRefreshToken:U(({refreshToken:{value:c}})=>(d(Ge,null),{...vt,refreshToken:{value:c}})),saveSession:U({user:(c,{data:l})=>{var h;return((h=l==null?void 0:l.session)==null?void 0:h.user)||null},accessToken:(c,{data:l})=>{if(l.session){const{accessTokenExpiresIn:h,accessToken:y}=l.session,v=new Date(Date.now()+h*1e3);return d(Ge,v.toISOString()),{value:y,expiresAt:v}}return d(Ge,null),{value:null,expiresAt:null}},refreshToken:(c,{data:l})=>{var h;const y=((h=l.session)==null?void 0:h.refreshToken)||null;return y&&d(qe,y),{value:y}}}),saveMfaTicket:U({mfa:(c,l)=>{var h;return(h=l.data)==null?void 0:h.mfa}}),resetTimer:U({refreshTimer:c=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:U({refreshTimer:(c,l)=>({startedAt:c.refreshTimer.startedAt,attempts:c.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:U({errors:({errors:c},{data:{error:l}})=>({...c,authentication:l})}),resetErrors:U({errors:c=>({}),importTokenAttempts:c=>0}),saveRegistrationError:U({errors:({errors:c},{data:{error:l}})=>({...c,registration:l})}),destroyRefreshToken:U({refreshToken:c=>(d(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Jt("refreshToken"),Jt("type"))},broadcastToken:c=>{if(s)try{new BroadcastChannel("nhost").postMessage(c.refreshToken.value)}catch{}}},guards:{isAnonymous:(c,l)=>{var h;return!!((h=c.user)!=null&&h.isAnonymous)},isSignedIn:c=>!!c.user&&!!c.refreshToken.value&&!!c.accessToken.value,noToken:c=>!c.refreshToken.value,hasRefreshToken:c=>!!c.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:c=>{const{expiresAt:l}=c.accessToken;return l?c.refreshTimer.lastAttempt?c.refreshTimer.attempts>Vt?!1:Date.now()-c.refreshTimer.lastAttempt.getTime()>Math.pow(2,c.refreshTimer.attempts-1)*5e3:i&&Date.now()-c.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Br<=0:!1},shouldRetryImportToken:(c,l)=>c.importTokenAttempts<Vt&&(l.data.error.status===Ht||l.data.error.status>=500),unverified:(c,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(c,l)=>{var h;return!!((h=l.data)!=null&&h.session)},hasMfaTicket:(c,l)=>{var h;return!!((h=l.data)!=null&&h.mfa)}},services:{signInPassword:(c,{email:l,password:h})=>de(l)?Et(h)?f("/signin/email-password",{email:l,password:h}):Promise.reject({error:pt}):Promise.reject({error:ue}),passwordlessSms:(c,{phoneNumber:l,options:h})=>{var y;return Qt(l)?(y=c.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:ne(e,h)},c.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:ne(e,h)}):Promise.reject({error:zt})},passwordlessSmsOtp:(c,{phoneNumber:l,otp:h})=>Qt(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:h}):Promise.reject({error:zt}),passwordlessEmail:(c,{email:l,options:h})=>{var y;return de(l)?(y=c.user)!=null&&y.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:ne(e,h)},c.accessToken.value):f("/signin/passwordless/email",{email:l,options:ne(e,h)}):Promise.reject({error:ue})},signInAnonymous:c=>f("/signin/anonymous"),signInMfaTotp:(c,l)=>{var h;const y=l.ticket||((h=c.mfa)==null?void 0:h.ticket);return y?sn(y)?f("/signin/mfa/totp",{ticket:y,otp:l.otp}):Promise.reject({error:Gr}):Promise.reject({error:Vr})},signInSecurityKeyEmail:async(c,{email:l})=>{if(!de(l))throw new Ve(ue);const h=await f("/signin/webauthn",{email:l});let y;try{y=await Yi(h)}catch(v){throw new Ve(v)}return f("/signin/webauthn/verify",{email:l,credential:y})},refreshToken:async(c,l)=>{const h=l.type==="TRY_TOKEN"?l.token:c.refreshToken.value;return{session:await f("/token",{refreshToken:h}),error:null}},signout:(c,l)=>f("/signout",{refreshToken:c.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(c,{email:l,password:h,options:y})=>{var v;return de(l)?Et(h)?(v=c.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:h,options:ne(e,y)},c.accessToken.value):f("/signup/email-password",{email:l,password:h,options:ne(e,y)}):Promise.reject({error:pt}):Promise.reject({error:ue})},signUpSecurityKey:async(c,{email:l,options:h})=>{if(!de(l))return Promise.reject({error:ue});const y=h==null?void 0:h.nickname;y&&delete h.nickname;const v=await f("/signup/webauthn",{email:l,options:h});let w;try{w=await en(v)}catch(T){throw new Ve(T)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:h==null?void 0:h.redirectTo,nickname:y}})},importRefreshToken:async c=>{if(c.user&&c.refreshToken.value&&c.accessToken.value&&c.accessToken.expiresAt)return{session:{accessToken:c.accessToken.value,accessTokenExpiresIn:c.accessToken.expiresAt.getTime()-Date.now(),refreshToken:c.refreshToken.value,user:c.user},error:null};let l=null;if(s){const y=Ke("refreshToken")||null;if(y)try{return{session:await f("/token",{refreshToken:y}),error:null}}catch(v){l=v.error}else{const v=Ke("error");if(v)return Promise.reject({session:null,error:{status:re,error:v,message:Ke("errorDescription")||v}})}}const h=await u(qe);if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(y){l=y.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:c})=>Math.pow(2,c-1)*5e3}})},cn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({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:U({error:n=>ue}),saveRequestError:U({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),un=({backendUrl:t,interpreter:e})=>ve({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:U({error:r=>pt}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!Et(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ve({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:U({error:r=>Fr}),saveInvalidMfaCodeError:U({error:r=>qr}),saveError:U({error:(r,{data:{error:n}})=>n}),saveGeneration:U({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:W((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS"),reportGeneratedSuccess:W("GENERATED"),reportGeneratedError:W(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 on(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ln=({backendUrl:t,clientUrl:e})=>ve({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:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),dn=({backendUrl:t,clientUrl:e})=>ve({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:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let Xt=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...d}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=an({...d,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var c;const l=(c=this.interpreter)==null?void 0:c.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||xe(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(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 hn extends Xt{constructor({...e}){super({...e,autoSignIn:wt()&&e.autoSignIn,autoRefreshToken:wt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=hn,fn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await en(n)}catch(s){throw new Ve(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},pn=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})})}),vn=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:""})})}),eo=(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})})}),yn=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})})}),mn=(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})})}),gn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,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})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),Zt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),En=(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:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),er=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),bn=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:zr});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})})}),tr=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.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})})}),An=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class On{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var d;this.url=e,this._client=new Xt({backendUrl:e,clientUrl:typeof window<"u"&&((d=window.location)==null?void 0:d.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await An(r,n,i)):ye(await tr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await gn(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Wt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return wt()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await wn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Yr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await En(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await Zt(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await Tn(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Sn(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:Jr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await bn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(ln(this._client)).start(),{error:i}=await yn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(un(this._client)).start(),{error:i}=await vn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(dn(this._client)).start(),{error:i}=await mn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(cn(this._client)).start(),{error:i}=await pn(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 Zt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await tr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await fn(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:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});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:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});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;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Bn(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:Hr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Kr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:Wr}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((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(o=>{if(!o.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 kn=typeof self=="object"?self.FormData:window.FormData,to=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rr={exports:{}};(function(t,e){var r=typeof self<"u"?self:to,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,p){this.message=a,this.name=p;var E=Error(a);this.stack=E.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(rr,rr.exports);const nr=ro(rr.exports),no=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},xn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const d={};i&&(d["x-nhost-file-id"]=i),o&&(d["x-nhost-bucket-id"]=o),n&&(d["x-nhost-file-name"]=no(n)),s&&(d["x-hasura-admin-secret"]=s),r&&(d.Authorization=`Bearer ${r}`);const f=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const c=await nr(f,{method:"POST",headers:d,body:e});return c.ok?{fileMetadata:await c.json(),error:null}:{error:{status:c.status,message:await c.text(),error:c.statusText},fileMetadata:null}}catch(c){return{error:{status:0,message:c.message,error:c.message},fileMetadata:null}}return new Promise(c=>{console.log("NOOOOOOO");let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):c({fileMetadata:l.response,error:null}),l.onerror=()=>c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),u&&l.upload.addEventListener("progress",u,!1),l.open("POST",f,!0),Object.entries(d).forEach(([h,y])=>{l.setRequestHeader(h,y)}),l.send(e)})};class In{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return xn(this.url,r,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await nr(`${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 nr(`${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}`}}}const Rn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Pn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new In({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new kn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Rn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}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 St={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},_n=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...St},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:U({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:U({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:U({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:U({progress:t=>null,loaded:t=>0}),resetContext:U(t=>St),addFile:U({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 kn;i.append("file",n);let o=0;return xn(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:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,d=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:d})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:d,bucketId:f}=s;r({type:"UPLOAD_DONE",id:d,bucketId:f})}}),()=>{}}}}),{pure:ir,sendParent:Tt}=vi,io=()=>ve({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:U((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:U({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:U({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:U({loaded:t=>0}),startProgress:U({progress:t=>0}),resetProgress:U({progress:t=>null}),addItem:U((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Di(_n().withConfig({actions:{sendProgress:Tt((u,{additions:d})=>({type:"UPLOAD_PROGRESS",additions:d})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...St,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:U({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:ir(t=>t.files.map(e=>W({type:"DESTROY"},{to:e.id}))),upload:ir((t,e)=>t.files.map(r=>W(e,{to:r.id}))),cancel:ir(t=>t.files.map(e=>W({type:"CANCEL"},{to:e.id})))}}),oo=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})})}),so=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 o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ao=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function bt(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 o=n.match(ao);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:d=1337}=o.groups,f=lo(e);return f||`${s}://${u}:${d}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function co(){return typeof window<"u"}function uo(){return typeof process<"u"&&process.env}function lo(t){return co()||!uo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Un(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new On({url:e,...t})}function Dn(t){const e="subdomain"in t||"backendUrl"in t?bt(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){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Gt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.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 ho(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Cn(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 fo(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Cn(n)}catch{}return{query:t,operationName:r}}const e=Cn(t);return{query:Se.print(t),operationName:e}}class po{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,o=ho(e,n,i),{headers:s,...u}=i||{},{query:d,operationName:f}=fo(o.document);try{const c=await Gt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:d,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!c.ok)return{data:null,error:{error:c.statusText,message:c.statusText,status:c.status}};const{data:l,errors:h}=await c.json();return h?{data:null,error:h}: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(c){const l=c;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 Mn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new po({url:e,...t})}function Ln(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pn({url:e,...t})}const vo=t=>new jn(t);class jn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:d=!0,...f}){this.auth=Un({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:d,...f}),this.storage=Ln({adminSecret:s,...f}),this.functions=Dn({adminSecret:s,...f}),this.graphql=Mn({adminSecret:s,...f}),this.auth.onAuthStateChanged((c,l)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Xt,g.AuthClientSSR=Xi,g.AuthCookieClient=hn,g.CodifiedError=Ve,g.EMAIL_NEEDS_VERIFICATION=Yr,g.HasuraAuthClient=On,g.HasuraStorageApi=In,g.HasuraStorageClient=Pn,g.INITIAL_FILE_CONTEXT=St,g.INITIAL_MACHINE_CONTEXT=vt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=qr,g.INVALID_MFA_TICKET_ERROR=Gr,g.INVALID_MFA_TYPE_ERROR=Fr,g.INVALID_PASSWORD_ERROR=pt,g.INVALID_PHONE_NUMBER_ERROR=zt,g.INVALID_REFRESH_TOKEN=Wr,g.INVALID_SIGN_IN_METHOD=Jr,g.MIN_PASSWORD_LENGTH=$r,g.NETWORK_ERROR_CODE=Ht,g.NHOST_JWT_EXPIRES_AT_KEY=Ge,g.NHOST_REFRESH_TOKEN_KEY=qe,g.NO_MFA_TICKET_ERROR=Vr,g.NO_REFRESH_TOKEN=Hr,g.NhostClient=jn,g.NhostFunctionsClient=Nn,g.OTHER_ERROR_CODE=Kt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Vt,g.STATE_ERROR_CODE=_e,g.TOKEN_REFRESHER_RUNNING_ERROR=Kr,g.TOKEN_REFRESH_MARGIN=Br,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=Fi,g.USER_UNAUTHENTICATED=zr,g.VALIDATION_ERROR_CODE=re,g.activateMfaPromise=eo,g.addSecurityKeyPromise=fn,g.appendImageTransformationParameters=Rn,g.changeEmailPromise=pn,g.changePasswordPromise=vn,g.createAuthClient=Un,g.createAuthMachine=an,g.createChangeEmailMachine=cn,g.createChangePasswordMachine=un,g.createEnableMfaMachine=Qi,g.createFileUploadMachine=_n,g.createFunctionsClient=Dn,g.createGraphqlClient=Mn,g.createMultipleFilesUploadMachine=io,g.createNhostClient=vo,g.createResetPasswordMachine=ln,g.createSendVerificationEmailMachine=dn,g.createStorageClient=Ln,g.encodeQueryParameters=Wt,g.generateQrCodePromise=Zi,g.getAuthenticationResult=ye,g.getFetch=on,g.getParameterByName=Ke,g.getSession=He,g.isBrowser=wt,g.isValidEmail=de,g.isValidPassword=Et,g.isValidPhoneNumber=Qt,g.isValidTicket=sn,g.localStorageGetter=tn,g.localStorageSetter=rn,g.postFetch=le,g.removeParameterFromWindow=Jt,g.resetPasswordPromise=yn,g.rewriteRedirectTo=ne,g.sendVerificationEmailPromise=mn,g.signInAnonymousPromise=gn,g.signInEmailPasswordPromise=wn,g.signInEmailPasswordlessPromise=Zt,g.signInEmailSecurityKeyPromise=En,g.signInMfaTotpPromise=Sn,g.signInSmsPasswordlessOtpPromise=Tn,g.signInSmsPasswordlessPromise=er,g.signOutPromise=bn,g.signUpEmailPasswordPromise=tr,g.signUpEmailSecurityKeyPromise=An,g.uploadFilePromise=oo,g.uploadMultipleFilesPromise=so,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
22
20
|
//# sourceMappingURL=nhost-js.umd.js.map
|