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