@nhost/nhost-js 1.13.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/functions/index.d.ts +2 -11
- package/dist/clients/functions/index.d.ts.map +1 -1
- package/dist/clients/functions/types.d.ts +2 -9
- package/dist/clients/functions/types.d.ts.map +1 -1
- package/dist/clients/graphql.d.ts +7 -0
- package/dist/clients/graphql.d.ts.map +1 -0
- package/dist/clients/nhost.d.ts +5 -5
- package/dist/clients/nhost.d.ts.map +1 -1
- package/dist/clients/storage.d.ts +1 -1
- package/dist/clients/storage.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +89 -182
- package/dist/index.esm.js.map +1 -1
- package/dist/utils/types.d.ts +3 -1
- package/dist/utils/types.d.ts.map +1 -1
- package/package.json +7 -14
- package/umd/nhost-js.umd.js +9 -9
- package/umd/nhost-js.umd.js.map +1 -1
- package/dist/clients/graphql/index.d.ts +0 -49
- package/dist/clients/graphql/index.d.ts.map +0 -1
- package/dist/clients/graphql/types.d.ts +0 -32
- package/dist/clients/graphql/types.d.ts.map +0 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(E,Se){typeof exports=="object"&&typeof module<"u"?Se(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],Se):(E=typeof globalThis<"u"?globalThis:E||self,Se(E["@nhost/nhost-js"]={},E.graphql))})(this,function(E,Se){"use strict";function _t(t){this.message=t}_t.prototype=new Error,_t.prototype.name="InvalidCharacterError";var dr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new _t("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,o=0,s="";n=e.charAt(o++);~n&&(r=i%4?64*r+n:n,i++%4)?s+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function Yn(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(dr(r).replace(/(.)/g,function(n,i){var o=i.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(e)}catch{return dr(e)}}function Je(t){this.message=t}function Wn(t,e){if(typeof t!="string")throw new Je("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse(Yn(t.split(".")[r]))}catch(n){throw new Je("Invalid token specified: "+n.message)}}Je.prototype=new Error,Je.prototype.name="InvalidTokenError";/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -11,12 +11,12 @@
|
|
|
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 y=function(){return y=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},y.apply(this,arguments)};function Ht(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 R(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 O(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(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function L(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 U;(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"})(U||(U={}));var ee;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ee||(ee={}));var it=U.Start,st=U.Stop,ge=U.Raise,ye=U.Send,Kt=U.Cancel,Dr=U.NullEvent,ot=U.Assign,zi=U.After,Hi=U.DoneState,at=U.Log,Lr=U.Init,ct=U.Invoke,Ki=U.ErrorExecution,Gt=U.ErrorPlatform,Jt=U.ErrorCustom,ut=U.Update,Mr=U.Choose,jr=U.Pure;const Gi=Object.freeze(Object.defineProperty({__proto__:null,after:zi,assign:ot,cancel:Kt,choose:Mr,doneState:Hi,error:Jt,errorExecution:Ki,errorPlatform:Gt,init:Lr,invoke:ct,log:at,nullEvent:Dr,pure:jr,raise:ge,send:ye,start:it,stop:st,update:ut},Symbol.toStringTag,{value:"Module"}));var Fr=".",$r={},Wt="xstate.guard",Ji="",F=process.env.NODE_ENV==="production",lt;function Yt(t,e,r){r===void 0&&(r=Fr);var n=Me(t,r),i=Me(e,r);return I(i)?I(n)?i===n:!1:I(n)?n in i:Object.keys(n).every(function(s){return s in i?Yt(n[s],i[s]):!1})}function Br(t){try{return I(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 Qt(t,e){try{return Te(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function Wi(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Me(t,e){if(Wi(t))return t.value;if(Te(t))return dt(t);if(typeof t!="string")return t;var r=Qt(t,e);return dt(r)}function dt(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 je(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 qr(t,e,r){var n,i,s={};try{for(var o=R(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,c=t[u];r(c)&&(s[u]=e(c,u,t))}}catch(l){n={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var Yi=function(t){return function(e){var r,n,i=e;try{for(var s=R(t),o=s.next();!o.done;o=s.next()){var a=o.value;i=i[a]}}catch(u){r={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function Qi(t,e){return function(r){var n,i,s=r;try{for(var o=R(t),a=o.next();!a.done;a=o.next()){var u=a.value;s=s[e][u]}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function ft(t){if(!t)return[[]];if(I(t))return[[t]];var e=$(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:ft(t[r]).map(function(i){return[r].concat(i)})}));return e}function $(t){var e;return(e=[]).concat.apply(e,L([],O(t),!1))}function Vr(t){return Te(t)?t:[t]}function W(t){return t===void 0?[]:Vr(t)}function ht(t,e,r){var n,i;if(_(t))return t(e,r.data);var s={};try{for(var o=R(Object.keys(t)),a=o.next();!a.done;a=o.next()){var u=a.value,c=t[u];_(c)?s[u]=c(e,r.data):s[u]=c}}catch(l){n={error:l}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function Xi(t){return/^(done|error)\./.test(t)}function zr(t){return!!(t instanceof Promise||t!==null&&(_(t)||typeof t=="object")&&_(t.then))}function Zi(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function es(t,e){var r,n,i=O([[],[]],2),s=i[0],o=i[1];try{for(var a=R(t),u=a.next();!u.done;u=a.next()){var c=u.value;e(c)?s.push(c):o.push(c)}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return[s,o]}function Hr(t,e){return je(t.states,function(r,n){if(r){var i=(I(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:Hr(r,i)}}})}function ts(t,e){return{current:e,states:Hr(t,e)}}function Kr(t,e,r,n){F||B(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var a,u,c=o.assignment,l={state:n,action:o,_event:e},v={};if(_(c))v=c(s,e.data,l);else try{for(var h=R(Object.keys(c)),f=h.next();!f.done;f=h.next()){var d=f.value,p=c[d];v[d]=_(p)?p(s,e.data,l):p}}catch(g){a={error:g}}finally{try{f&&!f.done&&(u=h.return)&&u.call(h)}finally{if(a)throw a.error}}return Object.assign({},s,v)},t);return i}var B=function(){};F||(B=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function Te(t){return Array.isArray(t)}function _(t){return typeof t=="function"}function I(t){return typeof t=="string"}function Gr(t,e){if(t)return I(t)?{type:Wt,name:t,predicate:e?e[t]:void 0}:_(t)?{type:Wt,name:t.name,predicate:t}:t}function rs(t){try{return"subscribe"in t&&_(t.subscribe)}catch{return!1}}var de=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();lt={},lt[de]=function(){return this},lt[Symbol.observable]=function(){return this};function ne(t){return!!t&&"__xstatenode"in t}function ns(t){return!!t&&typeof t.send=="function"}var is=function(){var t=0;return function(){return t++,t.toString(16)}}();function Xt(t,e){return I(t)||typeof t=="number"?y({type:t},e):t}function z(t,e){if(!I(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Xt(t);return y({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function be(t,e){var r=Vr(e).map(function(n){return typeof n>"u"||typeof n=="string"||ne(n)?{target:n,event:t}:y(y({},n),{event:t})});return r}function ss(t){if(!(t===void 0||t===Ji))return W(t)}function os(t,e,r){if(!F){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 Jr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Wt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var a=s==null?void 0:s[e.type];if(!a)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return a(r,n.data,o)}function Wr(t){return typeof t=="string"?{type:t}:t}function pt(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 vt(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=z({type:Lr});function mt(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(I(t)||typeof t=="number"){var n=mt(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=mt(t.type,e);if(_(n))r=y(y({},t),{exec:n});else if(n){var i=n.type||t.type;r=y(y(y({},n),t),{type:i})}else r=t}return r}var ie=function(t,e){if(!t)return[];var r=Te(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function gt(t){var e=Ae(t);return y(y({id:I(t)?t:e.id},e),{type:e.type})}function Yr(t){return I(t)?{type:ge,event:t}:fe(t,{to:ee.Internal})}function Qr(t){return{type:ge,_event:z(t.event)}}function fe(t,e){return{to:e?e.to:void 0,type:ye,event:_(t)?t:Xt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:_(t)?t.name:Br(t)}}function Xr(t,e,r,n){var i={_event:r},s=z(_(t.event)?t.event(e,r.data,i):t.event),o;if(I(t.delay)){var a=n&&n[t.delay];o=_(a)?a(e,r.data,i):a}else o=_(t.delay)?t.delay(e,r.data,i):t.delay;var u=_(t.to)?t.to(e,r.data,i):t.to;return y(y({},t),{to:u,_event:s,event:s.data,delay:o})}function Zt(t,e){return fe(t,y(y({},e),{to:ee.Parent}))}function as(t,e,r){return fe(e,y(y({},r),{to:t}))}function cs(){return Zt(ut)}function us(t,e){return fe(t,y(y({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var ls=function(t,e){return{context:t,event:e}};function ds(t,e){return t===void 0&&(t=ls),{type:at,label:e,expr:t}}var Zr=function(t,e,r){return y(y({},t),{value:I(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},en=function(t){return{type:Kt,sendId:t}};function tn(t){var e=gt(t);return{type:U.Start,activity:e,exec:void 0}}function rn(t){var e=_(t)?t:gt(t);return{type:U.Stop,activity:e,exec:void 0}}function nn(t,e,r){var n=_(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:U.Stop,activity:i};return s}var sn=function(t){return{type:ot,assignment:t}};function fs(t){return typeof t=="object"&&"type"in t}function on(t,e){var r=e?"#".concat(e):"";return"".concat(U.After,"(").concat(t,")").concat(r)}function Fe(t,e){var r="".concat(U.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function $e(t,e){var r="".concat(U.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat(U.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function hs(t){return{type:U.Pure,get:t}}function ps(t,e){if(!F&&(!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,L([],O(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 fe(function(n,i){return i},y(y({},e),{to:t}))}function vs(t,e){return Zt(function(r,n,i){return{type:Jt,data:_(t)?t(r,n,i):t}},y(y({},e),{to:ee.Parent}))}function ms(t){return{type:U.Choose,conds:t}}var gs=function(t){var e,r,n=[];try{for(var i=R(t),s=i.next();!s.done;s=i.next())for(var o=s.value,a=0;a<o.length;){if(o[a].type===ot){n.push(o[a]),o.splice(a,1);continue}a++}}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 Be(t,e,r,n,i,s,o){o===void 0&&(o=!1);var a=o?[]:gs(i),u=a.length?Kr(r,n,a,e):r,c=o?[r]:void 0,l=[];function v(d){var p;switch(d.type){case ge:return Qr(d);case ye:var g=Xr(d,u,n,t.options.delays);return F||B(!I(d.delay)||typeof g.delay=="number","No delay reference for delay expression '".concat(d.delay,"' was found on machine '").concat(t.id,"'")),s&&g.to!==ee.Internal&&l.push(g),g;case at:{var E=Zr(d,u,n);return s==null||s(E,u,n),E}case Mr:{var S=d,T=(p=S.conds.find(function(X){var le=Gr(X.cond,t.options.guards);return!le||Jr(t,le,u,n,s?void 0:e)}))===null||p===void 0?void 0:p.actions;if(!T)return[];var P=O(Be(t,e,u,n,[ie(W(T),t.options.actions)],s,o),2),k=P[0],j=P[1];return u=j,c==null||c.push(u),k}case jr:{var T=d.get(u,n.data);if(!T)return[];var x=O(Be(t,e,u,n,[ie(W(T),t.options.actions)],s,o),2),C=x[0],D=x[1];return u=D,c==null||c.push(u),C}case st:{var E=nn(d,u,n);return s==null||s(E,r,n),E}case ot:{u=Kr(u,n,[d],s?void 0:e),c==null||c.push(u);break}default:var b=Ae(d,t.options.actions),M=b.exec;if(s)s(b,u,n);else if(M&&c){var J=c.length-1;b=y(y({},b),{exec:function(X){for(var le=[],Ue=1;Ue<arguments.length;Ue++)le[Ue-1]=arguments[Ue];M.apply(void 0,L([c[J]],O(le),!1))}})}return b}}function h(d){var p,g,E=[];try{for(var S=R(d),T=S.next();!T.done;T=S.next()){var P=T.value,k=v(P);k&&(E=E.concat(k))}}catch(j){p={error:j}}finally{try{T&&!T.done&&(g=S.return)&&g.call(S)}finally{if(p)throw p.error}}return l.forEach(function(j){s(j,u,n)}),l.length=0,E}var f=$(i.map(h));return[f,u]}const ys=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:Gi,after:on,assign:sn,cancel:en,choose:ms,done:Fe,doneInvoke:$e,error:Oe,escalate:vs,forwardTo:ps,getActionFunction:mt,initEvent:we,isActionObject:fs,log:ds,pure:hs,raise:Yr,resolveActions:Be,resolveLog:Zr,resolveRaise:Qr,resolveSend:Xr,resolveStop:nn,respond:us,send:fe,sendParent:Zt,sendTo:as,sendUpdate:cs,start:tn,stop:rn,toActionObject:Ae,toActionObjects:ie,toActivityDefinition:gt},Symbol.toStringTag,{value:"Module"}));var yt=[],Re=function(t,e){yt.push(t);var r=e(t);return yt.pop(),r},ws=function(t){return t(yt[yt.length-1])};function an(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[de]=function(){return this},e}function Es(t,e,r,n){var i,s=Wr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],a=t.data?ht(t.data,r,n):void 0,u=o?er(o,t.id,a):an(t.id);return u.meta=t,u}function er(t,e,r){var n=an(e);if(n.deferred=!0,ne(t)){var i=n.state=Re(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function Ss(t){try{return typeof t.send=="function"}catch{return!1}}function Ts(t){return Ss(t)&&"id"in t}function bs(t){var e;return y((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[de]=function(){return this},e),t)}var wt=function(t){return t.type==="atomic"||t.type==="final"};function cn(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function qe(t){return cn(t).filter(function(e){return e.type!=="history"})}function un(t){var e=[t];return wt(t)?e:e.concat($(qe(t).map(un)))}function Ve(t,e){var r,n,i,s,o,a,u,c,l=new Set(t),v=tr(l),h=new Set(e);try{for(var f=R(h),d=f.next();!d.done;d=f.next())for(var p=d.value,g=p.parent;g&&!h.has(g);)h.add(g),g=g.parent}catch(D){r={error:D}}finally{try{d&&!d.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}var E=tr(h);try{for(var S=R(h),T=S.next();!T.done;T=S.next()){var p=T.value;if(p.type==="compound"&&(!E.get(p)||!E.get(p).length))v.get(p)?v.get(p).forEach(function(b){return h.add(b)}):p.initialStateNodes.forEach(function(b){return h.add(b)});else if(p.type==="parallel")try{for(var P=(o=void 0,R(qe(p))),k=P.next();!k.done;k=P.next()){var j=k.value;h.has(j)||(h.add(j),v.get(j)?v.get(j).forEach(function(b){return h.add(b)}):j.initialStateNodes.forEach(function(b){return h.add(b)}))}}catch(b){o={error:b}}finally{try{k&&!k.done&&(a=P.return)&&a.call(P)}finally{if(o)throw o.error}}}}catch(D){i={error:D}}finally{try{T&&!T.done&&(s=S.return)&&s.call(S)}finally{if(i)throw i.error}}try{for(var x=R(h),C=x.next();!C.done;C=x.next())for(var p=C.value,g=p.parent;g&&!h.has(g);)h.add(g),g=g.parent}catch(D){u={error:D}}finally{try{C&&!C.done&&(c=x.return)&&c.call(x)}finally{if(u)throw u.error}}return h}function ln(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(wt(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=ln(s,e)}),i}function tr(t){var e,r,n=new Map;try{for(var i=R(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(a){e={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function As(t,e){var r=Ve([t],e);return ln(t,tr(r))}function ze(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Os(t){return L([],O(new Set($(L([],O(t.map(function(e){return e.ownEvents})),!1)))),!1)}function Et(t,e){return e.type==="compound"?qe(e).some(function(r){return r.type==="final"&&ze(t,r)}):e.type==="parallel"?qe(e).every(function(r){return Et(t,r)}):!1}function Rs(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function dn(t){return new Set($(t.map(function(e){return e.tags})))}function fn(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(I(t)||I(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return fn(t[i],e[i])})}function ks(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function xs(t,e){var r=t.exec,n=y(y({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var te=function(){function t(e){var r=this,n;this.actions=[],this.activities=$r,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||$r,this.meta=Rs(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 Os(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="."),I(e))return[e];var i=Object.keys(e);return i.concat.apply(i,L([],O(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=Ht(e,["configuration","transitions","tags","machine"]);return y(y({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Yt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;F&&B(!!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}(),Is={deferEvents:!1},hn=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=y(y({},Is),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}(),rr=new Map,Ns=0,St={bookId:function(){return"x:".concat(Ns++)},register:function(t,e){return rr.set(t,e),t},get:function(t){return rr.get(t)},free:function(t){rr.delete(t)}};function nr(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;F||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 Ps(){var t=nr();if(t&&"__xstate__"in t)return t.__xstate__}function Cs(t){if(nr()){var e=Ps();e&&e.register(t)}}function Us(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 c=i.shift();r=t.transition(r,c,u),n.forEach(function(l){return l.next(r)})}s=!1}},a=bs({id:e.id,send:function(c){i.push(c),o()},getSnapshot:function(){return r},subscribe:function(c,l,v){var h=pt(c,l,v);return n.add(h),h.next(r),{unsubscribe:function(){n.delete(h)}}}}),u={parent:e.parent,self:a,id:e.id||"anonymous",observers:n};return r=t.start?t.start(u):r,a}var ir={sync:!1,autoForward:!1},q;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(q||(q={}));var _s=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=q.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(l,v){if(Te(l))return n.batch(l),n.state;var h=z(Xt(l,v));if(n.status===q.Stopped)return F||B(!1,'Event "'.concat(h.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
15
|
-
Event: `).concat(JSON.stringify(
|
|
16
|
-
Event: `).concat(JSON.stringify(
|
|
17
|
-
Event: `).concat(JSON.stringify(event)));else if(this.status!==q.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,a=!1,u=[],c=function(f){var d=z(f);r.forward(d),o=Re(r,function(){return r.machine.transition(o,d,void 0,n||void 0)}),u.push.apply(u,L([],O(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(p){return xs(p,o)})),!1)),a=a||!!o.changed};try{for(var l=R(e),v=l.next();!v.done;v=l.next()){var h=v.value;c(h)}}catch(f){i={error:f}}finally{try{v&&!v.done&&(s=l.return)&&s.call(l)}finally{if(i)throw i.error}}o.changed=a,o.actions=u,r.update(o,z(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=z(e);if(i.name.indexOf(Gt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(Gt)===0}))throw i.data.data;var s=Re(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=R(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,a=this.children.get(o);if(!a)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));a.send(e)}}catch(u){r={error:u}}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!==q.Running)return er(e,r);if(zr(e))return this.spawnPromise(Promise.resolve(e),r);if(_(e))return this.spawnCallback(e,r);if(Ts(e))return this.spawnActor(e,r);if(rs(e))return this.spawnObservable(e,r);if(ne(e))return this.spawnMachine(e,y(y({},n),{id:r}));if(Zi(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,y(y({},this.options),{parent:this,id:r.id||e.id})),s=y(y({},ir),r);s.sync&&i.onTransition(function(a){n.send(ut,{state:a,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(a){n.removeChild(i.id),n.send(z(a,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Us(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(u){s||(o=u,i.removeChild(r),i.send(z($e(r,u),{origin:r})))},function(u){if(!s){i.removeChild(r);var c=Oe(r,u);try{i.send(z(c,{origin:r}))}catch(l){os(u,l,r),i.devTools&&i.devTools.send(c,i.state),i.machine.strict&&i.stop()}}});var a=(n={id:r,send:function(){},subscribe:function(u,c,l){var v=pt(u,c,l),h=!1;return e.then(function(f){h||(v.next(f),!h&&v.complete())},function(f){h||v.error(f)}),{unsubscribe:function(){return h=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[de]=function(){return this},n);return this.children.set(r,a),a},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,a=new Set,u,c=function(h){u=h,a.forEach(function(f){return f(h)}),!s&&i.send(z(h,{origin:r}))},l;try{l=e(c,function(h){o.add(h)})}catch(h){this.send(Oe(r,h))}if(zr(l))return this.spawnPromise(l,r);var v=(n={id:r,send:function(h){return o.forEach(function(f){return f(h)})},subscribe:function(h){var f=pt(h);return a.add(f.next),{unsubscribe:function(){a.delete(f.next)}}},stop:function(){s=!0,_(l)&&l()},toJSON:function(){return{id:r}},getSnapshot:function(){return u}},n[de]=function(){return this},n);return this.children.set(r,v),v},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(u){s=u,i.send(z(u,{origin:r}))},function(u){i.removeChild(r),i.send(z(Oe(r,u),{origin:r}))},function(){i.removeChild(r),i.send(z($e(r),{origin:r}))}),a=(n={id:r,send:function(){},subscribe:function(u,c,l){return e.subscribe(u,c,l)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[de]=function(){return this},n);return this.children.set(r,a),a},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){F||B(!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[de]=function(){return this},n))},t.prototype.attachDev=function(){var e=nr();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(y(y({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:y({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Cs(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[de]=function(){return this},t.prototype.getSnapshot=function(){return this.status===q.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=ke,t}(),Ds=function(t){return I(t)?y(y({},ir),{name:t}):y(y(y({},ir),{name:is()}),t)};function Ls(t,e){var r=Ds(e);return ws(function(n){if(!F){var i=ne(t)||_(t);B(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ne(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):er(t,r.name)})}function ke(t,e){var r=new _s(t,e);return r}function Ms(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function Tt(t){return y(y({type:ct},t),{toJSON:function(){t.onDone,t.onError;var e=Ht(t,["onDone","onError"]);return y(y({},e),{type:ct,src:Ms(t.src)})}})}var xe="",sr="#",He="*",Ie={},Ne=function(t){return t[0]===sr},js=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Fs=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(I(s.target)||ne(s.target))}),i=e===xe?"the transient event":"event '".concat(e,"'");B(!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.")},$s=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(js(),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:Fr),this.id=this.config.id||L([this.machine.key],O(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,F||B(!("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?je(this.config.states,function(c,l){var v,h=new t(c,{},void 0,{parent:s,key:l});return Object.assign(s.idMap,y((v={},v[h.id]=h,v),h.idMap)),h}):Ie;var a=0;function u(c){var l,v;c.order=a++;try{for(var h=R(cn(c)),f=h.next();!f.done;f=h.next()){var d=f.value;u(d)}}catch(p){l={error:p}}finally{try{f&&!f.done&&(v=h.return)&&v.call(h)}finally{if(l)throw l.error}}}u(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(c){var l=c.event;return l===xe}):xe in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=W(this.config.entry||this.config.onEntry).map(function(c){return Ae(c)}),this.onExit=W(this.config.exit||this.config.onExit).map(function(c){return Ae(c)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=W(this.config.invoke).map(function(c,l){var v,h;if(ne(c)){var f=vt(s.id,l);return s.machine.options.services=y((v={},v[f]=c,v),s.machine.options.services),Tt({src:f,id:f})}else if(I(c.src)){var f=c.id||vt(s.id,l);return Tt(y(y({},c),{id:f,src:c.src}))}else if(ne(c.src)||_(c.src)){var f=c.id||vt(s.id,l);return s.machine.options.services=y((h={},h[f]=c.src,h),s.machine.options.services),Tt(y(y({id:f},c),{src:f}))}else{var d=c.src;return Tt(y(y({id:vt(s.id,l)},c),{src:d}))}}),this.activities=W(this.config.activities).concat(this.invoke).map(function(c){return gt(c)}),this.transition=this.transition.bind(this),this.tags=W(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||un(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,a=n.services,u=n.delays;return new t(this.config,{actions:y(y({},i),e.actions),activities:y(y({},s),e.activities),guards:y(y({},o),e.guards),services:y(y({},a),e.services),delays:y(y({},u),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return _(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:je(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===xe,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===He});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 a=_(s)?"".concat(e.id,":delay[").concat(o,"]"):s,u=on(a,e.id);return e.onEntry.push(fe(u,{delay:s})),e.onExit.push(en(u)),u},i=Te(r)?r.map(function(s,o){var a=n(s.delay,o);return y(y({},s),{event:a})}):$(Object.keys(r).map(function(s,o){var a=r[s],u=I(a)?{target:a}:a,c=isNaN(+s)?s:+s,l=n(c,o);return W(u).map(function(v){return y(y({},v),{event:l,delay:c})})}));return i.map(function(s){var o=s.delay;return y(y({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof te?e.value:Me(e,this.delimiter);if(I(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),a=[this];return a.push.apply(a,L([],O($(o.map(function(u){return n.getStateNode(u).getStateNodes(i[u])}))),!1)),a},t.prototype.handles=function(e){var r=Br(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof te?e:te.create(e),n=Array.from(Ve([],this.getStateNodes(r.value)));return new te(y(y({},r),{value:this.resolve(r.value),configuration:n,done:Et(n,this),tags:dn(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 a=R(Object.keys(e)),u=a.next();!u.done;u=a.next()){var c=u.value,l=e[c];if(l){var v=this.getStateNode(c),h=v._transition(l,r,n);h&&(o[c]=h)}}}catch(S){i={error:S}}finally{try{u&&!u.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}var f=Object.keys(o).map(function(S){return o[S]}),d=$(f.map(function(S){return S.transitions})),p=f.some(function(S){return S.transitions.length>0});if(!p)return this.next(r,n);var g=$(f.map(function(S){return S.entrySet})),E=$(Object.keys(o).map(function(S){return o[S].configuration}));return{transitions:d,entrySet:g,exitSet:$(f.map(function(S){return S.exitSet})),configuration:E,source:r,actions:$(Object.keys(o).map(function(S){return o[S].actions}))}},t.prototype._transition=function(e,r,n){return I(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,z(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,a=[],u=[],c;try{for(var l=R(this.getCandidates(o)),v=l.next();!v.done;v=l.next()){var h=v.value,f=h.cond,d=h.in,p=e.context,g=d?I(d)&&Ne(d)?e.matches(Me(this.getStateNodeById(d).path,this.delimiter)):Yt(Me(d,this.delimiter),Yi(this.path.slice(0,-2))(e.value)):!0,E=!1;try{E=!f||Jr(this.machine,f,p,r,e)}catch(k){throw new Error("Unable to evaluate guard '".concat(f.name||f.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
-
`).concat(k.message))}if(E&&g){h.target!==void 0&&(u=h.target),a.push.apply(a,L([],O(h.actions),!1)),c=h;break}}}catch(k){n={error:k}}finally{try{v&&!v.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}if(c){if(!u.length)return{transitions:[c],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:a};var S=$(u.map(function(k){return s.getRelativeStateNodes(k,e.historyValue)})),T=!!c.internal,P=[];return T||u.forEach(function(k){P.push.apply(P,L([],O(s.getExternalReentryNodes(k)),!1))}),{transitions:[c],entrySet:P,exitSet:T?[]:[this],configuration:S,source:e,actions:a}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=O(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,a){var u,c,l,v,h=this,f=Ve([],o?this.getStateNodes(o.value):[this]);try{for(var d=R(e),p=d.next();!p.done;p=d.next()){var g=p.value;(!ze(f,g)||ze(n.entrySet,g.parent))&&n.entrySet.push(g)}}catch(b){u={error:b}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(u)throw u.error}}try{for(var E=R(f),S=E.next();!S.done;S=E.next()){var g=S.value;(!ze(e,g)||ze(n.exitSet,g.parent))&&n.exitSet.push(g)}}catch(b){l={error:b}}finally{try{S&&!S.done&&(v=E.return)&&v.call(E)}finally{if(l)throw l.error}}var T=$(n.entrySet.map(function(b){var M=[];if(b.type!=="final")return M;var J=b.parent;if(!J.parent)return M;M.push(Fe(b.id,b.doneData),Fe(J.id,b.doneData?ht(b.doneData,i,s):void 0));var X=J.parent;return X.type==="parallel"&&qe(X).every(function(le){return Et(n.configuration,le)})&&M.push(Fe(X.id)),M}));n.exitSet.sort(function(b,M){return M.order-b.order}),n.entrySet.sort(function(b,M){return b.order-M.order});var P=new Set(n.entrySet),k=new Set(n.exitSet),j=Array.from(P).map(function(b){var M=b.onEntry,J=b.activities.map(function(X){return tn(X)});return ie(a?L(L([],O(M),!1),O(J),!1):L(L([],O(J),!1),O(M),!1),h.machine.options.actions)}).concat([T.map(Yr)]),x=Array.from(k).map(function(b){return ie(L(L([],O(b.onExit),!1),O(b.activities.map(function(M){return rn(M)})),!1),h.machine.options.actions)}),C=x.concat([ie(n.actions,this.machine.options.actions)]).concat(j);if(r){var D=ie($(L([],O(e),!1).sort(function(b,M){return M.order-b.order}).map(function(b){return b.onExit})),this.machine.options.actions).filter(function(b){return b.type!==ge&&(b.type!==ye||!!b.to&&b.to!==ee.Internal)});return C.concat([D])}return C},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=z(r),o;if(e instanceof te)o=n===void 0?e:this.resolveState(te.from(e,n));else{var a=I(e)?this.resolve(dt(this.getResolvedPath(e))):this.resolve(e),u=n??this.machine.context;o=this.resolveState(te.from(a,u))}if(!F&&s.name===He)throw new Error("An event cannot have the wildcard type ('".concat(He,"')"));if(this.strict&&!this.events.includes(s.name)&&!Xi(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var c=this._transition(o.value,o,s)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:o,actions:[]},l=Ve([],this.getStateNodes(o.value)),v=c.configuration.length?Ve(l,c.configuration):l;return c.configuration=L([],O(v),!1),this.resolveTransition(c,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,L([],O(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,a,u,c,l=this;s===void 0&&(s=we);var v=e.configuration,h=!r||e.transitions.length>0,f=h?e.configuration:r?r.configuration:[],d=Et(f,this),p=h?As(this.machine,v):void 0,g=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(f),d,e,n,s,r,i),S=r?y({},r.activities):{};try{for(var T=R(E),P=T.next();!P.done;P=T.next()){var k=P.value;try{for(var j=(u=void 0,R(k)),x=j.next();!x.done;x=j.next()){var C=x.value;C.type===it?S[C.activity.id||C.activity.type]=C:C.type===st&&(S[C.activity.id||C.activity.type]=!1)}}catch(G){u={error:G}}finally{try{x&&!x.done&&(c=j.return)&&c.call(j)}finally{if(u)throw u.error}}}}catch(G){o={error:G}}finally{try{P&&!P.done&&(a=T.return)&&a.call(T)}finally{if(o)throw o.error}}var D=O(Be(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),b=D[0],M=D[1],J=O(es(b,function(G){return G.type===ge||G.type===ye&&G.to===ee.Internal}),2),X=J[0],le=J[1],Ue=b.filter(function(G){var De;return G.type===it&&((De=G.activity)===null||De===void 0?void 0:De.type)===ct}),ha=Ue.reduce(function(G,De){return G[De.activity.id]=Es(De.activity,l.machine,M,s),G},r?y({},r.children):{}),Vt=new te({value:p||r.value,context:M,_event:s,_sessionid:r?r._sessionid:null,historyValue:p?g?ts(g,p):void 0:r?r.historyValue:void 0,history:!p||e.source?r:void 0,actions:p?le:[],activities:p?S:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:ha,done:d,tags:dn(f),machine:this}),$i=n!==M;Vt.changed=s.name===ut||$i;var _e=Vt.history;_e&&delete _e.history;var Bi=!d&&(this._transient||v.some(function(G){return G._transient}));if(!h&&(!Bi||s.name===xe))return Vt;var Z=Vt;if(!d)for(Bi&&(Z=this.resolveRaisedTransition(Z,{type:Dr},s,i));X.length;){var pa=X.shift();Z=this.resolveRaisedTransition(Z,pa._event,s,i)}var va=Z.changed||(_e?!!Z.actions.length||$i||typeof _e.value!=typeof Z.value||!fn(Z.value,_e.value):void 0);return Z.changed=va,Z.history=_e,Z},t.prototype.getStateNode=function(e){if(Ne(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=Ne(e)?e.slice(sr.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"&&Ne(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Qt(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||Ie;switch(this.type){case"parallel":return je(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Ie});case"compound":if(I(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?je(e,function(s,o){return s?n.getStateNode(o).resolve(s):Ie}):this.initialStateValue||{};default:return e||Ie}},t.prototype.getResolvedPath=function(e){if(Ne(e)){var r=this.machine.idMap[e.slice(sr.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Qt(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=qr(this.states,function(n){return n.initialStateValue||Ie},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=wt(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:L([],O(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r??this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;I(r.target)?e=Ne(r.target)?dt(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(wt(this))return[this];if(this.type==="compound"&&!this.initial)return F||B(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=ft(this.initialStateValue);return $(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=O(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:qr(this.states,function(r,n){if(!e)return r.historyValue();var i=I(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?$(ft(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=Qi(n.path,"states")(e).current;return I(s)?[n.getStateNode(s)]:$(ft(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=$(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 a=R(Object.keys(s)),u=a.next();!u.done;u=a.next()){var c=u.value,l=s[c];if(l.states)try{for(var v=(n=void 0,R(l.events)),h=v.next();!h.done;h=v.next()){var f=h.value;o.add("".concat(f))}}catch(d){n={error:d}}finally{try{h&&!h.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}}}catch(d){e={error:d}}finally{try{u&&!u.done&&(r=a.return)&&r.call(a)}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(!I(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(a){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(a.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=ss(e.target),i="internal"in e?e.internal:n?n.some(function(u){return I(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),a=y(y({},e),{actions:ie(W(e.actions)),cond:Gr(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return y(y({},a),{target:a.target?a.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return a},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=He,a=s[o],u=a===void 0?[]:a,c=Ht(s,[typeof o=="symbol"?o:o+""]);i=$(Object.keys(c).map(function(S){!F&&S===xe&&B(!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 T=be(S,c[S]);return F||Fs(n,S,T),T}).concat(be(He,u)))}var l=this.config.always?be("",this.config.always):[],v=this.config.onDone?be(String(Fe(this.id)),this.config.onDone):[];F||B(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=$(this.invoke.map(function(S){var T=[];return S.onDone&&T.push.apply(T,L([],O(be(String($e(S.id)),S.onDone)),!1)),S.onError&&T.push.apply(T,L([],O(be(String(Oe(S.id)),S.onError)),!1)),T})),f=this.after,d=$(L(L(L(L([],O(v),!1),O(h),!1),O(i),!1),O(l),!1).map(function(S){return W(S).map(function(T){return n.formatTransition(T)})}));try{for(var p=R(f),g=p.next();!g.done;g=p.next()){var E=g.value;d.push(E)}}catch(S){e={error:S}}finally{try{g&&!g.done&&(r=p.return)&&r.call(p)}finally{if(e)throw e.error}}return d},t}(),pn=!1;function he(t,e){return!F&&!t.predictableActionArguments&&!pn&&(pn=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new $s(t,e)}var A=sn,V=fe;/*! js-cookie v3.0.1 | MIT */function bt(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 Bs={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 or(t,e){function r(i,s,o){if(!(typeof document>"u")){o=bt({},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 a="";for(var u in o)o[u]&&(a+="; "+u,o[u]!==!0&&(a+="="+o[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+a}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var u=s[a].split("="),c=u.slice(1).join("=");try{var l=decodeURIComponent(u[0]);if(o[l]=t.read(c,l),i===l)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",bt({},s,{expires:-1}))},withAttributes:function(i){return or(this.converter,bt({},this.attributes,i))},withConverter:function(i){return or(bt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var ar=or(Bs,{path:"/"});function vn(t,e){return function(){return t.apply(e,arguments)}}const{toString:mn}=Object.prototype,{getPrototypeOf:cr}=Object,ur=(t=>e=>{const r=mn.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),se=t=>(t=t.toLowerCase(),e=>ur(e)===t),At=t=>e=>typeof e===t,{isArray:Pe}=Array,Ke=At("undefined");function qs(t){return t!==null&&!Ke(t)&&t.constructor!==null&&!Ke(t.constructor)&&Ee(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const gn=se("ArrayBuffer");function Vs(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&gn(t.buffer),e}const zs=At("string"),Ee=At("function"),yn=At("number"),lr=t=>t!==null&&typeof t=="object",Hs=t=>t===!0||t===!1,Ot=t=>{if(ur(t)!=="object")return!1;const e=cr(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Ks=se("Date"),Gs=se("File"),Js=se("Blob"),Ws=se("FileList"),Ys=t=>lr(t)&&Ee(t.pipe),Qs=t=>{const e="[object FormData]";return t&&(typeof FormData=="function"&&t instanceof FormData||mn.call(t)===e||Ee(t.toString)&&t.toString()===e)},Xs=se("URLSearchParams"),Zs=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ge(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,i;if(typeof t!="object"&&(t=[t]),Pe(t))for(n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else{const s=r?Object.getOwnPropertyNames(t):Object.keys(t),o=s.length;let a;for(n=0;n<o;n++)a=s[n],e.call(null,t[a],a,t)}}function wn(t,e){e=e.toLowerCase();const r=Object.keys(t);let n=r.length,i;for(;n-- >0;)if(i=r[n],e===i.toLowerCase())return i;return null}const En=typeof self>"u"?typeof global>"u"?globalThis:global:self,Sn=t=>!Ke(t)&&t!==En;function dr(){const{caseless:t}=Sn(this)&&this||{},e={},r=(n,i)=>{const s=t&&wn(e,i)||i;Ot(e[s])&&Ot(n)?e[s]=dr(e[s],n):Ot(n)?e[s]=dr({},n):Pe(n)?e[s]=n.slice():e[s]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&Ge(arguments[n],r);return e}const eo=(t,e,r,{allOwnKeys:n}={})=>(Ge(e,(i,s)=>{r&&Ee(i)?t[s]=vn(i,r):t[s]=i},{allOwnKeys:n}),t),to=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),ro=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},no=(t,e,r,n)=>{let i,s,o;const a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],(!n||n(o,t,e))&&!a[o]&&(e[o]=t[o],a[o]=!0);t=r!==!1&&cr(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},io=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return n!==-1&&n===r},so=t=>{if(!t)return null;if(Pe(t))return t;let e=t.length;if(!yn(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},oo=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&cr(Uint8Array)),ao=(t,e)=>{const n=(t&&t[Symbol.iterator]).call(t);let i;for(;(i=n.next())&&!i.done;){const s=i.value;e.call(t,s[0],s[1])}},co=(t,e)=>{let r;const n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},uo=se("HTMLFormElement"),lo=t=>t.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,function(r,n,i){return n.toUpperCase()+i}),Tn=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),fo=se("RegExp"),bn=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};Ge(r,(i,s)=>{e(i,s,t)!==!1&&(n[s]=i)}),Object.defineProperties(t,n)},m={isArray:Pe,isArrayBuffer:gn,isBuffer:qs,isFormData:Qs,isArrayBufferView:Vs,isString:zs,isNumber:yn,isBoolean:Hs,isObject:lr,isPlainObject:Ot,isUndefined:Ke,isDate:Ks,isFile:Gs,isBlob:Js,isRegExp:fo,isFunction:Ee,isStream:Ys,isURLSearchParams:Xs,isTypedArray:oo,isFileList:Ws,forEach:Ge,merge:dr,extend:eo,trim:Zs,stripBOM:to,inherits:ro,toFlatObject:no,kindOf:ur,kindOfTest:se,endsWith:io,toArray:so,forEachEntry:ao,matchAll:co,isHTMLForm:uo,hasOwnProperty:Tn,hasOwnProp:Tn,reduceDescriptors:bn,freezeMethods:t=>{bn(t,(e,r)=>{if(Ee(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const n=t[r];if(Ee(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},toObjectSet:(t,e)=>{const r={},n=i=>{i.forEach(s=>{r[s]=!0})};return Pe(t)?n(t):n(String(t).split(e)),r},toCamelCase:lo,noop:()=>{},toFiniteNumber:(t,e)=>(t=+t,Number.isFinite(t)?t:e),findKey:wn,global:En,isContextDefined:Sn,toJSONObject:t=>{const e=new Array(10),r=(n,i)=>{if(lr(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[i]=n;const s=Pe(n)?[]:{};return Ge(n,(o,a)=>{const u=r(o,i+1);!Ke(u)&&(s[a]=u)}),e[i]=void 0,s}}return n};return r(t,0)}};function N(t,e,r,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i)}m.inherits(N,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:m.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const An=N.prototype,On={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{On[t]={value:t}}),Object.defineProperties(N,On),Object.defineProperty(An,"isAxiosError",{value:!0}),N.from=(t,e,r,n,i,s)=>{const o=Object.create(An);return m.toFlatObject(t,o,function(u){return u!==Error.prototype},a=>a!=="isAxiosError"),N.call(o,t.message,e,r,n,i),o.cause=t,o.name=t.name,s&&Object.assign(o,s),o};var Rn=typeof self=="object"?self.FormData:window.FormData;function fr(t){return m.isPlainObject(t)||m.isArray(t)}function kn(t){return m.endsWith(t,"[]")?t.slice(0,-2):t}function xn(t,e,r){return t?t.concat(e).map(function(i,s){return i=kn(i),!r&&s?"["+i+"]":i}).join(r?".":""):e}function ho(t){return m.isArray(t)&&!t.some(fr)}const po=m.toFlatObject(m,{},null,function(e){return/^is[A-Z]/.test(e)});function vo(t){return t&&m.isFunction(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator]}function Rt(t,e,r){if(!m.isObject(t))throw new TypeError("target must be an object");e=e||new(Rn||FormData),r=m.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,g){return!m.isUndefined(g[p])});const n=r.metaTokens,i=r.visitor||l,s=r.dots,o=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&vo(e);if(!m.isFunction(i))throw new TypeError("visitor must be a function");function c(d){if(d===null)return"";if(m.isDate(d))return d.toISOString();if(!u&&m.isBlob(d))throw new N("Blob is not supported. Use a Buffer instead.");return m.isArrayBuffer(d)||m.isTypedArray(d)?u&&typeof Blob=="function"?new Blob([d]):Buffer.from(d):d}function l(d,p,g){let E=d;if(d&&!g&&typeof d=="object"){if(m.endsWith(p,"{}"))p=n?p:p.slice(0,-2),d=JSON.stringify(d);else if(m.isArray(d)&&ho(d)||m.isFileList(d)||m.endsWith(p,"[]")&&(E=m.toArray(d)))return p=kn(p),E.forEach(function(T,P){!(m.isUndefined(T)||T===null)&&e.append(o===!0?xn([p],P,s):o===null?p:p+"[]",c(T))}),!1}return fr(d)?!0:(e.append(xn(g,p,s),c(d)),!1)}const v=[],h=Object.assign(po,{defaultVisitor:l,convertValue:c,isVisitable:fr});function f(d,p){if(!m.isUndefined(d)){if(v.indexOf(d)!==-1)throw Error("Circular reference detected in "+p.join("."));v.push(d),m.forEach(d,function(E,S){(!(m.isUndefined(E)||E===null)&&i.call(e,E,m.isString(S)?S.trim():S,p,h))===!0&&f(E,p?p.concat(S):[S])}),v.pop()}}if(!m.isObject(t))throw new TypeError("data must be an object");return f(t),e}function In(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function hr(t,e){this._pairs=[],t&&Rt(t,this,e)}const Nn=hr.prototype;Nn.append=function(e,r){this._pairs.push([e,r])},Nn.toString=function(e){const r=e?function(n){return e.call(this,n,In)}:In;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function mo(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Pn(t,e,r){if(!e)return t;const n=r&&r.encode||mo,i=r&&r.serialize;let s;if(i?s=i(e,r):s=m.isURLSearchParams(e)?e.toString():new hr(e,r).toString(n),s){const o=t.indexOf("#");o!==-1&&(t=t.slice(0,o)),t+=(t.indexOf("?")===-1?"?":"&")+s}return t}class go{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){m.forEach(this.handlers,function(n){n!==null&&e(n)})}}const Cn=go,Un={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},yo=typeof URLSearchParams<"u"?URLSearchParams:hr,wo=FormData,Eo=(()=>{let t;return typeof navigator<"u"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window<"u"&&typeof document<"u"})(),oe={isBrowser:!0,classes:{URLSearchParams:yo,FormData:wo,Blob},isStandardBrowserEnv:Eo,protocols:["http","https","file","blob","url","data"]};function So(t,e){return Rt(t,new oe.classes.URLSearchParams,Object.assign({visitor:function(r,n,i,s){return oe.isNode&&m.isBuffer(r)?(this.append(n,r.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)}},e))}function To(t){return m.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function bo(t){const e={},r=Object.keys(t);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],e[s]=t[s];return e}function _n(t){function e(r,n,i,s){let o=r[s++];const a=Number.isFinite(+o),u=s>=r.length;return o=!o&&m.isArray(i)?i.length:o,u?(m.hasOwnProp(i,o)?i[o]=[i[o],n]:i[o]=n,!a):((!i[o]||!m.isObject(i[o]))&&(i[o]=[]),e(r,n,i[o],s)&&m.isArray(i[o])&&(i[o]=bo(i[o])),!a)}if(m.isFormData(t)&&m.isFunction(t.entries)){const r={};return m.forEachEntry(t,(n,i)=>{e(To(n),i,r,0)}),r}return null}const Ao={"Content-Type":void 0};function Oo(t,e,r){if(m.isString(t))try{return(e||JSON.parse)(t),m.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}const kt={transitional:Un,adapter:["xhr","http"],transformRequest:[function(e,r){const n=r.getContentType()||"",i=n.indexOf("application/json")>-1,s=m.isObject(e);if(s&&m.isHTMLForm(e)&&(e=new FormData(e)),m.isFormData(e))return i&&i?JSON.stringify(_n(e)):e;if(m.isArrayBuffer(e)||m.isBuffer(e)||m.isStream(e)||m.isFile(e)||m.isBlob(e))return e;if(m.isArrayBufferView(e))return e.buffer;if(m.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(n.indexOf("application/x-www-form-urlencoded")>-1)return So(e,this.formSerializer).toString();if((a=m.isFileList(e))||n.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Rt(a?{"files[]":e}:e,u&&new u,this.formSerializer)}}return s||i?(r.setContentType("application/json",!1),Oo(e)):e}],transformResponse:[function(e){const r=this.transitional||kt.transitional,n=r&&r.forcedJSONParsing,i=this.responseType==="json";if(e&&m.isString(e)&&(n&&!this.responseType||i)){const o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?N.from(a,N.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:oe.classes.FormData,Blob:oe.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};m.forEach(["delete","get","head"],function(e){kt.headers[e]={}}),m.forEach(["post","put","patch"],function(e){kt.headers[e]=m.merge(Ao)});const pr=kt,Ro=m.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ko=t=>{const e={};let r,n,i;return t&&t.split(`
|
|
20
|
-
|
|
21
|
-
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){const n=new this(e);return r.forEach(i=>n.set(i)),n}static accessor(e){const n=(this[Dn]=this[Dn]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=Je(o);n[a]||(Po(i,o),n[a]=!0)}return m.isArray(e)?e.forEach(s):s(e),this}}It.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),m.freezeMethods(It.prototype),m.freezeMethods(It);const ae=It;function vr(t,e){const r=this||pr,n=e||r,i=ae.from(n.headers);let s=n.data;return m.forEach(t,function(a){s=a.call(r,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function Mn(t){return!!(t&&t.__CANCEL__)}function We(t,e,r){N.call(this,t??"canceled",N.ERR_CANCELED,e,r),this.name="CanceledError"}m.inherits(We,N,{__CANCEL__:!0});const Co=null;function Uo(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new N("Request failed with status code "+r.status,[N.ERR_BAD_REQUEST,N.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}const _o=oe.isStandardBrowserEnv?function(){return{write:function(r,n,i,s,o,a){const u=[];u.push(r+"="+encodeURIComponent(n)),m.isNumber(i)&&u.push("expires="+new Date(i).toGMTString()),m.isString(s)&&u.push("path="+s),m.isString(o)&&u.push("domain="+o),a===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(r){const n=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(r){this.write(r,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}();function Do(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Lo(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}function jn(t,e){return t&&!Do(e)?Lo(t,e):e}const Mo=oe.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");let n;function i(s){let o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(o){const a=m.isString(o)?i(o):o;return a.protocol===n.protocol&&a.host===n.host}}():function(){return function(){return!0}}();function jo(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function Fo(t,e){t=t||10;const r=new Array(t),n=new Array(t);let i=0,s=0,o;return e=e!==void 0?e:1e3,function(u){const c=Date.now(),l=n[s];o||(o=c),r[i]=u,n[i]=c;let v=s,h=0;for(;v!==i;)h+=r[v++],v=v%t;if(i=(i+1)%t,i===s&&(s=(s+1)%t),c-o<e)return;const f=l&&c-l;return f?Math.round(h*1e3/f):void 0}}function Fn(t,e){let r=0;const n=Fo(50,250);return i=>{const s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,u=n(a),c=s<=o;r=s;const l={loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:u||void 0,estimated:u&&o&&c?(o-s)/u:void 0,event:i};l[e?"download":"upload"]=!0,t(l)}}const Nt={http:Co,xhr:typeof XMLHttpRequest<"u"&&function(t){return new Promise(function(r,n){let i=t.data;const s=ae.from(t.headers).normalize(),o=t.responseType;let a;function u(){t.cancelToken&&t.cancelToken.unsubscribe(a),t.signal&&t.signal.removeEventListener("abort",a)}m.isFormData(i)&&oe.isStandardBrowserEnv&&s.setContentType(!1);let c=new XMLHttpRequest;if(t.auth){const f=t.auth.username||"",d=t.auth.password?unescape(encodeURIComponent(t.auth.password)):"";s.set("Authorization","Basic "+btoa(f+":"+d))}const l=jn(t.baseURL,t.url);c.open(t.method.toUpperCase(),Pn(l,t.params,t.paramsSerializer),!0),c.timeout=t.timeout;function v(){if(!c)return;const f=ae.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),p={data:!o||o==="text"||o==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:f,config:t,request:c};Uo(function(E){r(E),u()},function(E){n(E),u()},p),c=null}if("onloadend"in c?c.onloadend=v:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(v)},c.onabort=function(){c&&(n(new N("Request aborted",N.ECONNABORTED,t,c)),c=null)},c.onerror=function(){n(new N("Network Error",N.ERR_NETWORK,t,c)),c=null},c.ontimeout=function(){let d=t.timeout?"timeout of "+t.timeout+"ms exceeded":"timeout exceeded";const p=t.transitional||Un;t.timeoutErrorMessage&&(d=t.timeoutErrorMessage),n(new N(d,p.clarifyTimeoutError?N.ETIMEDOUT:N.ECONNABORTED,t,c)),c=null},oe.isStandardBrowserEnv){const f=(t.withCredentials||Mo(l))&&t.xsrfCookieName&&_o.read(t.xsrfCookieName);f&&s.set(t.xsrfHeaderName,f)}i===void 0&&s.setContentType(null),"setRequestHeader"in c&&m.forEach(s.toJSON(),function(d,p){c.setRequestHeader(p,d)}),m.isUndefined(t.withCredentials)||(c.withCredentials=!!t.withCredentials),o&&o!=="json"&&(c.responseType=t.responseType),typeof t.onDownloadProgress=="function"&&c.addEventListener("progress",Fn(t.onDownloadProgress,!0)),typeof t.onUploadProgress=="function"&&c.upload&&c.upload.addEventListener("progress",Fn(t.onUploadProgress)),(t.cancelToken||t.signal)&&(a=f=>{c&&(n(!f||f.type?new We(null,t,c):f),c.abort(),c=null)},t.cancelToken&&t.cancelToken.subscribe(a),t.signal&&(t.signal.aborted?a():t.signal.addEventListener("abort",a)));const h=jo(l);if(h&&oe.protocols.indexOf(h)===-1){n(new N("Unsupported protocol "+h+":",N.ERR_BAD_REQUEST,t));return}c.send(i||null)})}};m.forEach(Nt,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const $o={getAdapter:t=>{t=m.isArray(t)?t:[t];const{length:e}=t;let r,n;for(let i=0;i<e&&(r=t[i],!(n=m.isString(r)?Nt[r.toLowerCase()]:r));i++);if(!n)throw n===!1?new N(`Adapter ${r} is not supported by the environment`,"ERR_NOT_SUPPORT"):new Error(m.hasOwnProp(Nt,r)?`Adapter '${r}' is not available in the build`:`Unknown adapter '${r}'`);if(!m.isFunction(n))throw new TypeError("adapter is not a function");return n},adapters:Nt};function mr(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new We}function $n(t){return mr(t),t.headers=ae.from(t.headers),t.data=vr.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),$o.getAdapter(t.adapter||pr.adapter)(t).then(function(n){return mr(t),n.data=vr.call(t,t.transformResponse,n),n.headers=ae.from(n.headers),n},function(n){return Mn(n)||(mr(t),n&&n.response&&(n.response.data=vr.call(t,t.transformResponse,n.response),n.response.headers=ae.from(n.response.headers))),Promise.reject(n)})}const Bn=t=>t instanceof ae?t.toJSON():t;function Ye(t,e){e=e||{};const r={};function n(c,l,v){return m.isPlainObject(c)&&m.isPlainObject(l)?m.merge.call({caseless:v},c,l):m.isPlainObject(l)?m.merge({},l):m.isArray(l)?l.slice():l}function i(c,l,v){if(m.isUndefined(l)){if(!m.isUndefined(c))return n(void 0,c,v)}else return n(c,l,v)}function s(c,l){if(!m.isUndefined(l))return n(void 0,l)}function o(c,l){if(m.isUndefined(l)){if(!m.isUndefined(c))return n(void 0,c)}else return n(void 0,l)}function a(c,l,v){if(v in e)return n(c,l);if(v in t)return n(void 0,c)}const u={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(c,l)=>i(Bn(c),Bn(l),!0)};return m.forEach(Object.keys(t).concat(Object.keys(e)),function(l){const v=u[l]||i,h=v(t[l],e[l],l);m.isUndefined(h)&&v!==a||(r[l]=h)}),r}const qn="1.2.0",gr={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{gr[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const Vn={};gr.transitional=function(e,r,n){function i(s,o){return"[Axios v"+qn+"] Transitional option '"+s+"'"+o+(n?". "+n:"")}return(s,o,a)=>{if(e===!1)throw new N(i(o," has been removed"+(r?" in "+r:"")),N.ERR_DEPRECATED);return r&&!Vn[o]&&(Vn[o]=!0,console.warn(i(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(s,o,a):!0}};function Bo(t,e,r){if(typeof t!="object")throw new N("options must be an object",N.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let i=n.length;for(;i-- >0;){const s=n[i],o=e[s];if(o){const a=t[s],u=a===void 0||o(a,s,t);if(u!==!0)throw new N("option "+s+" must be "+u,N.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new N("Unknown option "+s,N.ERR_BAD_OPTION)}}const yr={assertOptions:Bo,validators:gr},pe=yr.validators;class Pt{constructor(e){this.defaults=e,this.interceptors={request:new Cn,response:new Cn}}request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Ye(this.defaults,r);const{transitional:n,paramsSerializer:i,headers:s}=r;n!==void 0&&yr.assertOptions(n,{silentJSONParsing:pe.transitional(pe.boolean),forcedJSONParsing:pe.transitional(pe.boolean),clarifyTimeoutError:pe.transitional(pe.boolean)},!1),i!==void 0&&yr.assertOptions(i,{encode:pe.function,serialize:pe.function},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o;o=s&&m.merge(s.common,s[r.method]),o&&m.forEach(["delete","get","head","post","put","patch","common"],d=>{delete s[d]}),r.headers=ae.concat(o,s);const a=[];let u=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(r)===!1||(u=u&&p.synchronous,a.unshift(p.fulfilled,p.rejected))});const c=[];this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let l,v=0,h;if(!u){const d=[$n.bind(this),void 0];for(d.unshift.apply(d,a),d.push.apply(d,c),h=d.length,l=Promise.resolve(r);v<h;)l=l.then(d[v++],d[v++]);return l}h=a.length;let f=r;for(v=0;v<h;){const d=a[v++],p=a[v++];try{f=d(f)}catch(g){p.call(this,g);break}}try{l=$n.call(this,f)}catch(d){return Promise.reject(d)}for(v=0,h=c.length;v<h;)l=l.then(c[v++],c[v++]);return l}getUri(e){e=Ye(this.defaults,e);const r=jn(e.baseURL,e.url);return Pn(r,e.params,e.paramsSerializer)}}m.forEach(["delete","get","head","options"],function(e){Pt.prototype[e]=function(r,n){return this.request(Ye(n||{},{method:e,url:r,data:(n||{}).data}))}}),m.forEach(["post","put","patch"],function(e){function r(n){return function(s,o,a){return this.request(Ye(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Pt.prototype[e]=r(),Pt.prototype[e+"Form"]=r(!0)});const Ct=Pt;class wr{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(s){r=s});const n=this;this.promise.then(i=>{if(!n._listeners)return;let s=n._listeners.length;for(;s-- >0;)n._listeners[s](i);n._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{n.subscribe(a),s=a}).then(i);return o.cancel=function(){n.unsubscribe(s)},o},e(function(s,o,a){n.reason||(n.reason=new We(s,o,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}static source(){let e;return{token:new wr(function(i){e=i}),cancel:e}}}const qo=wr;function Vo(t){return function(r){return t.apply(null,r)}}function zo(t){return m.isObject(t)&&t.isAxiosError===!0}function zn(t){const e=new Ct(t),r=vn(Ct.prototype.request,e);return m.extend(r,Ct.prototype,e,{allOwnKeys:!0}),m.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return zn(Ye(t,i))},r}const H=zn(pr);H.Axios=Ct,H.CanceledError=We,H.CancelToken=qo,H.isCancel=Mn,H.VERSION=qn,H.toFormData=Rt,H.AxiosError=N,H.Cancel=H.CanceledError,H.all=function(e){return Promise.all(e)},H.spread=Vo,H.isAxiosError=zo,H.AxiosHeaders=ae,H.formToJSON=t=>_n(m.isHTMLForm(t)?new FormData(t):t),H.default=H;const Qe=H,Xe="nhostRefreshToken",Ze="nhostRefreshTokenExpiresAt",Hn=3,Kn=300,Er=5,Sr=0,Tr=1,Y=10,Ce=20;let et=class extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Tr,message:e.message}):(this.name=e.error,this.error=e)}};const ce={status:Y,error:"invalid-email",message:"Email is incorrectly formatted"},Gn={status:Y,error:"invalid-mfa-type",message:"MFA type is invalid"},Jn={status:Y,error:"invalid-mfa-code",message:"MFA code is invalid"},Ut={status:Y,error:"invalid-password",message:"Password is incorrectly formatted"},br={status:Y,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Wn={status:Y,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Yn={status:Y,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Qn={status:Y,error:"no-refresh-token",message:"No refresh token has been provided"},Xn={status:Ce,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},re={status:Ce,error:"already-signed-in",message:"User is already signed in"},Zn={status:Ce,error:"unauthenticated-user",message:"User is not authenticated"},Ho={status:Ce,error:"user-not-anonymous",message:"User is not anonymous"},ei={status:Ce,error:"unverified-user",message:"Email needs verification"},ti={status:Y,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},ri={status:Tr,error:"invalid-sign-in-method",message:"Invalid sign-in method"},_t={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function Ko(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 Ar(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 a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return s}function ni(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function ii(t){const{id:e}=t;return{...t,id:Ar(e),transports:t.transports}}function si(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let K=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function Go({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 K("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 K("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 K("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new K("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new K("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 K('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new K("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(si(s)){if(i.rp.id!==s)return new K(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new K(`${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 K("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new K("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Jo{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const Dt=new Jo;async function oi(t){if(!ni())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Ar(t.challenge),user:{...t.user,id:Ko(t.user.id)},excludeCredentials:t.excludeCredentials.map(ii)}};e.signal=Dt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(u){throw Go({error:u,options:e})}finally{Dt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,a={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"&&(a.transports=s.getTransports()),a}function Wo(t){return new TextDecoder("utf-8").decode(t)}async function Yo(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function Qo({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 K("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new K("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new K("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(si(i)){if(n.rpId!==i)return new K(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new K(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new K("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Xo(t,e=!1){var r,n;if(!ni())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(ii));const s={...t,challenge:Ar(t.challenge),allowCredentials:i},o={};if(e){if(!await Yo())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=Dt.createNewAbortSignal();let a;try{a=await navigator.credentials.get(o)}catch(f){throw Qo({error:f,options:o})}finally{Dt.reset()}if(!a)throw new Error("Authentication was not completed");const{id:u,rawId:c,response:l,type:v}=a;let h;return l.userHandle&&(h=Wo(l.userHandle)),{id:u,rawId:Se(c),response:{authenticatorData:Se(l.authenticatorData),clientDataJSON:Se(l.clientDataJSON),signature:Se(l.signature),userHandle:h},type:v,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:a.authenticatorAttachment}}const Lt=typeof window<"u",Mt=new Map,Zo=t=>Lt&&typeof localStorage<"u"?localStorage.getItem(t):Mt.get(t)??null,ea=(t,e)=>{Lt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?Mt.set(t,e):Mt.has(t)&&Mt.delete(t)},ai=(t,e)=>{if(t==="localStorage"||t==="web")return Zo;if(t==="cookie")return r=>Lt?ar.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},ci=(t,e)=>{if(t==="localStorage"||t==="web")return ea;if(t==="cookie")return(r,n)=>{Lt&&(n?ar.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):ar.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}`)},ve=t=>{const e=Qe.create({baseURL:t});return e.interceptors.response.use(r=>r,r=>{var n,i,s,o,a,u,c;return Promise.reject({error:{message:((i=(n=r.response)==null?void 0:n.data)==null?void 0:i.message)??r.message??r.request.responseText??JSON.stringify(r),status:((s=r.response)==null?void 0:s.status)??((a=(o=r.response)==null?void 0:o.data)==null?void 0:a.statusCode)??Sr,error:((c=(u=r.response)==null?void 0:u.data)==null?void 0:c.error)||r.request.statusText||"network"}})}),e},tt=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},me=({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},jt=()=>typeof window<"u",Or=(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},Q=(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),a=new URLSearchParams(o.search);let u=Object.fromEntries(a);r.startsWith("/")&&(u={...s,...u});let c=i.pathname;return o.pathname.length>1&&(c+=o.pathname.slice(1)),{...n,redirectTo:Or(o.origin+c,u)}};function rt(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Rr(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const ue=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,}))$/),Ft=t=>!!t&&typeof t=="string"&&t.length>=Hn,kr=t=>!!t&&typeof t=="string",ui=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),li=({backendUrl:t,clientUrl:e,clientStorageGetter:r,clientStorageSetter:n,clientStorageType:i="web",clientStorage:s,refreshIntervalTime:o,autoRefreshToken:a=!0,autoSignIn:u=!0})=>{const c=r||ai(i,s),l=n||ci(i,s),v=ve(t),h=async(f,d,p)=>(await v.post(f,d,p)).data;return he({schema:{context:{},events:{},services:{}},tsTypes:{},context:_t,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:V("SIGNED_IN"),reportSignedOut:V("SIGNED_OUT"),reportTokenChanged:V("TOKEN_CHANGED"),incrementTokenImportAttempts:A({importTokenAttempts:({importTokenAttempts:f})=>f+1}),clearContext:A(()=>(l(Ze,null),l(Xe,null),{..._t})),clearContextExceptRefreshToken:A(({refreshToken:{value:f}})=>(l(Ze,null),{..._t,refreshToken:{value:f}})),saveSession:A({user:(f,{data:d})=>{var p;return((p=d==null?void 0:d.session)==null?void 0:p.user)||null},accessToken:(f,{data:d})=>{if(d.session){const{accessTokenExpiresIn:p,accessToken:g}=d.session,E=new Date(Date.now()+p*1e3);return l(Ze,E.toISOString()),{value:g,expiresAt:E}}return l(Ze,null),{value:null,expiresAt:null}},refreshToken:(f,{data:d})=>{var p;const g=((p=d.session)==null?void 0:p.refreshToken)||null;return g&&l(Xe,g),{value:g}}}),saveMfaTicket:A({mfa:(f,d)=>{var p;return(p=d.data)==null?void 0:p.mfa}}),resetTimer:A({refreshTimer:f=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:A({refreshTimer:(f,d)=>({startedAt:f.refreshTimer.startedAt,attempts:f.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:A({errors:({errors:f},{data:{error:d}})=>({...f,authentication:d})}),resetErrors:A({errors:f=>({}),importTokenAttempts:f=>0}),saveRegistrationError:A({errors:({errors:f},{data:{error:d}})=>({...f,registration:d})}),destroyRefreshToken:A({refreshToken:f=>(l(Xe,null),{value:null})}),cleanUrl:()=>{u&&rt("refreshToken")&&(Rr("refreshToken"),Rr("type"))},broadcastToken:f=>{if(u)try{new BroadcastChannel("nhost").postMessage(f.refreshToken.value)}catch{}}},guards:{isAnonymous:(f,d)=>{var p;return!!((p=f.user)!=null&&p.isAnonymous)},isSignedIn:f=>!!f.user&&!!f.refreshToken.value&&!!f.accessToken.value,noToken:f=>!f.refreshToken.value,hasRefreshToken:f=>!!f.refreshToken.value,isAutoRefreshDisabled:()=>!a,refreshTimerShouldRefresh:f=>{const{expiresAt:d}=f.accessToken;return d?f.refreshTimer.lastAttempt?f.refreshTimer.attempts>Er?!1:Date.now()-f.refreshTimer.lastAttempt.getTime()>Math.pow(2,f.refreshTimer.attempts-1)*5e3:o&&Date.now()-f.refreshTimer.startedAt.getTime()>o*1e3?!0:d.getTime()-Date.now()-1e3*Kn<=0:!1},shouldRetryImportToken:(f,d)=>f.importTokenAttempts<Er&&(d.data.error.status===Sr||d.data.error.status>=500),unverified:(f,{data:{error:d}})=>d.status===401&&(d.message==="Email is not verified"||d.error==="unverified-user"),hasSession:(f,d)=>{var p;return!!((p=d.data)!=null&&p.session)},hasMfaTicket:(f,d)=>{var p;return!!((p=d.data)!=null&&p.mfa)}},services:{signInPassword:(f,{email:d,password:p})=>ue(d)?Ft(p)?h("/signin/email-password",{email:d,password:p}):Promise.reject({error:Ut}):Promise.reject({error:ce}),passwordlessSms:(f,{phoneNumber:d,options:p})=>{var g;return kr(d)?(g=f.user)!=null&&g.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:d,options:Q(e,p)},{headers:{authorization:`Bearer ${f.accessToken.value}`}})):h("/signin/passwordless/sms",{phoneNumber:d,options:Q(e,p)}):Promise.reject({error:br})},passwordlessSmsOtp:(f,{phoneNumber:d,otp:p})=>kr(d)?h("/signin/passwordless/sms/otp",{phoneNumber:d,otp:p}):Promise.reject({error:br}),passwordlessEmail:(f,{email:d,options:p})=>{var g;return ue(d)?(g=f.user)!=null&&g.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:d,options:Q(e,p)},{headers:{authorization:`Bearer ${f.accessToken.value}`}}):h("/signin/passwordless/email",{email:d,options:Q(e,p)}):Promise.reject({error:ce})},signInAnonymous:f=>h("/signin/anonymous"),signInMfaTotp:(f,d)=>{var p;const g=d.ticket||((p=f.mfa)==null?void 0:p.ticket);return g?ui(g)?h("/signin/mfa/totp",{ticket:g,otp:d.otp}):Promise.reject({error:Wn}):Promise.reject({error:Yn})},signInSecurityKeyEmail:async(f,{email:d})=>{if(!ue(d))throw new et(ce);const p=await h("/signin/webauthn",{email:d});let g;try{g=await Xo(p)}catch(E){throw new et(E)}return h("/signin/webauthn/verify",{email:d,credential:g})},refreshToken:async(f,d)=>{const p=d.type==="TRY_TOKEN"?d.token:f.refreshToken.value;return{session:await h("/token",{refreshToken:p}),error:null}},signout:(f,d)=>h("/signout",{refreshToken:f.refreshToken.value,all:!!d.all}),signUpEmailPassword:async(f,{email:d,password:p,options:g})=>{var E;return ue(d)?Ft(p)?(E=f.user)!=null&&E.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:d,password:p,options:Q(e,g)},{headers:{authorization:`Bearer ${f.accessToken.value}`}}):h("/signup/email-password",{email:d,password:p,options:Q(e,g)}):Promise.reject({error:Ut}):Promise.reject({error:ce})},signUpSecurityKey:async(f,{email:d,options:p})=>{if(!ue(d))return Promise.reject({error:ce});const g=p==null?void 0:p.nickname;g&&delete p.nickname;const E=await h("/signup/webauthn",{email:d,options:p});let S;try{S=await oi(E)}catch(T){throw new et(T)}return h("/signup/webauthn/verify",{credential:S,options:{redirectTo:p==null?void 0:p.redirectTo,nickname:g}})},importRefreshToken:async f=>{if(f.user&&f.refreshToken.value&&f.accessToken.value&&f.accessToken.expiresAt)return{session:{accessToken:f.accessToken.value,accessTokenExpiresIn:f.accessToken.expiresAt.getTime()-Date.now(),refreshToken:f.refreshToken.value,user:f.user},error:null};let d=null;if(u){const g=rt("refreshToken")||null;if(g)try{return{session:await h("/token",{refreshToken:g}),error:null}}catch(E){d=E.error}else{const E=rt("error");if(E)return Promise.reject({session:null,error:{status:Y,error:E,message:rt("errorDescription")||E}})}}const p=await c(Xe);if(p)try{return{session:await h("/token",{refreshToken:p}),error:null}}catch(g){d=g.error}return d?Promise.reject({error:d,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:f})=>Math.pow(2,f-1)*5e3}})},di=({backendUrl:t,clientUrl:e,interpreter:r})=>{const n=ve(t);return he({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:A({error:i=>ce}),saveRequestError:A({error:(i,{data:{error:s}})=>s}),reportError:V(i=>({type:"ERROR",error:i.error})),reportSuccess:V("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!ue(s)},services:{requestChange:async(i,{email:s,options:o})=>(await n.post("/user/email/change",{newEmail:s,options:Q(e,o)},{headers:{authorization:`Bearer ${r==null?void 0:r.getSnapshot().context.accessToken.value}`}})).data}})},fi=({backendUrl:t,interpreter:e})=>{const r=ve(t);return he({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:A({error:n=>Ut}),saveRequestError:A({error:(n,{data:{error:i}})=>i}),reportError:V(n=>({type:"ERROR",error:n.error})),reportSuccess:V("SUCCESS")},guards:{invalidPassword:(n,{password:i})=>!Ft(i)},services:{requestChange:(n,{password:i,ticket:s})=>r.post("/user/password",{newPassword:i,ticket:s},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}})}})},ta=({backendUrl:t,interpreter:e})=>{const r=ve(t);return he({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:A({error:n=>Gn}),saveInvalidMfaCodeError:A({error:n=>Jn}),saveError:A({error:(n,{data:{error:i}})=>i}),saveGeneration:A({imageUrl:(n,{data:{imageUrl:i}})=>i,secret:(n,{data:{totpSecret:i}})=>i}),reportError:V(n=>({type:"ERROR",error:n.error})),reportSuccess:V("SUCCESS"),reportGeneratedSuccess:V("GENERATED"),reportGeneratedError:V(n=>({type:"GENERATED_ERROR",error:n.error}))},guards:{invalidMfaCode:(n,{code:i})=>!i,invalidMfaType:(n,{activeMfaType:i})=>!i||i!=="totp"},services:{generate:async n=>{const{data:i}=await r.get("/mfa/totp/generate",{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});return i},activate:(n,{code:i,activeMfaType:s})=>r.post("/user/mfa",{code:i,activeMfaType:s},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}})}})},hi=({backendUrl:t,clientUrl:e})=>{const r=ve(t);return he({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:A({error:n=>ce}),saveRequestError:A({error:(n,{data:{error:i}})=>i}),reportError:V(n=>({type:"ERROR",error:n.error})),reportSuccess:V("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ue(i)},services:{requestChange:(n,{email:i,options:s})=>r.post("/user/password/reset",{email:i,options:Q(e,s)})}})},pi=({backendUrl:t,clientUrl:e})=>{const r=ve(t);return he({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:A({error:n=>ce}),saveRequestError:A({error:(n,{data:{error:i}})=>i}),reportError:V(n=>({type:"ERROR",error:n.error})),reportSuccess:V("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ue(i)},services:{request:async(n,{email:i,options:s})=>(await r.post("/user/email/send-verification-email",{email:i,options:Q(e,s)})).data}})};class xr{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:a,...u}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=li({...u,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:a}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",c=>{var l;const v=(l=this.interpreter)==null?void 0:l.getSnapshot().context.refreshToken.value;this.interpreter&&c.data!==v&&this.interpreter.send("TRY_TOKEN",{token:c.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const s=this.machine.withContext(i);this._interpreter||(this._interpreter=n||ke(s,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(o=>o())),this._interpreter.start(s.initialState),this._subscriptionsQueue.forEach(o=>o(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 vi extends xr{constructor({...e}){super({...e,autoSignIn:jt()&&e.autoSignIn,autoRefreshToken:jt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const ra=vi,mi=async({backendUrl:t,interpreter:e},r)=>{const n=ve(t);try{const{data:i}=await n.post("/user/webauthn/add",{},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});let s;try{s=await oi(i)}catch(a){throw new et(a)}const{data:o}=await n.post("/user/webauthn/verify",{credential:s,nickname:r},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});return{key:o,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1}}},gi=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})})}),yi=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})})}),na=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:""})})}),ia=(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})})}),wi=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})})}),Ei=(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})})}),Si=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:re,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})})}),Ti=(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:re,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:re,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})})}),bi=(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:re,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})})}),Ai=(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:re,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})})}),Nr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:re,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})})}),Oi=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:re,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})})}),Ri=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:Zn});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})})}),Pr=(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:re,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(a=>{a.matches("registration.incomplete.failed")?i({accessToken:null,error:a.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):a.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):a.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:a.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:a.context.user})})}),ki=(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:re,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})});class xi{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,autoLogin:i,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:c,start:l=!0}){var v;this.url=e,this._client=new xr({backendUrl:e,clientUrl:typeof window<"u"&&((v=window.location)==null?void 0:v.origin)||"",autoRefreshToken:r,autoSignIn:typeof i=="boolean"?i:n,start:l,clientStorage:s,clientStorageType:o,clientStorageGetter:a,clientStorageSetter:u,refreshIntervalTime:c})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?me(await ki(r,n,i)):me(await Pr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Si(r);return{...me(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=Or(`${this._client.backendUrl}/signin/provider/${n}`,Q(this._client.clientUrl,i));return jt()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Ti(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:ei}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...me(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await bi(r,e.email);return{...me(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 Oi(r,e.phoneNumber,e.otp);return{...me(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Nr(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Ai(r,e.otp,e.ticket);return{...me(n),mfa:null}}return{error:ri,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await Ri(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=ke(hi(this._client)).start(),{error:i}=await wi(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=ke(fi(this._client)).start(),{error:i}=await yi(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=ke(pi(this._client)).start(),{error:i}=await Ei(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=ke(di(this._client)).start(),{error:i}=await gi(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 Nr(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await Pr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await mi(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(tt(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,tt(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}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Vi(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:Qn});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:Xn});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:ti}):o.event.type==="TOKEN_CHANGED"&&n({session:tt(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return tt((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}}const Ii=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t},Cr=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}};class Ni{constructor({url:e}){this.url=e,this.httpClient=Qe.create({baseURL:this.url})}async upload(e){const{formData:r}=e;try{return{fileMetadata:(await this.httpClient.post("/files",r,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders(),"Content-Type":"multipart/form-data"}})).data,error:null}}catch(n){return{fileMetadata:null,error:n}}}async getPresignedUrl(e){try{const{fileId:r}=e,n=`/files/${r}/presignedurl`;return{presignedUrl:(await this.httpClient.get(n,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){const{bucketId:r,name:n,id:i}=e,s={};return r&&(s["x-nhost-bucket-id"]=r),i&&(s["x-nhost-file-id"]=i),n&&(s["x-nhost-file-name"]=Cr(n)),s}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class Pi{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Ni({url:e}),this.setAdminSecret(r)}async upload(e){let r;"file"in e?(r=new Rn,r.append("file",e.file)):r=e.formData;const{fileMetadata:n,error:i}=await this.api.upload({...e,formData:r});return i?{fileMetadata:null,error:i}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){const{fileId:r,...n}=e;return Ii(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const $t={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Ci=()=>he({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...$t},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:A({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:A({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:A({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:A({progress:t=>null,loaded:t=>0}),resetContext:A(t=>$t),addFile:A({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n={"Content-Type":"multipart/form-data"},i=e.id||t.id;i&&(n["x-nhost-file-id"]=i);const s=e.bucketId||t.bucketId;s&&(n["x-nhost-bucket-id"]=s);const o=e.file||t.file;n["x-nhost-file-name"]=Cr(e.name||o.name);const a=new FormData;a.append("file",o),e.adminSecret&&(n["x-hasura-admin-secret"]=e.adminSecret),e.accessToken&&(n.Authorization=`Bearer ${e.accessToken}`);let u=0;const c=new AbortController;return Qe.post(e.url+"/files",a,{headers:n,signal:c.signal,onUploadProgress:l=>{const v=l.total?Math.round(l.loaded*o.size/l.total):0,h=v-u;u=v,r({type:"UPLOAD_PROGRESS",progress:l.total?Math.round(v*100/l.total):0,loaded:v,additions:h})}}).then(({data:{id:l,bucketId:v}})=>{r({type:"UPLOAD_DONE",id:l,bucketId:v})}).catch(({response:l,message:v})=>{var h,f,d,p;r({type:"UPLOAD_ERROR",error:{status:(l==null?void 0:l.status)??0,message:((f=(h=l==null?void 0:l.data)==null?void 0:h.error)==null?void 0:f.message)||v,error:((p=(d=l==null?void 0:l.data)==null?void 0:d.error)==null?void 0:p.message)||v}})}),()=>{c.abort()}}}}),{pure:Ur,sendParent:Bt}=ys,sa=()=>he({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:A((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:A({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:A({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:A({loaded:t=>0}),startProgress:A({progress:t=>0}),resetProgress:A({progress:t=>null}),addItem:A((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,a)=>o+a.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Ls(Ci().withConfig({actions:{sendProgress:Bt((a,{additions:u})=>({type:"UPLOAD_PROGRESS",additions:u})),sendDone:Bt("UPLOAD_DONE"),sendError:Bt("UPLOAD_ERROR"),sendDestroy:Bt("REMOVE")}}).withContext({...$t,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:A({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=>V({type:"DESTROY"},{to:e.id}))),upload:Ur((t,e)=>t.files.map(r=>V(e,{to:r.id}))),cancel:Ur(t=>t.files.map(e=>V({type:"CANCEL"},{to:e.id})))}}),oa=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})})}),aa=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})})}),ca=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function qt(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(ca);if(s!=null&&s.groups){const{protocol:o="http",host:a,port:u=1337}=s.groups,c=da(e);return c||`${o}://${a}:${u}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function ua(){return typeof window<"u"}function la(){return typeof process<"u"&&process.env}function da(t){return ua()||!la()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Ui(t){const e="subdomain"in t||"backendUrl"in t?qt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new xi({url:e,...t})}function _i(t){const e="subdomain"in t||"backendUrl"in t?qt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Di({url:e,...t})}class Di{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=Qe.create({baseURL:r})}async call(e,r,{useAxios:n=!0,...i}={}){n&&console.warn("nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation.");const s={...this.generateAccessTokenHeaders(),...i==null?void 0:i.headers};let o;try{o=await this.instance.post(e,r,{...i,headers:s})}catch(a){if(a instanceof Error){if(n)return{res:null,error:a};const u=a;return{res:null,error:{error:u.code||"unknown",status:u.status||0,message:u.message}}}}return o?n?{res:o,error:null}:{res:{status:o.status,statusText:o.statusText,data:o.data},error:null}:n?{res:null,error:new Error("Unable to make post request to function")}:{res:null,error:{error:"invalid-response",status:0,message:"Unable to make post request to function"}}}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 Li(t){const e="subdomain"in t||"backendUrl"in t?qt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Mi({url:e,...t})}class Mi{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=Qe.create({baseURL:r})}async request(e,r,{useAxios:n=!0,...i}={}){const s={"Accept-Encoding":"*",...this.generateAccessTokenHeaders(),...i==null?void 0:i.headers};try{const o="",u=(await this.instance.post("",{operationName:o||void 0,query:typeof e=="string"?e:Le.print(e),variables:r},{...i,headers:s})).data,{data:c}=u;return u.errors?{data:null,error:u.errors}:typeof c!="object"||Array.isArray(c)||c===null?n?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:null,error:{error:"invalid-response",status:0,message:"incorrect response data from GraphQL server"}}:{data:c,error:null}}catch(o){if(console.error(o),n)return o instanceof Error?{data:null,error:o}:{data:null,error:new Error("Unable to get do GraphQL request")};const a=o;return{data:null,error:{error:a.code||"unknown",status:a.status||0,message:a.message}}}}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 ji(t){const e="subdomain"in t||"backendUrl"in t?qt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pi({url:e,...t})}const fa=t=>new Fi(t);class Fi{constructor({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,adminSecret:u,devTools:c,start:l=!0,...v}){this.auth=Ui({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:i,clientStorageType:s,autoRefreshToken:o,autoSignIn:a,start:l,...v}),this.storage=ji({adminSecret:u,...v}),this.functions=_i({adminSecret:u,...v}),this.graphql=Li({adminSecret:u,...v}),this.auth.onAuthStateChanged((h,f)=>{h==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(h=>{const f=h==null?void 0:h.accessToken;this.storage.setAccessToken(f),this.functions.setAccessToken(f),this.graphql.setAccessToken(f)}),this._adminSecret=u,this.devTools=c}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}w.AuthClient=xr,w.AuthClientSSR=ra,w.AuthCookieClient=vi,w.CodifiedError=et,w.EMAIL_NEEDS_VERIFICATION=ei,w.HasuraAuthClient=xi,w.HasuraStorageApi=Ni,w.HasuraStorageClient=Pi,w.INITIAL_FILE_CONTEXT=$t,w.INITIAL_MACHINE_CONTEXT=_t,w.INVALID_EMAIL_ERROR=ce,w.INVALID_MFA_CODE_ERROR=Jn,w.INVALID_MFA_TICKET_ERROR=Wn,w.INVALID_MFA_TYPE_ERROR=Gn,w.INVALID_PASSWORD_ERROR=Ut,w.INVALID_PHONE_NUMBER_ERROR=br,w.INVALID_REFRESH_TOKEN=ti,w.INVALID_SIGN_IN_METHOD=ri,w.MIN_PASSWORD_LENGTH=Hn,w.NETWORK_ERROR_CODE=Sr,w.NHOST_JWT_EXPIRES_AT_KEY=Ze,w.NHOST_REFRESH_TOKEN_KEY=Xe,w.NO_MFA_TICKET_ERROR=Yn,w.NO_REFRESH_TOKEN=Qn,w.NhostClient=Fi,w.NhostFunctionsClient=Di,w.NhostGraphqlClient=Mi,w.OTHER_ERROR_CODE=Tr,w.REFRESH_TOKEN_MAX_ATTEMPTS=Er,w.STATE_ERROR_CODE=Ce,w.TOKEN_REFRESHER_RUNNING_ERROR=Xn,w.TOKEN_REFRESH_MARGIN=Kn,w.USER_ALREADY_SIGNED_IN=re,w.USER_NOT_ANONYMOUS=Ho,w.USER_UNAUTHENTICATED=Zn,w.VALIDATION_ERROR_CODE=Y,w.activateMfaPromise=ia,w.addSecurityKeyPromise=mi,w.appendImageTransformationParameters=Ii,w.changeEmailPromise=gi,w.changePasswordPromise=yi,w.createAuthClient=Ui,w.createAuthMachine=li,w.createChangeEmailMachine=di,w.createChangePasswordMachine=fi,w.createEnableMfaMachine=ta,w.createFileUploadMachine=Ci,w.createFunctionsClient=_i,w.createGraphqlClient=Li,w.createMultipleFilesUploadMachine=sa,w.createNhostClient=fa,w.createResetPasswordMachine=hi,w.createSendVerificationEmailMachine=pi,w.createStorageClient=ji,w.encodeQueryParameters=Or,w.generateQrCodePromise=na,w.getAuthenticationResult=me,w.getParameterByName=rt,w.getSession=tt,w.isBrowser=jt,w.isValidEmail=ue,w.isValidPassword=Ft,w.isValidPhoneNumber=kr,w.isValidTicket=ui,w.localStorageGetter=ai,w.localStorageSetter=ci,w.nhostApiClient=ve,w.removeParameterFromWindow=Rr,w.resetPasswordPromise=wi,w.rewriteRedirectTo=Q,w.sendVerificationEmailPromise=Ei,w.signInAnonymousPromise=Si,w.signInEmailPasswordPromise=Ti,w.signInEmailPasswordlessPromise=Ir,w.signInEmailSecurityKeyPromise=bi,w.signInMfaTotpPromise=Ai,w.signInSmsPasswordlessOtpPromise=Oi,w.signInSmsPasswordlessPromise=Nr,w.signOutPromise=Ri,w.signUpEmailPasswordPromise=Pr,w.signUpEmailSecurityKeyPromise=ki,w.toIso88591=Cr,w.uploadFilePromise=oa,w.uploadMultipleFilesPromise=aa,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|
|
14
|
+
***************************************************************************** */var w=function(){return w=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},w.apply(this,arguments)};function It(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function j(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function D(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function V(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return t.concat(o||Array.prototype.slice.call(e))}var B;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(B||(B={}));var ie;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(ie||(ie={}));var Qe=B.Start,Ye=B.Stop,me=B.Raise,ge=B.Send,xt=B.Cancel,fr=B.NullEvent,We=B.Assign,Xn=B.After,Zn=B.DoneState,Xe=B.Log,hr=B.Init,Ze=B.Invoke,ei=B.ErrorExecution,Rt=B.ErrorPlatform,Pt=B.ErrorCustom,et=B.Update,pr=B.Choose,vr=B.Pure;const ti=Object.freeze(Object.defineProperty({__proto__:null,after:Xn,assign:We,cancel:xt,choose:pr,doneState:Zn,error:Pt,errorExecution:ei,errorPlatform:Rt,init:hr,invoke:Ze,log:Xe,nullEvent:fr,pure:vr,raise:me,send:ge,start:Qe,stop:Ye,update:et},Symbol.toStringTag,{value:"Module"}));var yr=".",mr={},Ut="xstate.guard",ri="",H=process.env.NODE_ENV==="production",tt;function Nt(t,e,r){r===void 0&&(r=yr);var n=Ne(t,r),i=Ne(e,r);return L(i)?L(n)?i===n:!1:L(n)?n in i:Object.keys(n).every(function(o){return o in i?Nt(n[o],i[o]):!1})}function gr(t){try{return L(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Dt(t,e){try{return be(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function ni(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Ne(t,e){if(ni(t))return t.value;if(be(t))return rt(t);if(typeof t!="string")return t;var r=Dt(t,e);return rt(r)}function rt(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function De(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var o=n[i];r[o]=e(t[o],o,t,i)}return r}function wr(t,e,r){var n,i,o={};try{for(var s=j(Object.keys(t)),u=s.next();!u.done;u=s.next()){var f=u.value,h=t[f];r(h)&&(o[f]=e(h,f,t))}}catch(l){n={error:l}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}var ii=function(t){return function(e){var r,n,i=e;try{for(var o=j(t),s=o.next();!s.done;s=o.next()){var u=s.value;i=i[u]}}catch(f){r={error:f}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}return i}};function oi(t,e){return function(r){var n,i,o=r;try{for(var s=j(t),u=s.next();!u.done;u=s.next()){var f=u.value;o=o[e][f]}}catch(h){n={error:h}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}}function nt(t){if(!t)return[[]];if(L(t))return[[t]];var e=K(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:nt(t[r]).map(function(i){return[r].concat(i)})}));return e}function K(t){var e;return(e=[]).concat.apply(e,V([],D(t),!1))}function Er(t){return be(t)?t:[t]}function te(t){return t===void 0?[]:Er(t)}function it(t,e,r){var n,i;if(q(t))return t(e,r.data);var o={};try{for(var s=j(Object.keys(t)),u=s.next();!u.done;u=s.next()){var f=u.value,h=t[f];q(h)?o[f]=h(e,r.data):o[f]=h}}catch(l){n={error:l}}finally{try{u&&!u.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return o}function si(t){return/^(done|error)\./.test(t)}function Sr(t){return!!(t instanceof Promise||t!==null&&(q(t)||typeof t=="object")&&q(t.then))}function ai(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function ci(t,e){var r,n,i=D([[],[]],2),o=i[0],s=i[1];try{for(var u=j(t),f=u.next();!f.done;f=u.next()){var h=f.value;e(h)?o.push(h):s.push(h)}}catch(l){r={error:l}}finally{try{f&&!f.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[o,s]}function br(t,e){return De(t.states,function(r,n){if(r){var i=(L(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:br(r,i)}}})}function ui(t,e){return{current:e,states:br(t,e)}}function Tr(t,e,r,n){H||J(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(o,s){var u,f,h=s.assignment,l={state:n,action:s,_event:e},c={};if(q(h))c=h(o,e.data,l);else try{for(var d=j(Object.keys(h)),p=d.next();!p.done;p=d.next()){var y=p.value,g=h[y];c[y]=q(g)?g(o,e.data,l):g}}catch(m){u={error:m}}finally{try{p&&!p.done&&(f=d.return)&&f.call(d)}finally{if(u)throw u.error}}return Object.assign({},o,c)},t);return i}var J=function(){};H||(J=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function be(t){return Array.isArray(t)}function q(t){return typeof t=="function"}function L(t){return typeof t=="string"}function Ar(t,e){if(t)return L(t)?{type:Ut,name:t,predicate:e?e[t]:void 0}:q(t)?{type:Ut,name:t.name,predicate:t}:t}function li(t){try{return"subscribe"in t&&q(t.subscribe)}catch{return!1}}var he=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();tt={},tt[he]=function(){return this},tt[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function di(t){return!!t&&typeof t.send=="function"}var fi=function(){var t=0;return function(){return t++,t.toString(16)}}();function Ct(t,e){return L(t)||typeof t=="number"?w({type:t},e):t}function W(t,e){if(!L(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=Ct(t);return w({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function Te(t,e){var r=Er(e).map(function(n){return typeof n>"u"||typeof n=="string"||ae(n)?{target:n,event:t}:w(w({},n),{event:t})});return r}function hi(t){if(!(t===void 0||t===ri))return te(t)}function pi(t,e,r){if(!H){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function Or(t,e,r,n,i){var o=t.options.guards,s={state:i,cond:e,_event:n};if(e.type===Ut)return((o==null?void 0:o[e.name])||e.predicate)(r,n.data,s);var u=o==null?void 0:o[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,s)}function kr(t){return typeof t=="string"?{type:t}:t}function ot(t,e,r){var n=function(){},i=typeof t=="object",o=i?t:null;return{next:((i?t.next:t)||n).bind(o),error:((i?t.error:e)||n).bind(o),complete:((i?t.complete:r)||n).bind(o)}}function st(t,e){return"".concat(t,":invocation[").concat(e,"]")}var we=W({type:hr});function at(t,e){return e&&e[t]||void 0}function Ae(t,e){var r;if(L(t)||typeof t=="number"){var n=at(t,e);q(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(q(t))r={type:t.name||t.toString(),exec:t};else{var n=at(t.type,e);if(q(n))r=w(w({},t),{exec:n});else if(n){var i=n.type||t.type;r=w(w(w({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=be(t)?t:[t];return r.map(function(n){return Ae(n,e)})};function ct(t){var e=Ae(t);return w(w({id:L(t)?t:e.id},e),{type:e.type})}function _r(t){return L(t)?{type:me,event:t}:pe(t,{to:ie.Internal})}function Ir(t){return{type:me,_event:W(t.event)}}function pe(t,e){return{to:e?e.to:void 0,type:ge,event:q(t)?t:Ct(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:q(t)?t.name:gr(t)}}function xr(t,e,r,n){var i={_event:r},o=W(q(t.event)?t.event(e,r.data,i):t.event),s;if(L(t.delay)){var u=n&&n[t.delay];s=q(u)?u(e,r.data,i):u}else s=q(t.delay)?t.delay(e,r.data,i):t.delay;var f=q(t.to)?t.to(e,r.data,i):t.to;return w(w({},t),{to:f,_event:o,event:o.data,delay:s})}function Mt(t,e){return pe(t,w(w({},e),{to:ie.Parent}))}function vi(t,e,r){return pe(e,w(w({},r),{to:t}))}function yi(){return Mt(et)}function mi(t,e){return pe(t,w(w({},e),{to:function(r,n,i){var o=i._event;return o.origin}}))}var gi=function(t,e){return{context:t,event:e}};function wi(t,e){return t===void 0&&(t=gi),{type:Xe,label:e,expr:t}}var Rr=function(t,e,r){return w(w({},t),{value:L(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Pr=function(t){return{type:xt,sendId:t}};function Ur(t){var e=ct(t);return{type:B.Start,activity:e,exec:void 0}}function Nr(t){var e=q(t)?t:ct(t);return{type:B.Stop,activity:e,exec:void 0}}function Dr(t,e,r){var n=q(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,o={type:B.Stop,activity:i};return o}var Cr=function(t){return{type:We,assignment:t}};function Ei(t){return typeof t=="object"&&"type"in t}function Mr(t,e){var r=e?"#".concat(e):"";return"".concat(B.After,"(").concat(t,")").concat(r)}function Ce(t,e){var r="".concat(B.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Me(t,e){var r="".concat(B.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat(B.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Si(t){return{type:B.Pure,get:t}}function bi(t,e){if(!H&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var o=typeof r=="function"?r.apply(void 0,V([],D(n),!1)):r;if(!o)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return o}}return pe(function(n,i){return i},w(w({},e),{to:t}))}function Ti(t,e){return Mt(function(r,n,i){return{type:Pt,data:q(t)?t(r,n,i):t}},w(w({},e),{to:ie.Parent}))}function Ai(t){return{type:B.Choose,conds:t}}var Oi=function(t){var e,r,n=[];try{for(var i=j(t),o=i.next();!o.done;o=i.next())for(var s=o.value,u=0;u<s.length;){if(s[u].type===We){n.push(s[u]),s.splice(u,1);continue}u++}}catch(f){e={error:f}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function je(t,e,r,n,i,o,s){s===void 0&&(s=!1);var u=s?[]:Oi(i),f=u.length?Tr(r,n,u,e):r,h=s?[r]:void 0,l=[];function c(y){var g;switch(y.type){case me:return Ir(y);case ge:var m=xr(y,f,n,t.options.delays);return H||J(!L(y.delay)||typeof m.delay=="number","No delay reference for delay expression '".concat(y.delay,"' was found on machine '").concat(t.id,"'")),o&&m.to!==ie.Internal&&l.push(m),m;case Xe:{var T=Rr(y,f,n);return o==null||o(T,f,n),T}case pr:{var b=y,A=(g=b.conds.find(function(G){var a=Ar(G.cond,t.options.guards);return!a||Or(t,a,f,n,o?void 0:e)}))===null||g===void 0?void 0:g.actions;if(!A)return[];var P=D(je(t,e,f,n,[ce(te(A),t.options.actions)],o,s),2),R=P[0],$=P[1];return f=$,h==null||h.push(f),R}case vr:{var A=y.get(f,n.data);if(!A)return[];var x=D(je(t,e,f,n,[ce(te(A),t.options.actions)],o,s),2),_=x[0],C=x[1];return f=C,h==null||h.push(f),_}case Ye:{var T=Dr(y,f,n);return o==null||o(T,r,n),T}case We:{f=Tr(f,n,[y],o?void 0:e),h==null||h.push(f);break}default:var k=Ae(y,t.options.actions),I=k.exec;if(o)o(k,f,n);else if(I&&h){var F=h.length-1;k=w(w({},k),{exec:function(G){for(var a=[],v=1;v<arguments.length;v++)a[v-1]=arguments[v];I.apply(void 0,V([h[F]],D(a),!1))}})}return k}}function d(y){var g,m,T=[];try{for(var b=j(y),A=b.next();!A.done;A=b.next()){var P=A.value,R=c(P);R&&(T=T.concat(R))}}catch($){g={error:$}}finally{try{A&&!A.done&&(m=b.return)&&m.call(b)}finally{if(g)throw g.error}}return l.forEach(function($){o($,f,n)}),l.length=0,T}var p=K(i.map(d));return[p,f]}const ki=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:ti,after:Mr,assign:Cr,cancel:Pr,choose:Ai,done:Ce,doneInvoke:Me,error:Oe,escalate:Ti,forwardTo:bi,getActionFunction:at,initEvent:we,isActionObject:Ei,log:wi,pure:Si,raise:_r,resolveActions:je,resolveLog:Rr,resolveRaise:Ir,resolveSend:xr,resolveStop:Dr,respond:mi,send:pe,sendParent:Mt,sendTo:vi,sendUpdate:yi,start:Ur,stop:Nr,toActionObject:Ae,toActionObjects:ce,toActivityDefinition:ct},Symbol.toStringTag,{value:"Module"}));var ut=[],ke=function(t,e){ut.push(t);var r=e(t);return ut.pop(),r},_i=function(t){return t(ut[ut.length-1])};function jr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[he]=function(){return this},e}function Ii(t,e,r,n){var i,o=kr(t.src),s=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[o.type],u=t.data?it(t.data,r,n):void 0,f=s?jt(s,t.id,u):jr(t.id);return f.meta=t,f}function jt(t,e,r){var n=jr(e);if(n.deferred=!0,ae(t)){var i=n.state=ke(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function xi(t){try{return typeof t.send=="function"}catch{return!1}}function Ri(t){return xi(t)&&"id"in t}function Pi(t){var e;return w((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[he]=function(){return this},e),t)}var lt=function(t){return t.type==="atomic"||t.type==="final"};function Lr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Le(t){return Lr(t).filter(function(e){return e.type!=="history"})}function $r(t){var e=[t];return lt(t)?e:e.concat(K(Le(t).map($r)))}function $e(t,e){var r,n,i,o,s,u,f,h,l=new Set(t),c=Lt(l),d=new Set(e);try{for(var p=j(d),y=p.next();!y.done;y=p.next())for(var g=y.value,m=g.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(C){r={error:C}}finally{try{y&&!y.done&&(n=p.return)&&n.call(p)}finally{if(r)throw r.error}}var T=Lt(d);try{for(var b=j(d),A=b.next();!A.done;A=b.next()){var g=A.value;if(g.type==="compound"&&(!T.get(g)||!T.get(g).length))c.get(g)?c.get(g).forEach(function(k){return d.add(k)}):g.initialStateNodes.forEach(function(k){return d.add(k)});else if(g.type==="parallel")try{for(var P=(s=void 0,j(Le(g))),R=P.next();!R.done;R=P.next()){var $=R.value;d.has($)||(d.add($),c.get($)?c.get($).forEach(function(k){return d.add(k)}):$.initialStateNodes.forEach(function(k){return d.add(k)}))}}catch(k){s={error:k}}finally{try{R&&!R.done&&(u=P.return)&&u.call(P)}finally{if(s)throw s.error}}}}catch(C){i={error:C}}finally{try{A&&!A.done&&(o=b.return)&&o.call(b)}finally{if(i)throw i.error}}try{for(var x=j(d),_=x.next();!_.done;_=x.next())for(var g=_.value,m=g.parent;m&&!d.has(m);)d.add(m),m=m.parent}catch(C){f={error:C}}finally{try{_&&!_.done&&(h=x.return)&&h.call(x)}finally{if(f)throw f.error}}return d}function Fr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(lt(n))return n.key}else return{}}var i={};return r.forEach(function(o){i[o.key]=Fr(o,e)}),i}function Lt(t){var e,r,n=new Map;try{for(var i=j(t),o=i.next();!o.done;o=i.next()){var s=o.value;n.has(s)||n.set(s,[]),s.parent&&(n.has(s.parent)||n.set(s.parent,[]),n.get(s.parent).push(s))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Ui(t,e){var r=$e([t],e);return Fr(t,Lt(r))}function Fe(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ni(t){return V([],D(new Set(K(V([],D(t.map(function(e){return e.ownEvents})),!1)))),!1)}function dt(t,e){return e.type==="compound"?Le(e).some(function(r){return r.type==="final"&&Fe(t,r)}):e.type==="parallel"?Le(e).every(function(r){return dt(t,r)}):!1}function Di(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Br(t){return new Set(K(t.map(function(e){return e.tags})))}function qr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(L(t)||L(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return qr(t[i],e[i])})}function Ci(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Mi(t,e){var r=t.exec,n=w(w({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=mr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||mr,this.meta=Di(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Ni(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=we;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=we;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),L(e))return[e];var i=Object.keys(e);return i.concat.apply(i,V([],D(i.map(function(o){return n.toStrings(e[o],r).map(function(s){return o+r+s})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=It(e,["configuration","transitions","tags","machine"]);return w(w({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Nt(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;H&&J(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),ji={deferEvents:!1},Vr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=w(w({},ji),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),$t=new Map,Li=0,ft={bookId:function(){return"x:".concat(Li++)},register:function(t,e){return $t.set(t,e),t},get:function(t){return $t.get(t)},free:function(t){$t.delete(t)}};function Ft(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;H||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function $i(){var t=Ft();if(t&&"__xstate__"in t)return t.__xstate__}function Fi(t){if(Ft()){var e=$i();e&&e.register(t)}}function Bi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],o=!1,s=function(){if(!o){for(o=!0;i.length>0;){var h=i.shift();r=t.transition(r,h,f),n.forEach(function(l){return l.next(r)})}o=!1}},u=Pi({id:e.id,send:function(h){i.push(h),s()},getSnapshot:function(){return r},subscribe:function(h,l,c){var d=ot(h,l,c);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),f={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(f):r,u}var Bt={sync:!1,autoForward:!1},Q;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Q||(Q={}));var qi=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=Q.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(l,c){if(be(l))return n.batch(l),n.state;var d=W(Ct(l,c));if(n.status===Q.Stopped)return H||J(!1,'Event "'.concat(d.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
15
|
+
Event: `).concat(JSON.stringify(d.data))),n.state;if(n.status!==Q.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(d.name,'" was sent to uninitialized service "').concat(n.machine.id,`". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.
|
|
16
|
+
Event: `).concat(JSON.stringify(d.data)));return n.scheduler.schedule(function(){n.forward(d);var p=n._nextState(d);n.update(p,d)}),n._state},this.sendTo=function(l,c,d){var p=n.parent&&(c===ie.Parent||n.parent.id===c),y=p?n.parent:L(c)?n.children.get(c)||ft.get(c):di(c)?c:void 0;if(!y){if(!p)throw new Error("Unable to send event to child '".concat(c,"' from service '").concat(n.id,"'."));H||J(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(l.type));return}if("machine"in y){if(n.status!==Q.Stopped||n.parent!==y||n.state.done){var g=w(w({},l),{name:l.name===Pt?"".concat(Oe(n.id)):l.name,origin:n.sessionId});!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([y,g]):y.send(g)}}else!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([y,l.data]):y.send(l.data)},this._exec=function(l,c,d,p){p===void 0&&(p=n.machine.options.actions);var y=l.exec||at(l.type,p),g=q(y)?y:y?y.exec:l.exec;if(g)try{return g(c,d.data,n.machine.config.predictableActionArguments?{action:l,_event:d}:{action:l,state:n.state,_event:d})}catch(F){throw n.parent&&n.parent.send({type:"xstate.error",data:F}),F}switch(l.type){case ge:var m=l;if(typeof m.delay=="number"){n.defer(m);return}else m.to?n.sendTo(m._event,m.to,d===we):n.send(m._event);break;case xt:n.cancel(l.sendId);break;case Qe:{if(n.status!==Q.Running)return;var T=l.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[T.id||T.type])break;if(T.type===B.Invoke){var b=kr(T.src),A=n.machine.options.services?n.machine.options.services[b.type]:void 0,P=T.id,R=T.data;H||J(!("forward"in T),"`forward` property is deprecated (found in invocation of '".concat(T.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var $="autoForward"in T?T.autoForward:!!T.forward;if(!A){H||J(!1,"No service found for invocation '".concat(T.src,"' in machine '").concat(n.machine.id,"'."));return}var x=R?it(R,c,d):void 0;if(typeof A=="string")return;var _=q(A)?A(c,d.data,{data:x,src:b,meta:T.meta}):A;if(!_)return;var C=void 0;ae(_)&&(_=x?_.withContext(x):_,C={autoForward:$}),n.spawn(_,P,C)}else n.spawnActivity(T);break}case Ye:{n.stopChild(l.activity.id);break}case Xe:var k=l.label,I=l.value;k?n.logger(k,I):n.logger(I);break;default:H||J(!1,"No implementation found for action type '".concat(l.type,"'"));break}};var i=w(w({},t.defaultOptions),r),o=i.clock,s=i.logger,u=i.parent,f=i.id,h=f!==void 0?f:e.id;this.id=h,this.logger=s,this.clock=o,this.parent=u,this.options=i,this.scheduler=new Vr({deferEvents:this.options.deferEvents}),this.sessionId=ft.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:ke(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return H||J(this.status!==Q.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var o=j(e.actions),s=o.next();!s.done;s=o.next()){var u=s.value;this.exec(u,e,r)}}catch(f){n={error:f}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,o,s,u,f,h,l,c=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 d=void 0;d=this._outgoingQueue.shift();)d[0].send(d[1]);if(this.children.forEach(function(C){c.state.children[C.id]=C}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var p=j(this.eventListeners),y=p.next();!y.done;y=p.next()){var g=y.value;g(e.event)}}catch(C){n={error:C}}finally{try{y&&!y.done&&(i=p.return)&&i.call(p)}finally{if(n)throw n.error}}try{for(var m=j(this.listeners),T=m.next();!T.done;T=m.next()){var g=T.value;g(e,e.event)}}catch(C){o={error:C}}finally{try{T&&!T.done&&(s=m.return)&&s.call(m)}finally{if(o)throw o.error}}try{for(var b=j(this.contextListeners),A=b.next();!A.done;A=b.next()){var P=A.value;P(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(C){u={error:C}}finally{try{A&&!A.done&&(f=b.return)&&f.call(b)}finally{if(u)throw u.error}}if(this.state.done){var R=e.configuration.find(function(C){return C.type==="final"&&C.parent===c.machine}),$=R&&R.doneData?it(R.doneData,e.context,r):void 0;try{for(var x=j(this.doneListeners),_=x.next();!_.done;_=x.next()){var g=_.value;g(Me(this.id,$))}}catch(C){h={error:C}}finally{try{_&&!_.done&&(l=x.return)&&l.call(x)}finally{if(h)throw h.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Q.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,o=ot(e,r,n);this.listeners.add(o.next),this.status!==Q.NotStarted&&o.next(this.state);var s=function(){i.doneListeners.delete(s),i.stopListeners.delete(s),o.complete()};return this.status===Q.Stopped?o.complete():(this.onDone(s),this.onStop(s)),{unsubscribe:function(){i.listeners.delete(o.next),i.doneListeners.delete(s),i.stopListeners.delete(s)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===Q.Running)return this;this.machine._init(),ft.register(this.sessionId,this),this.initialized=!0,this.status=Q.Running;var n=e===void 0?this.initialState:ke(this,function(){return Ci(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){q(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,o,s,u,f,h,l;try{for(var c=j(this.listeners),d=c.next();!d.done;d=c.next()){var p=d.value;this.listeners.delete(p)}}catch(x){e={error:x}}finally{try{d&&!d.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}try{for(var y=j(this.stopListeners),g=y.next();!g.done;g=y.next()){var p=g.value;p(),this.stopListeners.delete(p)}}catch(x){n={error:x}}finally{try{g&&!g.done&&(i=y.return)&&i.call(y)}finally{if(n)throw n.error}}try{for(var m=j(this.contextListeners),T=m.next();!T.done;T=m.next()){var p=T.value;this.contextListeners.delete(p)}}catch(x){o={error:x}}finally{try{T&&!T.done&&(s=m.return)&&s.call(m)}finally{if(o)throw o.error}}try{for(var b=j(this.doneListeners),A=b.next();!A.done;A=b.next()){var p=A.value;this.doneListeners.delete(p)}}catch(x){u={error:x}}finally{try{A&&!A.done&&(f=b.return)&&f.call(b)}finally{if(u)throw u.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Q.Stopped,this._initialState=void 0;try{for(var P=j(Object.keys(this.delayedEventsMap)),R=P.next();!R.done;R=P.next()){var $=R.value;this.clock.clearTimeout(this.delayedEventsMap[$])}}catch(x){h={error:x}}finally{try{R&&!R.done&&(l=P.return)&&l.call(P)}finally{if(h)throw h.error}}this.scheduler.clear(),this.scheduler=new Vr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=W({type:"xstate.stop"}),i=ke(e,function(){var o=K(V([],D(e.state.configuration),!1).sort(function(l,c){return c.order-l.order}).map(function(l){return ce(l.onExit,e.machine.options.actions)})),s=D(je(e.machine,e.state,e.state.context,n,[o],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),u=s[0],f=s[1],h=new oe({value:e.state.value,context:f,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:u.filter(function(l){return l.type!==me&&(l.type!==ge||!!l.to&&l.to!==ie.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return h.changed=!0,h});e.update(i,n),e._stopChildren(),ft.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===Q.NotStarted&&this.options.deferEvents)H||J(!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!==Q.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,o,s=r.state,u=!1,f=[],h=function(p){var y=W(p);r.forward(y),s=ke(r,function(){return r.machine.transition(s,y,void 0,n||void 0)}),f.push.apply(f,V([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(g){return Mi(g,s)})),!1)),u=u||!!s.changed};try{for(var l=j(e),c=l.next();!c.done;c=l.next()){var d=c.value;h(d)}}catch(p){i={error:p}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(i)throw i.error}}s.changed=u,s.actions=f,r.update(s,W(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=W(e);if(i.name.indexOf(Rt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(Rt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=j(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,u=this.children.get(s);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));u.send(e)}}catch(f){r={error:f}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),q(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Q.Running)return jt(e,r);if(Sr(e))return this.spawnPromise(Promise.resolve(e),r);if(q(e))return this.spawnCallback(e,r);if(Ri(e))return this.spawnActor(e,r);if(li(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,w(w({},n),{id:r}));if(ai(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,w(w({},this.options),{parent:this,id:r.id||e.id})),o=w(w({},Bt),r);o.sync&&i.onTransition(function(u){n.send(et,{state:u,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(W(u,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Bi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(f){o||(s=f,i.removeChild(r),i.send(W(Me(r,f),{origin:r})))},function(f){if(!o){i.removeChild(r);var h=Oe(r,f);try{i.send(W(h,{origin:r}))}catch(l){pi(f,l,r),i.devTools&&i.devTools.send(h,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(f,h,l){var c=ot(f,h,l),d=!1;return e.then(function(p){d||(c.next(p),!d&&c.complete())},function(p){d||c.error(p)}),{unsubscribe:function(){return d=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,u=new Set,f,h=function(d){f=d,u.forEach(function(p){return p(d)}),!o&&i.send(W(d,{origin:r}))},l;try{l=e(h,function(d){s.add(d)})}catch(d){this.send(Oe(r,d))}if(Sr(l))return this.spawnPromise(l,r);var c=(n={id:r,send:function(d){return s.forEach(function(p){return p(d)})},subscribe:function(d){var p=ot(d);return u.add(p.next),{unsubscribe:function(){u.delete(p.next)}}},stop:function(){o=!0,q(l)&&l()},toJSON:function(){return{id:r}},getSnapshot:function(){return f}},n[he]=function(){return this},n);return this.children.set(r,c),c},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(f){o=f,i.send(W(f,{origin:r}))},function(f){i.removeChild(r),i.send(W(Oe(r,f),{origin:r}))},function(){i.removeChild(r),i.send(W(Me(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(f,h,l){return e.subscribe(f,h,l)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){H||J(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[he]=function(){return this},n))},t.prototype.attachDev=function(){var e=Ft();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(w(w({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:w({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Fi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[he]=function(){return this},t.prototype.getSnapshot=function(){return this.status===Q.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=_e,t}(),Vi=function(t){return L(t)?w(w({},Bt),{name:t}):w(w(w({},Bt),{name:fi()}),t)};function Gi(t,e){var r=Vi(e);return _i(function(n){if(!H){var i=ae(t)||q(t);J(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):jt(t,r.name)})}function _e(t,e){var r=new qi(t,e);return r}function Hi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return w(w({type:Ze},t),{toJSON:function(){t.onDone,t.onError;var e=It(t,["onDone","onError"]);return w(w({},e),{type:Ze,src:Hi(t.src)})}})}var Ie="",qt="#",Be="*",xe={},Re=function(t){return t[0]===qt},Ki=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},zi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");J(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Ji=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ki(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:yr),this.id=this.config.id||V([this.machine.key],D(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,H||J(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?De(this.config.states,function(h,l){var c,d=new t(h,{},void 0,{parent:o,key:l});return Object.assign(o.idMap,w((c={},c[d.id]=d,c),d.idMap)),d}):xe;var u=0;function f(h){var l,c;h.order=u++;try{for(var d=j(Lr(h)),p=d.next();!p.done;p=d.next()){var y=p.value;f(y)}}catch(g){l={error:g}}finally{try{p&&!p.done&&(c=d.return)&&c.call(d)}finally{if(l)throw l.error}}}f(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(h){var l=h.event;return l===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(h){return Ae(h)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(h){return Ae(h)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(h,l){var c,d;if(ae(h)){var p=st(o.id,l);return o.machine.options.services=w((c={},c[p]=h,c),o.machine.options.services),ht({src:p,id:p})}else if(L(h.src)){var p=h.id||st(o.id,l);return ht(w(w({},h),{id:p,src:h.src}))}else if(ae(h.src)||q(h.src)){var p=h.id||st(o.id,l);return o.machine.options.services=w((d={},d[p]=h.src,d),o.machine.options.services),ht(w(w({id:p},h),{src:p}))}else{var y=h.src;return ht(w(w({id:st(o.id,l)},h),{src:y}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(h){return ct(h)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||$r(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,u=n.services,f=n.delays;return new t(this.config,{actions:w(w({},i),e.actions),activities:w(w({},o),e.activities),guards:w(w({},s),e.guards),services:w(w({},u),e.services),delays:w(w({},f),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return q(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:De(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Be});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var u=q(o)?"".concat(e.id,":delay[").concat(s,"]"):o,f=Mr(u,e.id);return e.onEntry.push(pe(f,{delay:o})),e.onExit.push(Pr(f)),f},i=be(r)?r.map(function(o,s){var u=n(o.delay,s);return w(w({},o),{event:u})}):K(Object.keys(r).map(function(o,s){var u=r[o],f=L(u)?{target:u}:u,h=isNaN(+o)?o:+o,l=n(h,s);return te(f).map(function(c){return w(w({},c),{event:l,delay:h})})}));return i.map(function(o){var s=o.delay;return w(w({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:Ne(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),u=[this];return u.push.apply(u,V([],D(K(s.map(function(f){return n.getStateNode(f).getStateNodes(i[f])}))),!1)),u},t.prototype.handles=function(e){var r=gr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(w(w({},r),{value:this.resolve(r.value),configuration:n,done:dt(n,this),tags:Br(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var u=j(Object.keys(e)),f=u.next();!f.done;f=u.next()){var h=f.value,l=e[h];if(l){var c=this.getStateNode(h),d=c._transition(l,r,n);d&&(s[h]=d)}}}catch(b){i={error:b}}finally{try{f&&!f.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}var p=Object.keys(s).map(function(b){return s[b]}),y=K(p.map(function(b){return b.transitions})),g=p.some(function(b){return b.transitions.length>0});if(!g)return this.next(r,n);var m=K(p.map(function(b){return b.entrySet})),T=K(Object.keys(s).map(function(b){return s[b].configuration}));return{transitions:y,entrySet:m,exitSet:K(p.map(function(b){return b.exitSet})),configuration:T,source:r,actions:K(Object.keys(s).map(function(b){return s[b].actions}))}},t.prototype._transition=function(e,r,n){return L(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,W(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,u=[],f=[],h;try{for(var l=j(this.getCandidates(s)),c=l.next();!c.done;c=l.next()){var d=c.value,p=d.cond,y=d.in,g=e.context,m=y?L(y)&&Re(y)?e.matches(Ne(this.getStateNodeById(y).path,this.delimiter)):Nt(Ne(y,this.delimiter),ii(this.path.slice(0,-2))(e.value)):!0,T=!1;try{T=!p||Or(this.machine,p,g,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(p.name||p.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
|
|
18
|
+
`).concat(R.message))}if(T&&m){d.target!==void 0&&(f=d.target),u.push.apply(u,V([],D(d.actions),!1)),h=d;break}}}catch(R){n={error:R}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}if(h){if(!f.length)return{transitions:[h],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var b=K(f.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!h.internal,P=[];return A||f.forEach(function(R){P.push.apply(P,V([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[h],entrySet:P,exitSet:A?[]:[this],configuration:b,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,u){var f,h,l,c,d=this,p=$e([],s?this.getStateNodes(s.value):[this]);try{for(var y=j(e),g=y.next();!g.done;g=y.next()){var m=g.value;(!Fe(p,m)||Fe(n.entrySet,m.parent))&&n.entrySet.push(m)}}catch(k){f={error:k}}finally{try{g&&!g.done&&(h=y.return)&&h.call(y)}finally{if(f)throw f.error}}try{for(var T=j(p),b=T.next();!b.done;b=T.next()){var m=b.value;(!Fe(e,m)||Fe(n.exitSet,m.parent))&&n.exitSet.push(m)}}catch(k){l={error:k}}finally{try{b&&!b.done&&(c=T.return)&&c.call(T)}finally{if(l)throw l.error}}var A=K(n.entrySet.map(function(k){var I=[];if(k.type!=="final")return I;var F=k.parent;if(!F.parent)return I;I.push(Ce(k.id,k.doneData),Ce(F.id,k.doneData?it(k.doneData,i,o):void 0));var G=F.parent;return G.type==="parallel"&&Le(G).every(function(a){return dt(n.configuration,a)})&&I.push(Ce(G.id)),I}));n.exitSet.sort(function(k,I){return I.order-k.order}),n.entrySet.sort(function(k,I){return k.order-I.order});var P=new Set(n.entrySet),R=new Set(n.exitSet),$=Array.from(P).map(function(k){var I=k.onEntry,F=k.activities.map(function(G){return Ur(G)});return ce(u?V(V([],D(I),!1),D(F),!1):V(V([],D(F),!1),D(I),!1),d.machine.options.actions)}).concat([A.map(_r)]),x=Array.from(R).map(function(k){return ce(V(V([],D(k.onExit),!1),D(k.activities.map(function(I){return Nr(I)})),!1),d.machine.options.actions)}),_=x.concat([ce(n.actions,this.machine.options.actions)]).concat($);if(r){var C=ce(K(V([],D(e),!1).sort(function(k,I){return I.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return _.concat([C])}return _},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=W(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=L(e)?this.resolve(rt(this.getResolvedPath(e))):this.resolve(e),f=n??this.machine.context;s=this.resolveState(oe.from(u,f))}if(!H&&o.name===Be)throw new Error("An event cannot have the wildcard type ('".concat(Be,"')"));if(this.strict&&!this.events.includes(o.name)&&!si(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var h=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},l=$e([],this.getStateNodes(s.value)),c=h.configuration.length?$e(l,h.configuration):l;return h.configuration=V([],D(c),!1),this.resolveTransition(h,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,V([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,u,f,h,l=this;o===void 0&&(o=we);var c=e.configuration,d=!r||e.transitions.length>0,p=d?e.configuration:r?r.configuration:[],y=dt(p,this),g=d?Ui(this.machine,c):void 0,m=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,T=this.getActions(new Set(p),y,e,n,o,r,i),b=r?w({},r.activities):{};try{for(var A=j(T),P=A.next();!P.done;P=A.next()){var R=P.value;try{for(var $=(f=void 0,j(R)),x=$.next();!x.done;x=$.next()){var _=x.value;_.type===Qe?b[_.activity.id||_.activity.type]=_:_.type===Ye&&(b[_.activity.id||_.activity.type]=!1)}}catch(Z){f={error:Z}}finally{try{x&&!x.done&&(h=$.return)&&h.call($)}finally{if(f)throw f.error}}}}catch(Z){s={error:Z}}finally{try{P&&!P.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}var C=D(je(this,r,n,o,T,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=C[0],I=C[1],F=D(ci(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),G=F[0],a=F[1],v=k.filter(function(Z){var Ue;return Z.type===Qe&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Ze}),S=v.reduce(function(Z,Ue){return Z[Ue.activity.id]=Ii(Ue.activity,l.machine,I,o),Z},r?w({},r.children):{}),M=new oe({value:g||r.value,context:I,_event:o,_sessionid:r?r._sessionid:null,historyValue:g?m?ui(m,g):void 0:r?r.historyValue:void 0,history:!g||e.source?r:void 0,actions:g?a:[],activities:g?b:r?r.activities:{},events:[],configuration:p,transitions:e.transitions,children:S,done:y,tags:Br(p),machine:this}),U=n!==I;M.changed=o.name===et||U;var O=M.history;O&&delete O.history;var ee=!y&&(this._transient||c.some(function(Z){return Z._transient}));if(!d&&(!ee||o.name===Ie))return M;var z=M;if(!y)for(ee&&(z=this.resolveRaisedTransition(z,{type:fr},o,i));G.length;){var fe=G.shift();z=this.resolveRaisedTransition(z,fe._event,o,i)}var No=z.changed||(O?!!z.actions.length||U||typeof O.value!=typeof z.value||!qr(z.value,O.value):void 0);return z.changed=No,z.history=O,z},t.prototype.getStateNode=function(e){if(Re(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Re(e)?e.slice(qt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Re(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Dt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||xe;switch(this.type){case"parallel":return De(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):xe});case"compound":if(L(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?De(e,function(o,s){return o?n.getStateNode(s).resolve(o):xe}):this.initialStateValue||{};default:return e||xe}},t.prototype.getResolvedPath=function(e){if(Re(e)){var r=this.machine.idMap[e.slice(qt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Dt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=wr(this.states,function(n){return n.initialStateValue||xe},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=lt(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:V([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r??this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;L(r.target)?e=Re(r.target)?rt(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(lt(this))return[this];if(this.type==="compound"&&!this.initial)return H||J(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=nt(this.initialStateValue);return K(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var o=this.getStateNode(n);if(o.type==="history")return o.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:wr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?K(nt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=oi(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:K(nt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=K(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var o=this.states,s=new Set(this.ownEvents);if(o)try{for(var u=j(Object.keys(o)),f=u.next();!f.done;f=u.next()){var h=f.value,l=o[h];if(l.states)try{for(var c=(n=void 0,j(l.events)),d=c.next();!d.done;d=c.next()){var p=d.value;s.add("".concat(p))}}catch(y){n={error:y}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}}}catch(y){e={error:y}}finally{try{f&&!f.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
+
`).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=hi(e.target),i="internal"in e?e.internal:n?n.some(function(f){return L(f)&&f[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=w(w({},e),{actions:ce(te(e.actions)),cond:Ar(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return w(w({},u),{target:u.target?u.target.map(function(f){return"#".concat(f.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var o=this.config.on,s=Be,u=o[s],f=u===void 0?[]:u,h=It(o,[typeof s=="symbol"?s:s+""]);i=K(Object.keys(h).map(function(b){!H&&b===Ie&&J(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var A=Te(b,h[b]);return H||zi(n,b,A),A}).concat(Te(Be,f)))}var l=this.config.always?Te("",this.config.always):[],c=this.config.onDone?Te(String(Ce(this.id)),this.config.onDone):[];H||J(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=K(this.invoke.map(function(b){var A=[];return b.onDone&&A.push.apply(A,V([],D(Te(String(Me(b.id)),b.onDone)),!1)),b.onError&&A.push.apply(A,V([],D(Te(String(Oe(b.id)),b.onError)),!1)),A})),p=this.after,y=K(V(V(V(V([],D(c),!1),D(d),!1),D(i),!1),D(l),!1).map(function(b){return te(b).map(function(A){return n.formatTransition(A)})}));try{for(var g=j(p),m=g.next();!m.done;m=g.next()){var T=m.value;y.push(T)}}catch(b){e={error:b}}finally{try{m&&!m.done&&(r=g.return)&&r.call(g)}finally{if(e)throw e.error}}return y},t}(),Gr=!1;function ve(t,e){return!H&&!t.predictableActionArguments&&!Gr&&(Gr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Ji(t,e)}var N=Cr,Y=pe;/*! js-cookie v3.0.1 | MIT */function pt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var Qi={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Vt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=pt({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var f in s)s[f]&&(u+="; "+f,s[f]!==!0&&(u+="="+s[f].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var f=o[u].split("="),h=f.slice(1).join("=");try{var l=decodeURIComponent(f[0]);if(s[l]=t.read(h,l),i===l)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",pt({},o,{expires:-1}))},withAttributes:function(i){return Vt(this.converter,pt({},this.attributes,i))},withConverter:function(i){return Vt(pt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Gt=Vt(Qi,{path:"/"}),Yi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Wi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ht={exports:{}};(function(t,e){var r=typeof self<"u"?self:Yi,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(a){return a&&h.indexOf(Object.prototype.toString.call(a))>-1};function c(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function d(a){return typeof a!="string"&&(a=String(a)),a}function p(a){var v={next:function(){var S=a.shift();return{done:S===void 0,value:S}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function y(a){this.map={},a instanceof y?a.forEach(function(v,S){this.append(S,v)},this):Array.isArray(a)?a.forEach(function(v){this.append(v[0],v[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(v){this.append(v,a[v])},this)}y.prototype.append=function(a,v){a=c(a),v=d(v);var S=this.map[a];this.map[a]=S?S+", "+v:v},y.prototype.delete=function(a){delete this.map[c(a)]},y.prototype.get=function(a){return a=c(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(c(a))},y.prototype.set=function(a,v){this.map[c(a)]=d(v)},y.prototype.forEach=function(a,v){for(var S in this.map)this.map.hasOwnProperty(S)&&a.call(v,this.map[S],S,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(v,S){a.push(S)}),p(a)},y.prototype.values=function(){var a=[];return this.forEach(function(v){a.push(v)}),p(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(v,S){a.push([S,v])}),p(a)},u.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function g(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function m(a){return new Promise(function(v,S){a.onload=function(){v(a.result)},a.onerror=function(){S(a.error)}})}function T(a){var v=new FileReader,S=m(v);return v.readAsArrayBuffer(a),S}function b(a){var v=new FileReader,S=m(v);return v.readAsText(a),S}function A(a){for(var v=new Uint8Array(a),S=new Array(v.length),M=0;M<v.length;M++)S[M]=String.fromCharCode(v[M]);return S.join("")}function P(a){if(a.slice)return a.slice(0);var v=new Uint8Array(a.byteLength);return v.set(new Uint8Array(a)),v.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&f(a)?(this._bodyArrayBuffer=P(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||l(a))?this._bodyArrayBuffer=P(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(T)}),this.text=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(C)}),this.json=function(){return this.text().then(JSON.parse)},this}var $=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function x(a){var v=a.toUpperCase();return $.indexOf(v)>-1?v:a}function _(a,v){v=v||{};var S=v.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,v.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!S&&a._bodyInit!=null&&(S=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new y(v.headers)),this.method=x(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function C(a){var v=new FormData;return a.trim().split("&").forEach(function(S){if(S){var M=S.split("="),U=M.shift().replace(/\+/g," "),O=M.join("=").replace(/\+/g," ");v.append(decodeURIComponent(U),decodeURIComponent(O))}}),v}function k(a){var v=new y,S=a.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(M){var U=M.split(":"),O=U.shift().trim();if(O){var ee=U.join(":").trim();v.append(O,ee)}}),v}R.call(_.prototype);function I(a,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new y(v.headers),this.url=v.url||"",this._initBody(a)}R.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},I.error=function(){var a=new I(null,{status:0,statusText:""});return a.type="error",a};var F=[301,302,303,307,308];I.redirect=function(a,v){if(F.indexOf(v)===-1)throw new RangeError("Invalid status code");return new I(null,{status:v,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(v,S){this.message=v,this.name=S;var M=Error(v);this.stack=M.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function G(a,v){return new Promise(function(S,M){var U=new _(a,v);if(U.signal&&U.signal.aborted)return M(new s.DOMException("Aborted","AbortError"));var O=new XMLHttpRequest;function ee(){O.abort()}O.onload=function(){var z={status:O.status,statusText:O.statusText,headers:k(O.getAllResponseHeaders()||"")};z.url="responseURL"in O?O.responseURL:z.headers.get("X-Request-URL");var fe="response"in O?O.response:O.responseText;S(new I(fe,z))},O.onerror=function(){M(new TypeError("Network request failed"))},O.ontimeout=function(){M(new TypeError("Network request failed"))},O.onabort=function(){M(new s.DOMException("Aborted","AbortError"))},O.open(U.method,U.url,!0),U.credentials==="include"?O.withCredentials=!0:U.credentials==="omit"&&(O.withCredentials=!1),"responseType"in O&&u.blob&&(O.responseType="blob"),U.headers.forEach(function(z,fe){O.setRequestHeader(fe,z)}),U.signal&&(U.signal.addEventListener("abort",ee),O.onreadystatechange=function(){O.readyState===4&&U.signal.removeEventListener("abort",ee)}),O.send(typeof U._bodyInit>"u"?null:U._bodyInit)})}return G.polyfill=!0,o.fetch||(o.fetch=G,o.Headers=y,o.Request=_,o.Response=I),s.Headers=y,s.Request=_,s.Response=I,s.fetch=G,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(Ht,Ht.exports);const Kt=Wi(Ht.exports),qe="nhostRefreshToken",Ve="nhostRefreshTokenExpiresAt",Hr=3,Kr=300,zt=5,Jt=0,Qt=1,re=10,Pe=20;class Ge extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Qt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},zr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},Jr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},vt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},Yt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Yr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Wr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Xr={status:Pe,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:Pe,error:"already-signed-in",message:"User is already signed in"},Zr={status:Pe,error:"unauthenticated-user",message:"User is not authenticated"},Xi={status:Pe,error:"user-not-anonymous",message:"User is not anonymous"},en={status:Pe,error:"unverified-user",message:"Email needs verification"},tn={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},rn={status:Qt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},yt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function Zi(t){return new TextEncoder().encode(t)}function Ee(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Wt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function nn(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function on(t){const{id:e}=t;return{...t,id:Wt(e),transports:t.transports}}function sn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let X=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function eo({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new X("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(sn(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class to{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const mt=new to;async function an(t){if(!nn())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Wt(t.challenge),user:{...t.user,id:Zi(t.user.id)},excludeCredentials:t.excludeCredentials.map(on)}};e.signal=mt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(f){throw eo({error:f,options:e})}finally{mt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function ro(t){return new TextDecoder("utf-8").decode(t)}async function no(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function io({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(sn(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function oo(t,e=!1){var r,n;if(!nn())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(on));const o={...t,challenge:Wt(t.challenge),allowCredentials:i},s={};if(e){if(!await no())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=mt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(p){throw io({error:p,options:s})}finally{mt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:f,rawId:h,response:l,type:c}=u;let d;return l.userHandle&&(d=ro(l.userHandle)),{id:f,rawId:Ee(h),response:{authenticatorData:Ee(l.authenticatorData),clientDataJSON:Ee(l.clientDataJSON),signature:Ee(l.signature),userHandle:d},type:c,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const gt=typeof window<"u",wt=new Map,so=t=>gt&&typeof localStorage<"u"?localStorage.getItem(t):wt.get(t)??null,ao=(t,e)=>{gt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?wt.set(t,e):wt.has(t)&&wt.delete(t)},cn=(t,e)=>{if(t==="localStorage"||t==="web")return so;if(t==="cookie")return r=>gt?Gt.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},un=(t,e)=>{if(t==="localStorage"||t==="web")return ao;if(t==="cookie")return(r,n)=>{gt&&(n?Gt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Gt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ye=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},Et=()=>typeof window<"u",ln=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Kt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const s={message:"Network Error",status:Jt,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>ln(t,"POST",{token:r,body:e}),dn=(t,e)=>ln(t,"GET",{token:e}),Xt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let f=Object.fromEntries(u);r.startsWith("/")&&(f={...o,...f});let h=i.pathname;return s.pathname.length>1&&(h+=s.pathname.slice(1)),{...n,redirectTo:Xt(s.origin+h,f)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Zt(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),St=t=>!!t&&typeof t=="string"&&t.length>=Hr,er=t=>!!t&&typeof t=="string",fn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),hn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=cn(r,n),f=un(r,n),h=async(l,c,d)=>(await le(`${t}${l}`,c,d)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:yt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:Y("SIGNED_IN"),reportSignedOut:Y("SIGNED_OUT"),reportTokenChanged:Y("TOKEN_CHANGED"),incrementTokenImportAttempts:N({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:N(()=>(f(Ve,null),f(qe,null),{...yt})),clearContextExceptRefreshToken:N(({refreshToken:{value:l}})=>(f(Ve,null),{...yt,refreshToken:{value:l}})),saveSession:N({user:(l,{data:c})=>{var d;return((d=c==null?void 0:c.session)==null?void 0:d.user)||null},accessToken:(l,{data:c})=>{if(c.session){const{accessTokenExpiresIn:d,accessToken:p}=c.session,y=new Date(Date.now()+d*1e3);return f(Ve,y.toISOString()),{value:p,expiresAt:y}}return f(Ve,null),{value:null,expiresAt:null}},refreshToken:(l,{data:c})=>{var d;const p=((d=c.session)==null?void 0:d.refreshToken)||null;return p&&f(qe,p),{value:p}}}),saveMfaTicket:N({mfa:(l,c)=>{var d;return(d=c.data)==null?void 0:d.mfa}}),resetTimer:N({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:N({refreshTimer:(l,c)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:N({errors:({errors:l},{data:{error:c}})=>({...l,authentication:c})}),resetErrors:N({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:N({errors:({errors:l},{data:{error:c}})=>({...l,registration:c})}),destroyRefreshToken:N({refreshToken:l=>(f(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Zt("refreshToken"),Zt("type"))},broadcastToken:l=>{if(s)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isAnonymous:(l,c)=>{var d;return!!((d=l.user)!=null&&d.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{const{expiresAt:c}=l.accessToken;return c?l.refreshTimer.lastAttempt?l.refreshTimer.attempts>zt?!1:Date.now()-l.refreshTimer.lastAttempt.getTime()>Math.pow(2,l.refreshTimer.attempts-1)*5e3:i&&Date.now()-l.refreshTimer.startedAt.getTime()>i*1e3?!0:c.getTime()-Date.now()-1e3*Kr<=0:!1},shouldRetryImportToken:(l,c)=>l.importTokenAttempts<zt&&(c.data.error.status===Jt||c.data.error.status>=500),unverified:(l,{data:{error:c}})=>c.status===401&&(c.message==="Email is not verified"||c.error==="unverified-user"),hasSession:(l,c)=>{var d;return!!((d=c.data)!=null&&d.session)},hasMfaTicket:(l,c)=>{var d;return!!((d=c.data)!=null&&d.mfa)}},services:{signInPassword:(l,{email:c,password:d})=>de(c)?St(d)?h("/signin/email-password",{email:c,password:d}):Promise.reject({error:vt}):Promise.reject({error:ue}),passwordlessSms:(l,{phoneNumber:c,options:d})=>{var p;return er(c)?(p=l.user)!=null&&p.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:c,options:ne(e,d)},l.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:c,options:ne(e,d)}):Promise.reject({error:Yt})},passwordlessSmsOtp:(l,{phoneNumber:c,otp:d})=>er(c)?h("/signin/passwordless/sms/otp",{phoneNumber:c,otp:d}):Promise.reject({error:Yt}),passwordlessEmail:(l,{email:c,options:d})=>{var p;return de(c)?(p=l.user)!=null&&p.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:c,options:ne(e,d)},l.accessToken.value):h("/signin/passwordless/email",{email:c,options:ne(e,d)}):Promise.reject({error:ue})},signInAnonymous:l=>h("/signin/anonymous"),signInMfaTotp:(l,c)=>{var d;const p=c.ticket||((d=l.mfa)==null?void 0:d.ticket);return p?fn(p)?h("/signin/mfa/totp",{ticket:p,otp:c.otp}):Promise.reject({error:Qr}):Promise.reject({error:Yr})},signInSecurityKeyEmail:async(l,{email:c})=>{if(!de(c))throw new Ge(ue);const d=await h("/signin/webauthn",{email:c});let p;try{p=await oo(d)}catch(y){throw new Ge(y)}return h("/signin/webauthn/verify",{email:c,credential:p})},refreshToken:async(l,c)=>{const d=c.type==="TRY_TOKEN"?c.token:l.refreshToken.value;return{session:await h("/token",{refreshToken:d}),error:null}},signout:(l,c)=>h("/signout",{refreshToken:l.refreshToken.value,all:!!c.all}),signUpEmailPassword:async(l,{email:c,password:d,options:p})=>{var y;return de(c)?St(d)?(y=l.user)!=null&&y.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:c,password:d,options:ne(e,p)},l.accessToken.value):h("/signup/email-password",{email:c,password:d,options:ne(e,p)}):Promise.reject({error:vt}):Promise.reject({error:ue})},signUpSecurityKey:async(l,{email:c,options:d})=>{if(!de(c))return Promise.reject({error:ue});const p=d==null?void 0:d.nickname;p&&delete d.nickname;const y=await h("/signup/webauthn",{email:c,options:d});let g;try{g=await an(y)}catch(m){throw new Ge(m)}return h("/signup/webauthn/verify",{credential:g,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:p}})},importRefreshToken:async l=>{if(l.user&&l.refreshToken.value&&l.accessToken.value&&l.accessToken.expiresAt)return{session:{accessToken:l.accessToken.value,accessTokenExpiresIn:l.accessToken.expiresAt.getTime()-Date.now(),refreshToken:l.refreshToken.value,user:l.user},error:null};let c=null;if(s){const p=Ke("refreshToken")||null;if(p)try{return{session:await h("/token",{refreshToken:p}),error:null}}catch(y){c=y.error}else{const y=Ke("error");if(y)return Promise.reject({session:null,error:{status:re,error:y,message:Ke("errorDescription")||y}})}}const d=await u(qe);if(d)try{return{session:await h("/token",{refreshToken:d}),error:null}}catch(p){c=p.error}return c?Promise.reject({error:c,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>Math.pow(2,l-1)*5e3}})},pn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:N({error:n=>ue}),saveRequestError:N({error:(n,{data:{error:i}})=>i}),reportError:Y(n=>({type:"ERROR",error:n.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),vn=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:N({error:r=>vt}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!St(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),co=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:N({error:r=>zr}),saveInvalidMfaCodeError:N({error:r=>Jr}),saveError:N({error:(r,{data:{error:n}})=>n}),saveGeneration:N({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:Y((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS"),reportGeneratedSuccess:Y("GENERATED"),reportGeneratedError:Y(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await dn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),yn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:N({error:r=>ue}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),mn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:N({error:r=>ue}),saveRequestError:N({error:(r,{data:{error:n}})=>n}),reportError:Y(r=>({type:"ERROR",error:r.error})),reportSuccess:Y("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let tr=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...f}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=hn({...f,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",h=>{var l;const c=(l=this.interpreter)==null?void 0:l.getSnapshot().context.refreshToken.value;this.interpreter&&h.data!==c&&this.interpreter.send("TRY_TOKEN",{token:h.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||_e(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}};class gn extends tr{constructor({...e}){super({...e,autoSignIn:Et()&&e.autoSignIn,autoRefreshToken:Et()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const uo=gn,wn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await an(n)}catch(s){throw new Ge(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},En=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),Sn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),lo=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),fo=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),bn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Tn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),An=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),On=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),rr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),kn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),_n=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),nr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),In=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),xn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:Zr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),ir=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),Rn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class Pn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var f;this.url=e,this._client=new tr({backendUrl:e,clientUrl:typeof window<"u"&&((f=window.location)==null?void 0:f.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await Rn(r,n,i)):ye(await ir(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await An(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Xt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return Et()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await On(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:en}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await kn(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await rr(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await In(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await nr(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await _n(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:rn,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await xn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=_e(yn(this._client)).start(),{error:i}=await bn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=_e(vn(this._client)).start(),{error:i}=await Sn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=_e(mn(this._client)).start(),{error:i}=await Tn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=_e(pn(this._client)).start(),{error:i}=await En(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await rr(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await nr(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await ir(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await wn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Wn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Wr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Xr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:tn}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Un=typeof self=="object"?self.FormData:window.FormData,ho=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function po(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var or={exports:{}};(function(t,e){var r=typeof self<"u"?self:ho,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function f(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var h=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(a){return a&&h.indexOf(Object.prototype.toString.call(a))>-1};function c(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function d(a){return typeof a!="string"&&(a=String(a)),a}function p(a){var v={next:function(){var S=a.shift();return{done:S===void 0,value:S}}};return u.iterable&&(v[Symbol.iterator]=function(){return v}),v}function y(a){this.map={},a instanceof y?a.forEach(function(v,S){this.append(S,v)},this):Array.isArray(a)?a.forEach(function(v){this.append(v[0],v[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(v){this.append(v,a[v])},this)}y.prototype.append=function(a,v){a=c(a),v=d(v);var S=this.map[a];this.map[a]=S?S+", "+v:v},y.prototype.delete=function(a){delete this.map[c(a)]},y.prototype.get=function(a){return a=c(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(c(a))},y.prototype.set=function(a,v){this.map[c(a)]=d(v)},y.prototype.forEach=function(a,v){for(var S in this.map)this.map.hasOwnProperty(S)&&a.call(v,this.map[S],S,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(v,S){a.push(S)}),p(a)},y.prototype.values=function(){var a=[];return this.forEach(function(v){a.push(v)}),p(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(v,S){a.push([S,v])}),p(a)},u.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function g(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function m(a){return new Promise(function(v,S){a.onload=function(){v(a.result)},a.onerror=function(){S(a.error)}})}function T(a){var v=new FileReader,S=m(v);return v.readAsArrayBuffer(a),S}function b(a){var v=new FileReader,S=m(v);return v.readAsText(a),S}function A(a){for(var v=new Uint8Array(a),S=new Array(v.length),M=0;M<v.length;M++)S[M]=String.fromCharCode(v[M]);return S.join("")}function P(a){if(a.slice)return a.slice(0);var v=new Uint8Array(a.byteLength);return v.set(new Uint8Array(a)),v.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&f(a)?(this._bodyArrayBuffer=P(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||l(a))?this._bodyArrayBuffer=P(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(T)}),this.text=function(){var a=g(this);if(a)return a;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(C)}),this.json=function(){return this.text().then(JSON.parse)},this}var $=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function x(a){var v=a.toUpperCase();return $.indexOf(v)>-1?v:a}function _(a,v){v=v||{};var S=v.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,v.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!S&&a._bodyInit!=null&&(S=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=v.credentials||this.credentials||"same-origin",(v.headers||!this.headers)&&(this.headers=new y(v.headers)),this.method=x(v.method||this.method||"GET"),this.mode=v.mode||this.mode||null,this.signal=v.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&S)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(S)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function C(a){var v=new FormData;return a.trim().split("&").forEach(function(S){if(S){var M=S.split("="),U=M.shift().replace(/\+/g," "),O=M.join("=").replace(/\+/g," ");v.append(decodeURIComponent(U),decodeURIComponent(O))}}),v}function k(a){var v=new y,S=a.replace(/\r?\n[\t ]+/g," ");return S.split(/\r?\n/).forEach(function(M){var U=M.split(":"),O=U.shift().trim();if(O){var ee=U.join(":").trim();v.append(O,ee)}}),v}R.call(_.prototype);function I(a,v){v||(v={}),this.type="default",this.status=v.status===void 0?200:v.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in v?v.statusText:"OK",this.headers=new y(v.headers),this.url=v.url||"",this._initBody(a)}R.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},I.error=function(){var a=new I(null,{status:0,statusText:""});return a.type="error",a};var F=[301,302,303,307,308];I.redirect=function(a,v){if(F.indexOf(v)===-1)throw new RangeError("Invalid status code");return new I(null,{status:v,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,v){this.message=a,this.name=v;var S=Error(a);this.stack=S.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function G(a,v){return new Promise(function(S,M){var U=new _(a,v);if(U.signal&&U.signal.aborted)return M(new s.DOMException("Aborted","AbortError"));var O=new XMLHttpRequest;function ee(){O.abort()}O.onload=function(){var z={status:O.status,statusText:O.statusText,headers:k(O.getAllResponseHeaders()||"")};z.url="responseURL"in O?O.responseURL:z.headers.get("X-Request-URL");var fe="response"in O?O.response:O.responseText;S(new I(fe,z))},O.onerror=function(){M(new TypeError("Network request failed"))},O.ontimeout=function(){M(new TypeError("Network request failed"))},O.onabort=function(){M(new s.DOMException("Aborted","AbortError"))},O.open(U.method,U.url,!0),U.credentials==="include"?O.withCredentials=!0:U.credentials==="omit"&&(O.withCredentials=!1),"responseType"in O&&u.blob&&(O.responseType="blob"),U.headers.forEach(function(z,fe){O.setRequestHeader(fe,z)}),U.signal&&(U.signal.addEventListener("abort",ee),O.onreadystatechange=function(){O.readyState===4&&U.signal.removeEventListener("abort",ee)}),O.send(typeof U._bodyInit>"u"?null:U._bodyInit)})}return G.polyfill=!0,o.fetch||(o.fetch=G,o.Headers=y,o.Request=_,o.Response=I),s.Headers=y,s.Request=_,s.Response=I,s.fetch=G,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(or,or.exports);const sr=po(or.exports),vo=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},Nn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const f={};i&&(f["x-nhost-file-id"]=i),o&&(f["x-nhost-bucket-id"]=o),n&&(f["x-nhost-file-name"]=vo(n)),s&&(f["x-hasura-admin-secret"]=s),r&&(f.Authorization=`Bearer ${r}`);const h=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const l=await sr(h,{method:"POST",headers:f,body:e});return l.ok?{fileMetadata:await l.json(),error:null}:{error:{status:l.status,message:await l.text(),error:l.statusText},fileMetadata:null}}catch(l){return{error:{status:0,message:l.message,error:l.message},fileMetadata:null}}return new Promise(l=>{console.log("NOOOOOOO");let c=new XMLHttpRequest;c.responseType="json",c.onload=()=>c.status<200&&c.status>=300?l({fileMetadata:null,error:{error:c.statusText,message:c.statusText,status:c.status}}):l({fileMetadata:c.response,error:null}),c.onerror=()=>l({fileMetadata:null,error:{error:c.statusText,message:c.statusText,status:c.status}}),u&&c.upload.addEventListener("progress",u,!1),c.open("POST",h,!0),Object.entries(f).forEach(([d,p])=>{c.setRequestHeader(d,p)}),c.send(e)})};class Dn{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return Nn(this.url,r,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await sr(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await sr(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const Cn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Mn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Dn({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new Un,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Cn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const bt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},jn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...bt},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:N({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:N({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:N({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:N({progress:t=>null,loaded:t=>0}),resetContext:N(t=>bt),addFile:N({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new Un;i.append("file",n);let o=0;return Nn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,f=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:f})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:f,bucketId:h}=s;r({type:"UPLOAD_DONE",id:f,bucketId:h})}}),()=>{}}}}),{pure:ar,sendParent:Tt}=ki,yo=()=>ve({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:N((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:N({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:N({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:N({loaded:t=>0}),startProgress:N({progress:t=>0}),resetProgress:N({progress:t=>null}),addItem:N((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Gi(jn().withConfig({actions:{sendProgress:Tt((u,{additions:f})=>({type:"UPLOAD_PROGRESS",additions:f})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...bt,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:N({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:ar(t=>t.files.map(e=>Y({type:"DESTROY"},{to:e.id}))),upload:ar((t,e)=>t.files.map(r=>Y(e,{to:r.id}))),cancel:ar(t=>t.files.map(e=>Y({type:"CANCEL"},{to:e.id})))}}),mo=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),go=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),wo=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function At(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const o=n.match(wo);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:f=1337}=o.groups,h=bo(e);return h||`${s}://${u}:${f}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function Eo(){return typeof window<"u"}function So(){return typeof process<"u"&&process.env}function bo(t){return Eo()||!So()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Ln(t){const e="subdomain"in t||"backendUrl"in t?At(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Pn({url:e,...t})}function $n(t){const e="subdomain"in t||"backendUrl"in t?At(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Fn({url:e,...t})}class Fn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Kt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}var cr={},Bn={},Ot={};Object.defineProperty(Ot,"__esModule",{value:!0});var To=function(){function t(e){this.value=e}return t}();Ot.EnumType=To;var kt={};Object.defineProperty(kt,"__esModule",{value:!0});var Ao=function(){function t(e){this.value=e}return t.prototype.toJSON=function(){return"$"+this.value},t}();kt.VariableType=Ao,function(t){Object.defineProperty(t,"__esModule",{value:!0});var e=Ot,r=kt;t.configFields=["__args","__alias","__aliasFor","__variables","__directives","__on","__all_on","__typeName","__name"];function n(c){if(c instanceof e.EnumType)return c.value;if(c instanceof r.VariableType)return"$"+c.value;if(typeof c!="object"||c===null)return JSON.stringify(c);if(Array.isArray(c))return"["+c.map(function(p){return n(p)}).join(", ")+"]";var d=Object.keys(c).map(function(p){return p+": "+n(c[p])}).join(", ");return"{"+d+"}"}function i(c){var d=[];for(var p in c)d.push(p+": "+n(c[p]));return d.join(", ")}function o(c){var d=[];for(var p in c)d.push("$"+p+": "+c[p]);return d.join(", ")}function s(c){var d=Object.keys(c)[0],p=c[d];if(typeof p=="boolean"||typeof p=="object"&&Object.keys(p).length===0)return d;if(typeof p=="object"){var y=[];for(var g in p){var m=n(p[g]).replace(/"/g,"");y.push(g+": "+m)}return d+"("+y.join(", ")+")"}else throw new Error("Unsupported type for directive: "+typeof p+`. Types allowed: object, boolean.
|
|
20
|
+
`+("Offending object: "+JSON.stringify(c)))}function u(c){return Array(c*4+1).join(" ")}function f(c,d){return t.configFields.indexOf(c)==-1&&d.indexOf(c)==-1}function h(c,d,p,y){Object.keys(c).filter(function(g){return f(g,y.ignoreFields)}).forEach(function(g){var m=c[g];if(typeof m=="object"){if(Array.isArray(m)&&(m=m.find(function(F){return F&&typeof F=="object"}),!m)){p.push([""+g,d]);return}var T=Object.keys(m).filter(function(F){return f(F,y.ignoreFields)}).length,b=T>0,A=typeof m.__args=="object"&&Object.keys(m.__args).length>0,P=typeof m.__directives=="object",R=m.__all_on instanceof Array,$=typeof m.__on=="object",x=""+g;if(typeof m.__name=="string"&&(x=x+" "+m.__name),typeof m.__aliasFor=="string"&&(x=x+": "+m.__aliasFor),typeof m.__variables=="object"&&Object.keys(m.__variables).length>0)x=x+" ("+o(m.__variables)+")";else if(A||P){var _="",C="";P&&(C=Object.entries(m.__directives).map(function(F){var G;return"@"+s((G={},G[F[0]]=F[1],G))}).join(" ")),A&&(_="("+i(m.__args)+")");var k=P&&A?" ":"";x=x+" "+_+k+C}if(p.push([x+(b||$||R?" {":""),d]),h(m,d+1,p,y),R&&m.__all_on.forEach(function(F){p.push(["..."+F,d+1])}),$){var I=m.__on instanceof Array?m.__on:[m.__on];I.forEach(function(F){var G=F.__typeName;p.push(["... on "+G+" {",d+1]),h(F,d+2,p,y),p.push(["}",d+1])})}(b||$||R)&&p.push(["}",d])}else(y.includeFalsyKeys===!0||m)&&p.push([""+g,d])})}function l(c,d){if(d===void 0&&(d={}),!c||typeof c!="object")throw new Error("query object not specified");if(Object.keys(c).length==0)throw new Error("query object has no data");d.ignoreFields instanceof Array||(d.ignoreFields=[]);var p=[];h(c,0,p,d);var y="";return p.forEach(function(g){var m=g[0],T=g[1];d.pretty?(y&&(y+=`
|
|
21
|
+
`),y+=u(T)+m):(y&&(y+=" "),y+=m)}),y}t.jsonToGraphQLQuery=l}(Bn),function(t){function e(i){for(var o in i)Object.prototype.hasOwnProperty.call(t,o)||(t[o]=i[o])}Object.defineProperty(t,"__esModule",{value:!0}),e(Bn);var r=Ot;t.EnumType=r.EnumType;var n=kt;t.VariableType=n.VariableType}(cr);const Oo=(t,e)=>t.introspection.__schema.types.find(r=>Object.entries(e).every(([n,i])=>r[n]===i)),qn=(t,e)=>{var r;const n=(r=t.introspection.__schema[`${e.toLowerCase()}Type`])==null?void 0:r.name;if(!n)return null;const i=Oo(t,{kind:"OBJECT",name:n});if(!i)throw new Error(`Could not find the root operation type for ${e}`);return i},Vn=(t,e)=>{var r;if(!t)return[];const n=qn(t,e);return((r=n==null?void 0:n.fields)==null?void 0:r.map(i=>i.name))??[]},Gn=(t,e)=>{const r=t.introspection.__schema.types.find(n=>"name"in n&&e&&"name"in e&&n.name===e.name);if(!r)throw new Error("Could not find type");return r},ko=(t,e)=>{var r,n;const i=(n=(r=e==null?void 0:e.args)==null?void 0:r.find(o=>o.name===t))==null?void 0:n.type;if(!i)throw new Error(`Could not determine the type of the argument ${t}`);return i},_o=(t,e,r)=>{var n,i;const o="type"in r?r.type:r,s=Gn(t,ze(t,o));return s.kind==="OBJECT"||s.kind==="INTERFACE"?((n=s.fields)==null?void 0:n.find(f=>f.name===e))||null:s.kind==="INPUT_OBJECT"&&((i=s==null?void 0:s.inputFields)==null?void 0:i.find(f=>f.name===e))||null},Io=(t,e,r)=>{var n;const i=qn(t,e),o=(n=i==null?void 0:i.fields)==null?void 0:n.find(s=>s.name===r);if(!o)throw new Error(`Could not find root operation ${r}`);return o},ze=(t,e)=>{var r;if("type"in e)return ze(t,e.type);if(e.kind==="NON_NULL"||e.kind==="LIST")return ze(t,e.ofType);const n=(r=t.introspection.__schema.types)==null?void 0:r.find(i=>"name"in i&&i.name===e.name);if(!n)throw new Error("not found");return n},ur=(t,e)=>{var r;if(e.kind==="NON_NULL")return`${ur(t,e.ofType)}!`;if(e.kind==="LIST")return`[${ur(t,e.ofType)}]`;const n=(r=t.introspection.__schema.types)==null?void 0:r.find(i=>"name"in i&&i.name===e.name);if(!n)throw new Error(`Could not find type ${e.name}`);if(!("name"in n))throw new Error(`Could not determine GraphQL type name for ${e.name}`);return n.name},lr=(t,e=!0,r,n={},i={},o="")=>{var s;const u={},f=e!==!0&&e.select||{},h=e!==!0&&e.variables||{},l={},c=e!==!0&&e.on;if(c&&(u.__typename=!0,u.__on=Object.keys(c).map(d=>{const p=o?`${o}_on_${d}`:`on_${d}`,{query:y,variables:g,variablesValues:m}=lr(t,c[d],Gn(t,{kind:"OBJECT",name:d}),n,i,p);return n={...n,...g},i={...i,...m},{__typeName:d,...y}})),"type"in r&&Object.keys(h).forEach(d=>{const p=o?`${o}_${d}`:d;n[p]=ur(t,ko(d,r)),l[d]=new cr.VariableType(p),i[d]=h[d]}),Object.keys(f).length===0){const d=ze(t,r);d.kind==="OBJECT"&&((s=d.fields)==null||s.forEach(p=>{const y=ze(t,p.type);(y.kind==="SCALAR"||y.kind==="ENUM")&&(u[p.name]=!0)}))}else Object.entries(f).forEach(([d,p])=>{const y=o?`${o}_${d}`:d,g=_o(t,d,r);if(!g)throw new Error(`Field ${d} is not defined`);const{query:m,variables:T,variablesValues:b}=lr(t,p,g,n,i,y);u[d]=m,n={...n,...T},i={...i,...b}});return{query:{...u,__args:l},variables:n,variablesValues:i}},Hn=(t,e,r,n={})=>{if(!t)throw new Error("Schema is not defined");const{query:i,variables:o,variablesValues:s}=lr(t,n,Io(t,e,r));return{query:cr.jsonToGraphQLQuery({[e.toLowerCase()]:{__variables:o,[r]:i}},{pretty:!0}),variables:s}};function xo(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Kn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function Ro(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Kn(n)}catch{}return{query:t,operationName:r}}const e=Kn(t);return{query:Se.print(t),operationName:e}}class Po{constructor(e){const{url:r,adminSecret:n,schema:i}=e;this._url=r,this.accessToken=null,this.adminSecret=n,this.query=Vn(i,"Query").reduce((o,s)=>(o[s]=async u=>{const{query:f,variables:h}=Hn(i,"Query",s,u),{data:l,error:c}=await this.request(f,h);if(c)throw"message"in c?new Error(c.message):new Error(c[0].message);return l[s]},o),{}),this.mutation=Vn(i,"Mutation").reduce((o,s)=>(o[s]=async u=>{const{query:f,variables:h}=Hn(i,"Mutation",s,u),{data:l,error:c}=await this.request(f,h);if(c)throw"message"in c?new Error(c.message):new Error(c[0].message);return l[s]},o),{})}async request(e,...r){const[n,i]=r,o=xo(e,n,i),{headers:s,...u}=i||{},{query:f,operationName:h}=Ro(o.document);try{const l=await Kt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:f,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!l.ok)return{data:null,error:{error:l.statusText,message:l.statusText,status:l.status}};const{data:c,errors:d}=await l.json();return d?{data:null,error:d}:typeof c!="object"||Array.isArray(c)||c===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:c,error:null}}catch(l){const c=l;return{data:null,error:{message:c.message,status:c.name==="AbortError"?0:500,error:c.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function zn(t){const e="subdomain"in t||"backendUrl"in t?At(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Po({url:e,...t})}function Jn(t){const e="subdomain"in t||"backendUrl"in t?At(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Mn({url:e,...t})}const Uo=t=>new Qn(t);class Qn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:f=!0,schema:h,...l}){this.auth=Ln({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:f,...l}),this.storage=Jn({adminSecret:s,...l}),this.functions=$n({adminSecret:s,...l}),this.graphql=zn({adminSecret:s,schema:h,...l}),this.auth.onAuthStateChanged((c,d)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const d=c==null?void 0:c.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}E.AuthClient=tr,E.AuthClientSSR=uo,E.AuthCookieClient=gn,E.CodifiedError=Ge,E.EMAIL_NEEDS_VERIFICATION=en,E.HasuraAuthClient=Pn,E.HasuraStorageApi=Dn,E.HasuraStorageClient=Mn,E.INITIAL_FILE_CONTEXT=bt,E.INITIAL_MACHINE_CONTEXT=yt,E.INVALID_EMAIL_ERROR=ue,E.INVALID_MFA_CODE_ERROR=Jr,E.INVALID_MFA_TICKET_ERROR=Qr,E.INVALID_MFA_TYPE_ERROR=zr,E.INVALID_PASSWORD_ERROR=vt,E.INVALID_PHONE_NUMBER_ERROR=Yt,E.INVALID_REFRESH_TOKEN=tn,E.INVALID_SIGN_IN_METHOD=rn,E.MIN_PASSWORD_LENGTH=Hr,E.NETWORK_ERROR_CODE=Jt,E.NHOST_JWT_EXPIRES_AT_KEY=Ve,E.NHOST_REFRESH_TOKEN_KEY=qe,E.NO_MFA_TICKET_ERROR=Yr,E.NO_REFRESH_TOKEN=Wr,E.NhostClient=Qn,E.NhostFunctionsClient=Fn,E.OTHER_ERROR_CODE=Qt,E.REFRESH_TOKEN_MAX_ATTEMPTS=zt,E.STATE_ERROR_CODE=Pe,E.TOKEN_REFRESHER_RUNNING_ERROR=Xr,E.TOKEN_REFRESH_MARGIN=Kr,E.USER_ALREADY_SIGNED_IN=se,E.USER_NOT_ANONYMOUS=Xi,E.USER_UNAUTHENTICATED=Zr,E.VALIDATION_ERROR_CODE=re,E.activateMfaPromise=fo,E.addSecurityKeyPromise=wn,E.appendImageTransformationParameters=Cn,E.changeEmailPromise=En,E.changePasswordPromise=Sn,E.createAuthClient=Ln,E.createAuthMachine=hn,E.createChangeEmailMachine=pn,E.createChangePasswordMachine=vn,E.createEnableMfaMachine=co,E.createFileUploadMachine=jn,E.createFunctionsClient=$n,E.createGraphqlClient=zn,E.createMultipleFilesUploadMachine=yo,E.createNhostClient=Uo,E.createResetPasswordMachine=yn,E.createSendVerificationEmailMachine=mn,E.createStorageClient=Jn,E.encodeQueryParameters=Xt,E.generateQrCodePromise=lo,E.getAuthenticationResult=ye,E.getFetch=dn,E.getParameterByName=Ke,E.getSession=He,E.isBrowser=Et,E.isValidEmail=de,E.isValidPassword=St,E.isValidPhoneNumber=er,E.isValidTicket=fn,E.localStorageGetter=cn,E.localStorageSetter=un,E.postFetch=le,E.removeParameterFromWindow=Zt,E.resetPasswordPromise=bn,E.rewriteRedirectTo=ne,E.sendVerificationEmailPromise=Tn,E.signInAnonymousPromise=An,E.signInEmailPasswordPromise=On,E.signInEmailPasswordlessPromise=rr,E.signInEmailSecurityKeyPromise=kn,E.signInMfaTotpPromise=_n,E.signInSmsPasswordlessOtpPromise=In,E.signInSmsPasswordlessPromise=nr,E.signOutPromise=xn,E.signUpEmailPasswordPromise=ir,E.signUpEmailSecurityKeyPromise=Rn,E.uploadFilePromise=mo,E.uploadMultipleFilesPromise=go,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
|
|
22
22
|
//# sourceMappingURL=nhost-js.umd.js.map
|