@nhost/nhost-js 3.0.5 → 3.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/umd/nhost-js.umd.js +8 -8
- package/umd/nhost-js.umd.js.map +1 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(y,
|
|
1
|
+
(function(y,Se){typeof exports=="object"&&typeof module!="undefined"?Se(exports,require("graphql")):typeof define=="function"&&define.amd?define(["exports","graphql"],Se):(y=typeof globalThis!="undefined"?globalThis:y||self,Se(y["@nhost/nhost-js"]={},y.graphql))})(this,function(y,Se){"use strict";new TextEncoder;const pr=new TextDecoder,ei=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},ti=t=>{let e=t;e instanceof Uint8Array&&(e=pr.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ei(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class ri extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(e){var r;super(e),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}class ve extends ri{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}}function ni(t){return typeof t=="object"&&t!==null}function ii(t){if(!ni(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}const si=ti;function oi(t){if(typeof t!="string")throw new ve("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=t.split(".");if(r===5)throw new ve("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ve("Invalid JWT");if(!e)throw new ve("JWTs must contain a payload");let n;try{n=si(e)}catch{throw new ve("Failed to base64url decode the payload")}let i;try{i=JSON.parse(pr.decode(n))}catch{throw new ve("Failed to parse the decoded payload as JSON")}if(!ii(i))throw new ve("Invalid JWT Claims Set");return i}/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -11,11 +11,11 @@
|
|
|
11
11
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
12
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
13
|
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},m.apply(this,arguments)};function Pt(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 _(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function B(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 L;(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"})(L||(L={}));var fe;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(fe||(fe={}));var Ze=L.Start,et=L.Stop,Se=L.Raise,Me=L.Send,_t=L.Cancel,pr=L.NullEvent,tt=L.Assign,ei=L.After,ti=L.DoneState,rt=L.Log,vr=L.Init,nt=L.Invoke,ri=L.ErrorExecution,Nt=L.ErrorPlatform,Ut=L.ErrorCustom,it=L.Update,yr=L.Choose,mr=L.Pure;const ni=Object.freeze(Object.defineProperty({__proto__:null,after:ei,assign:tt,cancel:_t,choose:yr,doneState:ti,error:Ut,errorExecution:ri,errorPlatform:Nt,init:vr,invoke:nt,log:rt,nullEvent:pr,pure:mr,raise:Se,send:Me,start:Ze,stop:et,update:it},Symbol.toStringTag,{value:"Module"}));var gr=".",wr={},Dt="xstate.guard",ii="",V=process.env.NODE_ENV==="production",st;function Ct(t,e,r){r===void 0&&(r=gr);var n=Le(t,r),i=Le(e,r);return U(i)?U(n)?i===n:!1:U(n)?n in i:Object.keys(n).every(function(s){return s in i?Ct(n[s],i[s]):!1})}function Er(t){try{return U(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Mt(t,e){try{return be(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function si(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Le(t,e){if(si(t))return t.value;if(be(t))return ot(t);if(typeof t!="string")return t;var r=Mt(t,e);return ot(r)}function ot(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 Tr(t,e,r){var n,i,s={};try{for(var o=R(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,f=t[c];r(f)&&(s[c]=e(f,c,t))}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var oi=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 u=o.value;i=i[u]}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function ai(t,e){return function(r){var n,i,s=r;try{for(var o=R(t),u=o.next();!u.done;u=o.next()){var c=u.value;s=s[e][c]}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function at(t){if(!t)return[[]];if(U(t))return[[t]];var e=H(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:at(t[r]).map(function(i){return[r].concat(i)})}));return e}function H(t){var e;return(e=[]).concat.apply(e,B([],_(t),!1))}function Sr(t){return be(t)?t:[t]}function re(t){return t===void 0?[]:Sr(t)}function ct(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=R(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,f=t[c];N(f)?s[c]=f(e,r.data):s[c]=f}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function ci(t){return/^(done|error)\./.test(t)}function br(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function ui(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function li(t,e){var r,n,i=_([[],[]],2),s=i[0],o=i[1];try{for(var u=R(t),c=u.next();!c.done;c=u.next()){var f=c.value;e(f)?s.push(f):o.push(f)}}catch(a){r={error:a}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[s,o]}function Ar(t,e){return je(t.states,function(r,n){if(r){var i=(U(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:Ar(r,i)}}})}function di(t,e){return{current:e,states:Ar(t,e)}}function kr(t,e,r,n){V||J(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var u,c,f=o.assignment,a={state:n,action:o,_event:e},l={};if(N(f))l=f(s,e.data,a);else try{for(var d=R(Object.keys(f)),h=d.next();!h.done;h=d.next()){var v=h.value,w=f[v];l[v]=N(w)?w(s,e.data,a):w}}catch(S){u={error:S}}finally{try{h&&!h.done&&(c=d.return)&&c.call(d)}finally{if(u)throw u.error}}return Object.assign({},s,l)},t);return i}var J=function(){};V||(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 N(t){return typeof t=="function"}function U(t){return typeof t=="string"}function Or(t,e){if(t)return U(t)?{type:Dt,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Dt,name:t.name,predicate:t}:t}function fi(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var he=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();st={},st[he]=function(){return this},st[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function hi(t){return!!t&&typeof t.send=="function"}var pi=function(){var t=0;return function(){return t++,t.toString(16)}}();function ut(t,e){return U(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!U(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=ut(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function Ae(t,e){var r=Sr(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||ae(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function vi(t){if(!(t===void 0||t===ii))return re(t)}function yi(t,e,r){if(!V){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function Ir(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Dt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var u=s==null?void 0:s[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,o)}function xr(t){return typeof t=="string"?{type:t}:t}function lt(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 dt(t,e){return"".concat(t,":invocation[").concat(e,"]")}function Lt(t){return(t.type===Se||t.type===Me&&t.to===fe.Internal)&&typeof t.delay!="number"}var ve=Q({type:vr});function ft(t,e){return e&&e[t]||void 0}function ke(t,e){var r;if(U(t)||typeof t=="number"){var n=ft(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=ft(t.type,e);if(N(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=be(t)?t:[t];return r.map(function(n){return ke(n,e)})};function ht(t){var e=ke(t);return m(m({id:U(t)?t:e.id},e),{type:e.type})}function Rr(t,e){return{type:Se,event:typeof t=="function"?t:ut(t),delay:e?e.delay:void 0,id:e==null?void 0:e.id}}function Pr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;return m(m({},t),{type:Se,_event:s,delay:o})}function ye(t,e){return{to:e?e.to:void 0,type:Me,event:N(t)?t:ut(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:Er(t)}}function _r(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var c=N(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:c,_event:s,event:s.data,delay:o})}function jt(t,e){return ye(t,m(m({},e),{to:fe.Parent}))}function mi(t,e,r){return ye(e,m(m({},r),{to:t}))}function gi(){return jt(it)}function wi(t,e){return ye(t,m(m({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var Ei=function(t,e){return{context:t,event:e}};function Ti(t,e){return t===void 0&&(t=Ei),{type:rt,label:e,expr:t}}var Nr=function(t,e,r){return m(m({},t),{value:U(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Ur=function(t){return{type:_t,sendId:t}};function Dr(t){var e=ht(t);return{type:L.Start,activity:e,exec:void 0}}function Cr(t){var e=N(t)?t:ht(t);return{type:L.Stop,activity:e,exec:void 0}}function Mr(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:L.Stop,activity:i};return s}var Lr=function(t){return{type:tt,assignment:t}};function Si(t){return typeof t=="object"&&"type"in t}function jr(t,e){var r=e?"#".concat(e):"";return"".concat(L.After,"(").concat(t,")").concat(r)}function $e(t,e){var r="".concat(L.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Fe(t,e){var r="".concat(L.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Oe(t,e){var r="".concat(L.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function bi(t){return{type:L.Pure,get:t}}function Ai(t,e){if(!V&&(!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,B([],_(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 ye(function(n,i){return i},m(m({},e),{to:t}))}function ki(t,e){return jt(function(r,n,i){return{type:Ut,data:N(t)?t(r,n,i):t}},m(m({},e),{to:fe.Parent}))}function Oi(t){return{type:L.Choose,conds:t}}var Ii=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,u=0;u<o.actions.length;){if(o.actions[u].type===tt){n.push(o.actions[u]),o.actions.splice(u,1);continue}u++}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function qe(t,e,r,n,i,s,o){o===void 0&&(o=!1);var u=o?[]:Ii(i),c=u.length?kr(r,n,u,e):r,f=o?[r]:void 0,a=[];function l(v,w){var S;switch(w.type){case Se:{var E=Pr(w,c,n,t.options.delays);return s&&typeof E.delay=="number"&&s(E,c,n),E}case Me:var T=_r(w,c,n,t.options.delays);if(!V){var b=w.delay;J(!U(b)||typeof T.delay=="number","No delay reference for delay expression '".concat(b,"' was found on machine '").concat(t.id,"'"))}return s&&T.to!==fe.Internal&&(v==="entry"?a.push(T):s(T,c,n)),T;case rt:{var O=Nr(w,c,n);return s==null||s(O,c,n),O}case yr:{var $=w,C=(S=$.conds.find(function(p){var g=Or(p.cond,t.options.guards);return!g||Ir(t,g,c,n,s?void 0:e)}))===null||S===void 0?void 0:S.actions;if(!C)return[];var P=_(qe(t,e,c,n,[{type:v,actions:ce(re(C),t.options.actions)}],s,o),2),j=P[0],x=P[1];return c=x,f==null||f.push(c),j}case mr:{var C=w.get(c,n.data);if(!C)return[];var K=_(qe(t,e,c,n,[{type:v,actions:ce(re(C),t.options.actions)}],s,o),2),k=K[0],F=K[1];return c=F,f==null||f.push(c),k}case et:{var O=Mr(w,c,n);return s==null||s(O,r,n),O}case tt:{c=kr(c,n,[w],s?void 0:e),f==null||f.push(c);break}default:var z=ke(w,t.options.actions),G=z.exec;if(s)s(z,c,n);else if(G&&f){var we=f.length-1,Ee=m(m({},z),{exec:function(p){for(var g=[],A=1;A<arguments.length;A++)g[A-1]=arguments[A];G.apply(void 0,B([f[we]],_(g),!1))}});z=Ee}return z}}function d(v){var w,S,E=[];try{for(var T=R(v.actions),b=T.next();!b.done;b=T.next()){var O=b.value,$=l(v.type,O);$&&(E=E.concat($))}}catch(C){w={error:C}}finally{try{b&&!b.done&&(S=T.return)&&S.call(T)}finally{if(w)throw w.error}}return a.forEach(function(C){s(C,c,n)}),a.length=0,E}var h=H(i.map(d));return[h,c]}const xi=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:ni,after:jr,assign:Lr,cancel:Ur,choose:Oi,done:$e,doneInvoke:Fe,error:Oe,escalate:ki,forwardTo:Ai,getActionFunction:ft,initEvent:ve,isActionObject:Si,log:Ti,pure:bi,raise:Rr,resolveActions:qe,resolveLog:Nr,resolveRaise:Pr,resolveSend:_r,resolveStop:Mr,respond:wi,send:ye,sendParent:jt,sendTo:mi,sendUpdate:gi,start:Dr,stop:Cr,toActionObject:ke,toActionObjects:ce,toActivityDefinition:ht},Symbol.toStringTag,{value:"Module"}));var pt=[],Ie=function(t,e){pt.push(t);var r=e(t);return pt.pop(),r},Ri=function(t){return t(pt[pt.length-1])};function $r(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[he]=function(){return this},e}function Pi(t,e,r,n){var i,s=xr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],u=t.data?ct(t.data,r,n):void 0,c=o?$t(o,t.id,u):$r(t.id);return c.meta=t,c}function $t(t,e,r){var n=$r(e);if(n.deferred=!0,ae(t)){var i=n.state=Ie(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function _i(t){try{return typeof t.send=="function"}catch{return!1}}function Ni(t){return _i(t)&&"id"in t}function Ui(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[he]=function(){return this},e),t)}var vt=function(t){return t.type==="atomic"||t.type==="final"};function Fr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Be(t){return Fr(t).filter(function(e){return e.type!=="history"})}function qr(t){var e=[t];return vt(t)?e:e.concat(H(Be(t).map(qr)))}function Ge(t,e){var r,n,i,s,o,u,c,f,a=new Set(t),l=Ft(a),d=new Set(e);try{for(var h=R(d),v=h.next();!v.done;v=h.next())for(var w=v.value,S=w.parent;S&&!d.has(S);)d.add(S),S=S.parent}catch(x){r={error:x}}finally{try{v&&!v.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}var E=Ft(d);try{for(var T=R(d),b=T.next();!b.done;b=T.next()){var w=b.value;if(w.type==="compound"&&(!E.get(w)||!E.get(w).length))l.get(w)?l.get(w).forEach(function(K){return d.add(K)}):w.initialStateNodes.forEach(function(K){return d.add(K)});else if(w.type==="parallel")try{for(var O=(o=void 0,R(Be(w))),$=O.next();!$.done;$=O.next()){var C=$.value;d.has(C)||(d.add(C),l.get(C)?l.get(C).forEach(function(K){return d.add(K)}):C.initialStateNodes.forEach(function(K){return d.add(K)}))}}catch(K){o={error:K}}finally{try{$&&!$.done&&(u=O.return)&&u.call(O)}finally{if(o)throw o.error}}}}catch(x){i={error:x}}finally{try{b&&!b.done&&(s=T.return)&&s.call(T)}finally{if(i)throw i.error}}try{for(var P=R(d),j=P.next();!j.done;j=P.next())for(var w=j.value,S=w.parent;S&&!d.has(S);)d.add(S),S=S.parent}catch(x){c={error:x}}finally{try{j&&!j.done&&(f=P.return)&&f.call(P)}finally{if(c)throw c.error}}return d}function Br(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(vt(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Br(s,e)}),i}function Ft(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(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Di(t,e){var r=Ge([t],e);return Br(t,Ft(r))}function Ve(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Ci(t){return B([],_(new Set(H(B([],_(t.map(function(e){return e.ownEvents})),!1)))),!1)}function yt(t,e){return e.type==="compound"?Be(e).some(function(r){return r.type==="final"&&Ve(t,r)}):e.type==="parallel"?Be(e).every(function(r){return yt(t,r)}):!1}function Mi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Gr(t){return new Set(H(t.map(function(e){return e.tags})))}function Vr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(U(t)||U(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Vr(t[i],e[i])})}function Li(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function ji(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=wr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||wr,this.meta=Mi(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 Ci(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=ve;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=ve;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),U(e))return[e];var i=Object.keys(e);return i.concat.apply(i,B([],_(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=Pt(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Ct(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;V&&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}(),$i={deferEvents:!1},Hr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},$i),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}(),qt=new Map,Fi=0,He={bookId:function(){return"x:".concat(Fi++)},register:function(t,e){return qt.set(t,e),t},get:function(t){return qt.get(t)},free:function(t){qt.delete(t)}};function Bt(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;V||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 qi(){var t=Bt();if(t&&"__xstate__"in t)return t.__xstate__}function Bi(t){if(Bt()){var e=qi();e&&e.register(t)}}function Gi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,c),n.forEach(function(a){return a.next(r)})}s=!1}},u=Ui({id:e.id,send:function(f){i.push(f),o()},getSnapshot:function(){return r},subscribe:function(f,a,l){var d=lt(f,a,l);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),c={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(c):r,u}var Gt={sync:!1,autoForward:!1},W;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(W||(W={}));var Vi=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=W.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(a,l){if(be(a))return n.batch(a),n.state;var d=Q(ut(a,l));if(n.status===W.Stopped)return V||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!==
|
|
16
|
-
Event: `).concat(JSON.stringify(d.data)));return n.scheduler.schedule(function(){n.forward(d);var h=n._nextState(d);n.update(h,d)}),n._state},this.sendTo=function(a,l,d){var h=n.parent&&(l===fe.Parent||n.parent.id===l),v=h?n.parent:U(l)?l===fe.Internal?n:n.children.get(l)||
|
|
17
|
-
Event: `).concat(JSON.stringify(event)));else if(this.status!==W.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,u=!1,c=[],f=function(h){var v=Q(h);r.forward(v),o=Ie(r,function(){return r.machine.transition(o,v,void 0,n||void 0)}),c.push.apply(c,B([],_(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(w){return ji(w,o)})),!1)),u=u||!!o.changed};try{for(var a=R(e),l=a.next();!l.done;l=a.next()){var d=l.value;f(d)}}catch(h){i={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}o.changed=u,o.actions=c,r.update(o,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(Nt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(Nt)===0}))throw i.data.data;var s=Ie(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=R(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,u=this.children.get(o);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));u.send(e)}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this,n=this.clock.setTimeout(function(){"to"in e&&e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay);e.id&&(this.delayedEventsMap[e.id]=n)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==W.Running)return $t(e,r);if(br(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(Ni(e))return this.spawnActor(e,r);if(fi(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(ui(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),s=m(m({},Gt),r);s.sync&&i.onTransition(function(u){n.send(it,{state:u,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Gi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(c){s||(o=c,i.removeChild(r),i.send(Q(Fe(r,c),{origin:r})))},function(c){if(!s){i.removeChild(r);var f=Oe(r,c);try{i.send(Q(f,{origin:r}))}catch(a){yi(c,a,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(c,f,a){var l=lt(c,f,a),d=!1;return e.then(function(h){d||(l.next(h),!d&&l.complete())},function(h){d||l.error(h)}),{unsubscribe:function(){return d=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,u=new Set,c,f=function(d){c=d,u.forEach(function(h){return h(d)}),!s&&i.send(Q(d,{origin:r}))},a;try{a=e(f,function(d){o.add(d)})}catch(d){this.send(Oe(r,d))}if(br(a))return this.spawnPromise(a,r);var l=(n={id:r,send:function(d){return o.forEach(function(h){return h(d)})},subscribe:function(d){var h=lt(d);return u.add(h.next),{unsubscribe:function(){u.delete(h.next)}}},stop:function(){s=!0,N(a)&&a()},toJSON:function(){return{id:r}},getSnapshot:function(){return c}},n[he]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(c){s=c,i.send(Q(c,{origin:r}))},function(c){i.removeChild(r),i.send(Q(Oe(r,c),{origin:r}))},function(){i.removeChild(r),i.send(Q(Fe(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(c,f,a){return e.subscribe(c,f,a)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){V||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=Bt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Bi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[he]=function(){return this},t.prototype.getSnapshot=function(){return this.status===W.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=xe,t}(),Hi=function(t){return U(t)?m(m({},Gt),{name:t}):m(m(m({},Gt),{name:pi()}),t)};function Ki(t,e){var r=Hi(e);return Ri(function(n){if(!V){var i=ae(t)||N(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):$t(t,r.name)})}function xe(t,e){var r=new Vi(t,e);return r}function zi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function mt(t){return m(m({type:nt},t),{toJSON:function(){t.onDone,t.onError;var e=Pt(t,["onDone","onError"]);return m(m({},e),{type:nt,src:zi(t.src)})}})}var Re="",Vt="#",Ke="*",Pe={},_e=function(t){return t[0]===Vt},Wi=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Yi=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(U(s.target)||ae(s.target))}),i=e===Re?"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 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(Wi(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:gr),this.id=this.config.id||B([this.machine.key],_(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,V||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?je(this.config.states,function(f,a){var l,d=new t(f,{},void 0,{parent:s,key:a});return Object.assign(s.idMap,m((l={},l[d.id]=d,l),d.idMap)),d}):Pe;var u=0;function c(f){var a,l;f.order=u++;try{for(var d=R(Fr(f)),h=d.next();!h.done;h=d.next()){var v=h.value;c(v)}}catch(w){a={error:w}}finally{try{h&&!h.done&&(l=d.return)&&l.call(d)}finally{if(a)throw a.error}}}c(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(f){var a=f.event;return a===Re}):Re in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=re(this.config.entry||this.config.onEntry).map(function(f){return ke(f)}),this.onExit=re(this.config.exit||this.config.onExit).map(function(f){return ke(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=re(this.config.invoke).map(function(f,a){var l,d;if(ae(f)){var h=dt(s.id,a);return s.machine.options.services=m((l={},l[h]=f,l),s.machine.options.services),mt({src:h,id:h})}else if(U(f.src)){var h=f.id||dt(s.id,a);return mt(m(m({},f),{id:h,src:f.src}))}else if(ae(f.src)||N(f.src)){var h=f.id||dt(s.id,a);return s.machine.options.services=m((d={},d[h]=f.src,d),s.machine.options.services),mt(m(m({id:h},f),{src:h}))}else{var v=f.src;return mt(m(m({id:dt(s.id,a)},f),{src:v}))}}),this.activities=re(this.config.activities).concat(this.invoke).map(function(f){return ht(f)}),this.transition=this.transition.bind(this),this.tags=re(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||qr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,u=n.services,c=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},s),e.activities),guards:m(m({},o),e.guards),services:m(m({},u),e.services),delays:m(m({},c),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states: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===Re,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===Ke});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var u=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,c=jr(u,e.id);return e.onEntry.push(ye(c,{delay:s})),e.onExit.push(Ur(c)),c},i=be(r)?r.map(function(s,o){var u=n(s.delay,o);return m(m({},s),{event:u})}):H(Object.keys(r).map(function(s,o){var u=r[s],c=U(u)?{target:u}:u,f=isNaN(+s)?s:+s,a=n(f,o);return re(c).map(function(l){return m(m({},l),{event:a,delay:f})})}));return i.map(function(s){var o=s.delay;return m(m({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:Le(e,this.delimiter);if(U(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),u=[this];return u.push.apply(u,B([],_(H(o.map(function(c){return n.getStateNode(c).getStateNodes(i[c])}))),!1)),u},t.prototype.handles=function(e){var r=Er(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from(Ge([],this.getStateNodes(r.value)));return new oe(m(m({},r),{value:this.resolve(r.value),configuration:n,done:yt(n,this),tags:Gr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var u=R(Object.keys(e)),c=u.next();!c.done;c=u.next()){var f=c.value,a=e[f];if(a){var l=this.getStateNode(f),d=l._transition(a,r,n);d&&(o[f]=d)}}}catch(E){i={error:E}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(i)throw i.error}}var h=Object.keys(o).map(function(E){return o[E]}),v=H(h.map(function(E){return E.transitions})),w=h.some(function(E){return E.transitions.length>0});if(!w)return this.next(r,n);var S=H(Object.keys(o).map(function(E){return o[E].configuration}));return{transitions:v,exitSet:H(h.map(function(E){return E.exitSet})),configuration:S,source:r,actions:H(Object.keys(o).map(function(E){return o[E].actions}))}},t.prototype._transition=function(e,r,n){return U(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,u=[],c=[],f;try{for(var a=R(this.getCandidates(o)),l=a.next();!l.done;l=a.next()){var d=l.value,h=d.cond,v=d.in,w=e.context,S=v?U(v)&&_e(v)?e.matches(Le(this.getStateNodeById(v).path,this.delimiter)):Ct(Le(v,this.delimiter),oi(this.path.slice(0,-2))(e.value)):!0,E=!1;try{E=!h||Ir(this.machine,h,w,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(h.name||h.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
-
`).concat(O.message))}if(E&&S){d.target!==void 0&&(c=d.target),u.push.apply(u,B([],_(d.actions),!1)),f=d;break}}}catch(O){n={error:O}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}if(f){if(!c.length)return{transitions:[f],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var T=H(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),b=!!f.internal;return{transitions:[f],exitSet:b?[]:H(c.map(function(O){return s.getPotentiallyReenteringNodes(O)})),configuration:T,source:e,actions:u}}},t.prototype.getPotentiallyReenteringNodes=function(e){if(this.order<e.order)return[this];for(var r=[],n=this,i=e;n&&n!==i;)r.push(n),n=n.parent;return n!==i?[]:(r.push(i),r)},t.prototype.getActions=function(e,r,n,i,s,o,u){var c,f,a,l,d=this,h=o?Ge([],this.getStateNodes(o.value)):[],v=new Set;try{for(var w=R(Array.from(e).sort(function(k,F){return k.order-F.order})),S=w.next();!S.done;S=w.next()){var E=S.value;(!Ve(h,E)||Ve(n.exitSet,E)||E.parent&&v.has(E.parent))&&v.add(E)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(f=w.return)&&f.call(w)}finally{if(c)throw c.error}}try{for(var T=R(h),b=T.next();!b.done;b=T.next()){var E=b.value;(!Ve(e,E)||Ve(n.exitSet,E.parent))&&n.exitSet.push(E)}}catch(k){a={error:k}}finally{try{b&&!b.done&&(l=T.return)&&l.call(T)}finally{if(a)throw a.error}}n.exitSet.sort(function(k,F){return F.order-k.order});var O=Array.from(v).sort(function(k,F){return k.order-F.order}),$=new Set(n.exitSet),C=H(O.map(function(k){var F=[];if(k.type!=="final")return F;var z=k.parent;if(!z.parent)return F;F.push($e(k.id,k.doneData),$e(z.id,k.doneData?ct(k.doneData,i,s):void 0));var G=z.parent;return G.type==="parallel"&&Be(G).every(function(we){return yt(n.configuration,we)})&&F.push($e(G.id)),F})),P=O.map(function(k){var F=k.onEntry,z=k.activities.map(function(G){return Dr(G)});return{type:"entry",actions:ce(u?B(B([],_(F),!1),_(z),!1):B(B([],_(z),!1),_(F),!1),d.machine.options.actions)}}).concat({type:"state_done",actions:C.map(function(k){return Rr(k)})}),j=Array.from($).map(function(k){return{type:"exit",actions:ce(B(B([],_(k.onExit),!1),_(k.activities.map(function(F){return Cr(F)})),!1),d.machine.options.actions)}}),x=j.concat({type:"transition",actions:ce(n.actions,this.machine.options.actions)}).concat(P);if(r){var K=ce(H(B([],_(e),!1).sort(function(k,F){return F.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return!Lt(k)});return x.concat({type:"stop",actions:K})}return x},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=Q(r),o;if(e instanceof oe)o=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=U(e)?this.resolve(ot(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(oe.from(u,c))}if(!V&&s.name===Ke)throw new Error("An event cannot have the wildcard type ('".concat(Ke,"')"));if(this.strict&&!this.events.includes(s.name)&&!ci(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var f=this._transition(o.value,o,s)||{transitions:[],configuration:[],exitSet:[],source:o,actions:[]},a=Ge([],this.getStateNodes(o.value)),l=f.configuration.length?Ge(a,f.configuration):a;return f.configuration=B([],_(l),!1),this.resolveTransition(f,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,B([],_(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,u,c,f,a=this;s===void 0&&(s=ve);var l=e.configuration,d=!r||e.transitions.length>0,h=d?e.configuration:r?r.configuration:[],v=yt(h,this),w=d?Di(this.machine,l):void 0,S=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(h),v,e,n,s,r,i),T=r?m({},r.activities):{};try{for(var b=R(E),O=b.next();!O.done;O=b.next()){var $=O.value;try{for(var C=(c=void 0,R($.actions)),P=C.next();!P.done;P=C.next()){var j=P.value;j.type===Ze?T[j.activity.id||j.activity.type]=j:j.type===et&&(T[j.activity.id||j.activity.type]=!1)}}catch(ee){c={error:ee}}finally{try{P&&!P.done&&(f=C.return)&&f.call(C)}finally{if(c)throw c.error}}}}catch(ee){o={error:ee}}finally{try{O&&!O.done&&(u=b.return)&&u.call(b)}finally{if(o)throw o.error}}var x=_(qe(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),K=x[0],k=x[1],F=_(li(K,Lt),2),z=F[0],G=F[1],we=K.filter(function(ee){var Y;return ee.type===Ze&&((Y=ee.activity)===null||Y===void 0?void 0:Y.type)===nt}),Ee=we.reduce(function(ee,Y){return ee[Y.activity.id]=Pi(Y.activity,a.machine,k,s),ee},r?m({},r.children):{}),p=new oe({value:w||r.value,context:k,_event:s,_sessionid:r?r._sessionid:null,historyValue:w?S?di(S,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?G:[],activities:w?T:r?r.activities:{},events:[],configuration:h,transitions:e.transitions,children:Ee,done:v,tags:Gr(h),machine:this}),g=n!==k;p.changed=s.name===it||g;var A=p.history;A&&delete A.history;var q=!v&&(this._transient||l.some(function(ee){return ee._transient}));if(!d&&(!q||s.name===Re))return p;var D=p;if(!v)for(q&&(D=this.resolveRaisedTransition(D,{type:pr},s,i));z.length;){var M=z.shift();D=this.resolveRaisedTransition(D,M._event,s,i)}var Ce=D.changed||(A?!!D.actions.length||g||typeof A.value!=typeof D.value||!Vr(D.value,A.value):void 0);return D.changed=Ce,D.history=A,D},t.prototype.getStateNode=function(e){if(_e(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=_e(e)?e.slice(Vt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&_e(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Mt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Pe;switch(this.type){case"parallel":return je(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Pe});case"compound":if(U(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?je(e,function(s,o){return s?n.getStateNode(o).resolve(s):Pe}):this.initialStateValue||{};default:return e||Pe}},t.prototype.getResolvedPath=function(e){if(_e(e)){var r=this.machine.idMap[e.slice(Vt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Mt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=Tr(this.states,function(n){return n.initialStateValue||Pe},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=vt(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,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;U(r.target)?e=_e(r.target)?ot(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(vt(this))return[this];if(this.type==="compound"&&!this.initial)return V||J(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=at(this.initialStateValue);return H(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=_(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:Tr(this.states,function(r,n){if(!e)return r.historyValue();var i=U(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?H(at(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=ai(n.path,"states")(e).current;return U(s)?[n.getStateNode(s)]:H(at(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=H(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var u=R(Object.keys(s)),c=u.next();!c.done;c=u.next()){var f=c.value,a=s[f];if(a.states)try{for(var l=(n=void 0,R(a.events)),d=l.next();!d.done;d=l.next()){var h=d.value;o.add("".concat(h))}}catch(v){n={error:v}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!U(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(u.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=vi(e.target),i="internal"in e?e.internal:n?n.some(function(c){return U(c)&&c[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),u=m(m({},e),{actions:ce(re(e.actions)),cond:Or(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(c){return"#".concat(c.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=Ke,u=s[o],c=u===void 0?[]:u,f=Pt(s,[typeof o=="symbol"?o:o+""]);i=H(Object.keys(f).map(function(T){!V&&T===Re&&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 b=Ae(T,f[T]);return V||Yi(n,T,b),b}).concat(Ae(Ke,c)))}var a=this.config.always?Ae("",this.config.always):[],l=this.config.onDone?Ae(String($e(this.id)),this.config.onDone):[];V||J(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=H(this.invoke.map(function(T){var b=[];return T.onDone&&b.push.apply(b,B([],_(Ae(String(Fe(T.id)),T.onDone)),!1)),T.onError&&b.push.apply(b,B([],_(Ae(String(Oe(T.id)),T.onError)),!1)),b})),h=this.after,v=H(B(B(B(B([],_(l),!1),_(d),!1),_(i),!1),_(a),!1).map(function(T){return re(T).map(function(b){return n.formatTransition(b)})}));try{for(var w=R(h),S=w.next();!S.done;S=w.next()){var E=S.value;v.push(E)}}catch(T){e={error:T}}finally{try{S&&!S.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),Kr=!1;function pe(t,e){return!V&&!("predictableActionArguments"in t)&&!Kr&&(Kr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Ji(t,e)}var I=Lr,X=ye;/*! js-cookie v3.0.5 | MIT */function gt(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 Xi={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 Ht(t,e){function r(i,s,o){if(typeof document!="undefined"){o=gt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var c in o)o[c]&&(u+="; "+c,o[c]!==!0&&(u+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+u}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},u=0;u<s.length;u++){var c=s[u].split("="),f=c.slice(1).join("=");try{var a=decodeURIComponent(c[0]);if(o[a]=t.read(f,a),i===a)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",gt({},s,{expires:-1}))},withAttributes:function(i){return Ht(this.converter,gt({},this.attributes,i))},withConverter:function(i){return Ht(gt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Kt=Ht(Xi,{path:"/"}),zt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Qi(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Yt={exports:{}};(function(t,e){(function(r){function n(i){var s=i&&i.Promise||r.Promise,o=i&&i.XMLHttpRequest||r.XMLHttpRequest;return function(){var u=Object.create(r,{fetch:{value:void 0,writable:!0}});return function(c,f){f(e)}(this,function(c){var f=typeof u!="undefined"&&u||typeof self!="undefined"&&self||typeof f!="undefined"&&f,a={searchParams:"URLSearchParams"in f,iterable:"Symbol"in f&&"iterator"in Symbol,blob:"FileReader"in f&&"Blob"in f&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in f,arrayBuffer:"ArrayBuffer"in f};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(a.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(p){return p&&d.indexOf(Object.prototype.toString.call(p))>-1};function v(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function w(p){return typeof p!="string"&&(p=String(p)),p}function S(p){var g={next:function(){var A=p.shift();return{done:A===void 0,value:A}}};return a.iterable&&(g[Symbol.iterator]=function(){return g}),g}function E(p){this.map={},p instanceof E?p.forEach(function(g,A){this.append(A,g)},this):Array.isArray(p)?p.forEach(function(g){this.append(g[0],g[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(g){this.append(g,p[g])},this)}E.prototype.append=function(p,g){p=v(p),g=w(g);var A=this.map[p];this.map[p]=A?A+", "+g:g},E.prototype.delete=function(p){delete this.map[v(p)]},E.prototype.get=function(p){return p=v(p),this.has(p)?this.map[p]:null},E.prototype.has=function(p){return this.map.hasOwnProperty(v(p))},E.prototype.set=function(p,g){this.map[v(p)]=w(g)},E.prototype.forEach=function(p,g){for(var A in this.map)this.map.hasOwnProperty(A)&&p.call(g,this.map[A],A,this)},E.prototype.keys=function(){var p=[];return this.forEach(function(g,A){p.push(A)}),S(p)},E.prototype.values=function(){var p=[];return this.forEach(function(g){p.push(g)}),S(p)},E.prototype.entries=function(){var p=[];return this.forEach(function(g,A){p.push([A,g])}),S(p)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function T(p){if(p.bodyUsed)return s.reject(new TypeError("Already read"));p.bodyUsed=!0}function b(p){return new s(function(g,A){p.onload=function(){g(p.result)},p.onerror=function(){A(p.error)}})}function O(p){var g=new FileReader,A=b(g);return g.readAsArrayBuffer(p),A}function $(p){var g=new FileReader,A=b(g);return g.readAsText(p),A}function C(p){for(var g=new Uint8Array(p),A=new Array(g.length),q=0;q<g.length;q++)A[q]=String.fromCharCode(g[q]);return A.join("")}function P(p){if(p.slice)return p.slice(0);var g=new Uint8Array(p.byteLength);return g.set(new Uint8Array(p)),g.buffer}function j(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:a.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:a.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():a.arrayBuffer&&a.blob&&l(p)?(this._bodyArrayBuffer=P(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||h(p))?this._bodyArrayBuffer=P(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return s.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return s.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=T(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?s.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):s.resolve(this._bodyArrayBuffer))}else return this.blob().then(O)}),this.text=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(C(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return s.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(F)}),this.json=function(){return this.text().then(JSON.parse)},this}var x=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function K(p){var g=p.toUpperCase();return x.indexOf(g)>-1?g:p}function k(p,g){if(!(this instanceof k))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');g=g||{};var A=g.body;if(p instanceof k){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,g.headers||(this.headers=new E(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!A&&p._bodyInit!=null&&(A=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=g.credentials||this.credentials||"same-origin",(g.headers||!this.headers)&&(this.headers=new E(g.headers)),this.method=K(g.method||this.method||"GET"),this.mode=g.mode||this.mode||null,this.signal=g.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(g.cache==="no-store"||g.cache==="no-cache")){var q=/([?&])_=[^&]*/;if(q.test(this.url))this.url=this.url.replace(q,"$1_="+new Date().getTime());else{var D=/\?/;this.url+=(D.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}k.prototype.clone=function(){return new k(this,{body:this._bodyInit})};function F(p){var g=new FormData;return p.trim().split("&").forEach(function(A){if(A){var q=A.split("="),D=q.shift().replace(/\+/g," "),M=q.join("=").replace(/\+/g," ");g.append(decodeURIComponent(D),decodeURIComponent(M))}}),g}function z(p){var g=new E,A=p.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(q){return q.indexOf(`
|
|
20
|
-
`)===0?q.substr(1,q.length):q}).forEach(function(q){var D=q.split(":"),M=D.shift().trim();if(M){var Ce=D.join(":").trim();g.append(M,Ce)}}),g}j.call(k.prototype);function G(p,g){if(!(this instanceof G))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');g||(g={}),this.type="default",this.status=g.status===void 0?200:g.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in g?g.statusText:"",this.headers=new E(g.headers),this.url=g.url||"",this._initBody(p)}j.call(G.prototype),G.prototype.clone=function(){return new G(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},G.error=function(){var p=new G(null,{status:0,statusText:""});return p.type="error",p};var we=[301,302,303,307,308];G.redirect=function(p,g){if(we.indexOf(g)===-1)throw new RangeError("Invalid status code");return new G(null,{status:g,headers:{location:p}})},c.DOMException=f.DOMException;try{new c.DOMException}catch{c.DOMException=function(g,A){this.message=g,this.name=A;var q=Error(g);this.stack=q.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function Ee(p,g){return new s(function(A,q){var D=new k(p,g);if(D.signal&&D.signal.aborted)return q(new c.DOMException("Aborted","AbortError"));var M=new o;function Ce(){M.abort()}M.onload=function(){var Y={status:M.status,statusText:M.statusText,headers:z(M.getAllResponseHeaders()||"")};Y.url="responseURL"in M?M.responseURL:Y.headers.get("X-Request-URL");var xt="response"in M?M.response:M.responseText;setTimeout(function(){A(new G(xt,Y))},0)},M.onerror=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},M.ontimeout=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},M.onabort=function(){setTimeout(function(){q(new c.DOMException("Aborted","AbortError"))},0)};function ee(Y){try{return Y===""&&f.location.href?f.location.href:Y}catch{return Y}}M.open(D.method,ee(D.url),!0),D.credentials==="include"?M.withCredentials=!0:D.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&(a.blob?M.responseType="blob":a.arrayBuffer&&D.headers.get("Content-Type")&&D.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(M.responseType="arraybuffer")),g&&typeof g.headers=="object"&&!(g.headers instanceof E)?Object.getOwnPropertyNames(g.headers).forEach(function(Y){M.setRequestHeader(Y,w(g.headers[Y]))}):D.headers.forEach(function(Y,xt){M.setRequestHeader(xt,Y)}),D.signal&&(D.signal.addEventListener("abort",Ce),M.onreadystatechange=function(){M.readyState===4&&D.signal.removeEventListener("abort",Ce)}),M.send(typeof D._bodyInit=="undefined"?null:D._bodyInit)})}Ee.polyfill=!0,f.fetch||(f.fetch=Ee,f.Headers=E,f.Request=k,f.Response=G),c.Headers=E,c.Request=k,c.Response=G,c.fetch=Ee,Object.defineProperty(c,"__esModule",{value:!0})}),{fetch:u.fetch,Headers:u.Headers,Request:u.Request,Response:u.Response,DOMException:u.DOMException}}()}t.exports=n})(typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:zt)})(Yt,Yt.exports);var Zi=Yt.exports;const Jt=Wt(Zi),Ne="nhostRefreshToken",ze="nhostRefreshTokenId",me="nhostRefreshTokenExpiresAt",zr=3,Wr=60,Xt=5,Qt=0,Zt=1,ne=10,Ue=20;class De extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Zt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:ne,error:"invalid-email",message:"Email is incorrectly formatted"},Yr={status:ne,error:"invalid-mfa-type",message:"MFA type is invalid"},Jr={status:ne,error:"invalid-mfa-code",message:"MFA code is invalid"},wt={status:ne,error:"invalid-password",message:"Password is incorrectly formatted"},er={status:ne,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Xr={status:ne,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Qr={status:ne,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Zr={status:ne,error:"no-refresh-token",message:"No refresh token has been provided"},en={status:Ue,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},ie={status:Ue,error:"already-signed-in",message:"User is already signed in"},tn={status:Ue,error:"unauthenticated-user",message:"User is not authenticated"},es={status:Ue,error:"user-not-anonymous",message:"User is not anonymous"},rn={status:Ue,error:"unverified-user",message:"Email needs verification"},nn={status:ne,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},sn={status:Zt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Et={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function ts(t){return new TextEncoder().encode(t)}function ge(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 tr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let u=0;u<i.length;u++)o[u]=i.charCodeAt(u);return s}function on(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function an(t){const{id:e}=t;return{...t,id:tr(e),transports:t.transports}}function cn(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let Z=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function rs({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 Z("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 Z("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 Z("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new Z("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new Z("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 Z('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new Z("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(cn(s)){if(i.rp.id!==s)return new Z(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new Z(`${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 Z("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new Z("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class ns{createNewAbortSignal(){return this.controller&&this.controller.abort("Cancelling existing WebAuthn API call for new one"),this.controller=new AbortController,this.controller.signal}}const un=new ns;async function ln(t){if(!on())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:tr(t.challenge),user:{...t.user,id:ts(t.user.id)},excludeCredentials:t.excludeCredentials.map(an)}};e.signal=un.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(c){throw rs({error:c,options:e})}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,u={id:n,rawId:ge(i),response:{attestationObject:ge(s.attestationObject),clientDataJSON:ge(s.clientDataJSON)},type:o,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof s.getTransports=="function"&&(u.transports=s.getTransports()),u}function is(t){return new TextDecoder("utf-8").decode(t)}async function ss(){const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function os({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 Z("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new Z("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new Z("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(cn(i)){if(n.rpId!==i)return new Z(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new Z(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new Z("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function dn(t,e=!1){var r,n;if(!on())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(an));const s={...t,challenge:tr(t.challenge),allowCredentials:i},o={};if(e){if(!await ss())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=un.createNewAbortSignal();let u;try{u=await navigator.credentials.get(o)}catch(h){throw os({error:h,options:o})}if(!u)throw new Error("Authentication was not completed");const{id:c,rawId:f,response:a,type:l}=u;let d;return a.userHandle&&(d=is(a.userHandle)),{id:c,rawId:ge(f),response:{authenticatorData:ge(a.authenticatorData),clientDataJSON:ge(a.clientDataJSON),signature:ge(a.signature),userHandle:d},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const Tt=typeof window!="undefined",St=new Map,as=t=>{var e;return Tt&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=St.get(t))!=null?e:null},cs=(t,e)=>{Tt&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?St.set(t,e):St.has(t)&&St.delete(t)},fn=(t,e)=>{if(t==="localStorage"||t==="web")return as;if(t==="cookie")return r=>{var n;return Tt&&(n=Kt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},hn=(t,e)=>{if(t==="localStorage"||t==="web")return cs;if(t==="cookie")return(r,n)=>{Tt&&(n?Kt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Kt.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}`)},We=t=>!t||!t.accessToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},le=({accessToken:t,refreshToken:e,isError:r,user:n,error:i})=>r?{session:null,error:i}:n&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:e,user:n},error:null}:{session:null,error:null},bt=()=>typeof window!="undefined";let pn=globalThis.fetch;typeof EdgeRuntime!="string"&&(pn=Jt().fetch);const vn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await pn(t,s);if(!o.ok){const u=await o.json();return Promise.reject({error:u})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:o})}},te=async(t,e,r)=>vn(t,"POST",{token:r,body:e}),yn=(t,e)=>vn(t,"GET",{token:e}),rr=(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},se=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(o.search);let c=Object.fromEntries(u);r.startsWith("/")&&(c={...s,...c});let f=i.pathname;return o.pathname.length>1&&(f+=o.pathname.slice(1)),{...n,redirectTo:rr(o.origin+f,c)}};function Ye(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function nr(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const 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,}))$/),At=t=>!!t&&typeof t=="string"&&t.length>=zr,ir=t=>!!t&&typeof t=="string",mn=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),gn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const u=fn(r,n),c=hn(r,n),f=async(a,l,d)=>(await te(`${t}${a}`,l,d)).data;return pe({schema:{context:{},events:{},services:{}},tsTypes:{},context:Et,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:I({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:I(()=>(c(me,null),c(Ne,null),c(ze,null),{...Et})),clearContextExceptRefreshToken:I(({refreshToken:{value:a}})=>(c(me,null),{...Et,refreshToken:{value:a}})),saveSession:I({user:(a,{data:l})=>{var d;return((d=l==null?void 0:l.session)==null?void 0:d.user)||null},accessToken:(a,{data:l})=>{if(l.session){const{accessTokenExpiresIn:d,accessToken:h}=l.session,v=new Date(Date.now()+d*1e3);return c(me,v.toISOString()),{value:h,expiresAt:v,expiresInSeconds:d}}return c(me,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:l})=>{var d,h;const v=((d=l.session)==null?void 0:d.refreshToken)||null,w=((h=l.session)==null?void 0:h.refreshTokenId)||null;return v&&c(Ne,v),w&&c(ze,w),{value:v}}}),savePATSession:I({user:(a,{data:l})=>{var d;return((d=l==null?void 0:l.session)==null?void 0:d.user)||null},accessToken:(a,{data:l})=>{if(l.session){const{accessTokenExpiresIn:d,accessToken:h}=l.session,v=new Date(Date.now()+d*1e3);return c(me,v.toISOString()),{value:h,expiresAt:v,expiresInSeconds:d}}return c(me,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:l})=>{var d,h;const v=((d=l.session)==null?void 0:d.refreshToken)||null,w=((h=l.session)==null?void 0:h.refreshTokenId)||null;return v&&c(Ne,v),w&&c(ze,w),{value:v,isPAT:!0}}}),saveMfaTicket:I({mfa:(a,l)=>{var d;return(d=l.data)==null?void 0:d.mfa}}),resetTimer:I({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:I({refreshTimer:(a,l)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:I({errors:({errors:a},{data:{error:l}})=>({...a,authentication:l})}),resetErrors:I({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:I({errors:({errors:a},{data:{error:l}})=>({...a,registration:l})}),destroyRefreshToken:I({refreshToken:a=>(c(Ne,null),c(ze,null),{value:null})}),cleanUrl:()=>{o&&Ye("refreshToken")&&(nr("refreshToken"),nr("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage(a.refreshToken.value)}catch{}}},guards:{isAnonymous:(a,l)=>{var d;return!!((d=a.user)!=null&&d.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var l;return!!((l=a.refreshToken)!=null&&l.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:l}=a.accessToken;if(!l)return!1;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>Xt?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const d=a.accessToken.expiresInSeconds;return d?l.getTime()-Date.now()-1e3*Math.min(Wr,d*.5)<=0:!1},shouldRetryImportToken:(a,l)=>a.importTokenAttempts<Xt&&(l.data.error.status===Qt||l.data.error.status>=500),unverified:(a,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(a,l)=>{var d;return!!((d=l.data)!=null&&d.session)},hasMfaTicket:(a,l)=>{var d;return!!((d=l.data)!=null&&d.mfa)}},services:{signInPassword:(a,{email:l,password:d})=>de(l)?At(d)?f("/signin/email-password",{email:l,password:d}):Promise.reject({error:wt}):Promise.reject({error:ue}),signInPAT:(a,{pat:l})=>f("/signin/pat",{personalAccessToken:l}),passwordlessSms:(a,{phoneNumber:l,options:d})=>{var h;return ir(l)?(h=a.user)!=null&&h.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:se(e,d)},a.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:se(e,d)}):Promise.reject({error:er})},passwordlessSmsOtp:(a,{phoneNumber:l,otp:d})=>ir(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:d}):Promise.reject({error:er}),passwordlessEmail:(a,{email:l,options:d})=>{var h;return de(l)?(h=a.user)!=null&&h.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:se(e,d)},a.accessToken.value):f("/signin/passwordless/email",{email:l,options:se(e,d)}):Promise.reject({error:ue})},signInAnonymous:a=>f("/signin/anonymous"),signInMfaTotp:(a,l)=>{var d;const h=l.ticket||((d=a.mfa)==null?void 0:d.ticket);return h?mn(h)?f("/signin/mfa/totp",{ticket:h,otp:l.otp}):Promise.reject({error:Xr}):Promise.reject({error:Qr})},signInSecurityKeyEmail:async(a,{email:l})=>{if(!de(l))throw new De(ue);const d=await f("/signin/webauthn",{email:l});let h;try{h=await dn(d)}catch(v){throw new De(v)}return f("/signin/webauthn/verify",{email:l,credential:h})},refreshToken:async(a,l)=>{const d=l.type==="TRY_TOKEN"?l.token:a.refreshToken.value;return{session:await f("/token",{refreshToken:d}),error:null}},signout:(a,l)=>f("/signout",{refreshToken:a.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(a,{email:l,password:d,options:h})=>{var v;return de(l)?At(d)?(v=a.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:d,options:se(e,h)},a.accessToken.value):f("/signup/email-password",{email:l,password:d,options:se(e,h)}):Promise.reject({error:wt}):Promise.reject({error:ue})},signUpSecurityKey:async(a,{email:l,options:d})=>{if(!de(l))return Promise.reject({error:ue});const h=d==null?void 0:d.nickname;h&&delete d.nickname;const v=await f("/signup/webauthn",{email:l,options:d});let w;try{w=await ln(v)}catch(S){throw new De(S)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:h}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let l=null;if(o){const h=Ye("refreshToken")||null;if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(v){l=v.error}else{const v=Ye("error");if(v)return Promise.reject({session:null,error:{status:ne,error:v,message:Ye("errorDescription")||v}})}}const d=await u(Ne);if(d)try{return{session:await f("/token",{refreshToken:d}),error:null}}catch(h){l=h.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},wn=({backendUrl:t,clientUrl:e,interpreter:r})=>pe({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:I({error:n=>ue}),saveRequestError:I({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:s})=>(await te(`${t}/user/email/change`,{newEmail:i,options:se(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),En=({backendUrl:t,interpreter:e})=>pe({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:I({error:r=>wt}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!At(n)},services:{requestChange:(r,{password:n,ticket:i})=>te(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),us=({backendUrl:t,interpreter:e})=>pe({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:I({error:r=>Yr}),saveInvalidMfaCodeError:I({error:r=>Jr}),saveError:I({error:(r,{data:{error:n}})=>n}),saveGeneration:I({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:X((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS"),reportGeneratedSuccess:X("GENERATED"),reportGeneratedError:X(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 yn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>te(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Tn=({backendUrl:t,clientUrl:e})=>pe({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:I({error:r=>ue}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:se(e,i)})}}),Sn=({backendUrl:t,clientUrl:e})=>pe({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:I({error:r=>ue}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await te(`${t}/user/email/send-verification-email`,{email:n,options:se(e,i)})).data}});class sr{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:u,...c}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=gn({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var a;const l=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||xe(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class bn extends sr{constructor({...e}){super({...e,autoSignIn:bt()&&e.autoSignIn,autoRefreshToken:bt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const ls=bn,An=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await te(`${t}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await ln(n)}catch(o){throw new De(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},kn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),On=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})})}),ds=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:""})})}),fs=(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})})}),In=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})})}),xn=(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})})}),Rn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:ie,user:null,accessToken:null,refreshToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value,refreshToken:n.context.refreshToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),Pn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ie,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),or=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:ie,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})})}),_n=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:ie,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),Nn=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:u}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let c;try{c=await dn(u)}catch(f){throw new De(f)}try{const{data:{session:f},error:a}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:c},o);f&&!a&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:f}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(f){const{error:a}=f;r({error:a,isError:!0,isSuccess:!1,elevated:!1})}}),Un=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ie,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Dn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:ie,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:ie,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})})}),Cn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:ie,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Mn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:tn});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),cr=(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:ie,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),Ln=(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:ie,accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),hs=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.toUTCString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1,data:null}}};class jn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:u=!0}){var c;this.url=e,this._client=new sr({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?le(await Ln(r,n,i)):le(await cr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Rn(r);return{...le(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=rr(`${this._client.backendUrl}/signin/provider/${n}`,se(this._client.clientUrl,i));return bt()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Pn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:rn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...le(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await _n(r,e.email);return{...le(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await or(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Cn(r,e.phoneNumber,e.otp);return{...le(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Un(r,e.otp,e.ticket);return{...le(n),mfa:null}}return{error:sn,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Dn(r,e);return le(n)}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await Mn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(Tn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(En(this._client)).start(),{error:i}=await On(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(Sn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(wn(this._client)).start(),{error:i}=await kn(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 or(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await cr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await An(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Nn(this._client,e),mfa:null}}async createPAT(e,r){return hs(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(We(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,We(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Zn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Zr});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:en});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:nn}):o.event.type==="TOKEN_CHANGED"&&n({session:We(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return We((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var ps=typeof self=="object"?self.FormData:window.FormData;const ur=Wt(ps);let $n=globalThis.fetch;const lr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u,headers:c={}}={})=>{var f;const a={...c};s&&e.append("bucket-id",s),o&&(a["x-hasura-admin-secret"]=o),r&&(a.Authorization=`Bearer ${r}`);const l=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof ur&&($n=Jt().fetch);const d=await $n(l,{method:"POST",headers:a,body:e}),h=await d.json();return d.ok?{fileMetadata:h,error:null}:{error:{status:d.status,message:((f=h==null?void 0:h.error)==null?void 0:f.message)||d.statusText,error:d.statusText},fileMetadata:null}}catch(d){return{error:{status:0,message:d.message,error:d.message},fileMetadata:null}}return new Promise(d=>{let h=new XMLHttpRequest;h.responseType="json",h.onload=()=>{var v,w,S,E,T;return h.status<200||h.status>=300?d({fileMetadata:null,error:{error:(w=(v=h.response)==null?void 0:v.error)!=null?w:h.response,message:(T=(E=(S=h.response)==null?void 0:S.error)==null?void 0:E.message)!=null?T:h.response,status:h.status}}):d({fileMetadata:h.response,error:null})},h.onerror=()=>d({fileMetadata:null,error:{error:h.statusText,message:h.statusText,status:h.status}}),u&&h.upload.addEventListener("progress",u,!1),h.open("POST",l,!0),Object.entries(a).forEach(([v,w])=>{h.setRequestHeader(v,w)}),h.send(e)})};function kt(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}let Je;typeof Je=="undefined"&&(Je=Jt().fetch);class Fn{constructor({url:e}){this.url=e}async uploadFormData({formData:e,headers:r,bucketId:n}){const{error:i,fileMetadata:s}=await lr(this.url,e,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:n,headers:r});return i?{fileMetadata:null,error:i}:s&&!("processedFiles"in s)?{fileMetadata:{processedFiles:[s]},error:null}:{fileMetadata:s,error:null}}async uploadFile({file:e,bucketId:r,id:n,name:i}){const s=typeof window=="undefined"?new ur:new FormData;s.append("file[]",e),s.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:o,fileMetadata:u}=await lr(this.url,s,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:r,fileId:n,name:i});return o?{fileMetadata:null,error:o}:u&&"processedFiles"in u?{fileMetadata:u.processedFiles[0],error:null}:{fileMetadata:u,error:null}}async downloadFile(e){try{const{fileId:r,headers:n={},...i}=e,s=kt(`${this.url}/files/${r}`,i),o=await Je(s,{method:"GET",headers:{...this.generateAuthHeaders(),...n}});if(!o.ok)throw new Error(await o.text());return{file:await o.blob(),error:null}}catch(r){return{file:null,error:r}}}async getPresignedUrl(e){try{const{fileId:r}=e,n=await Je(`${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 Je(`${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}`}}}class qn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Fn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return kt(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,...n}=e,{presignedUrl:i,error:s}=await this.api.getPresignedUrl(e);if(s)return{presignedUrl:null,error:s};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const o=kt(i.url,n);return{presignedUrl:{...i,url:o},error:null}}async download(e){const{file:r,error:n}=await this.api.downloadFile(e);return n?{file:null,error:n}:r?{file:r,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}let dr;typeof dr=="undefined"&&(dr=ur);const Ot={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Bn=()=>pe({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...Ot},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:I({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:I({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:I({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:I({progress:t=>null,loaded:t=>0}),resetContext:I(t=>Ot),addFile:I({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new dr;i.append("file[]",n);let s=0;return lr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o&&!("processedFiles"in o)){const{id:c,bucketId:f}=o;r({type:"UPLOAD_DONE",id:c,bucketId:f})}if(o&&"processedFiles"in o){const{id:c,bucketId:f}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:c,bucketId:f})}}),()=>{}}}}),{pure:fr,sendParent:It}=xi,vs=()=>pe({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:I((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:I({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:I({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:I({loaded:t=>0}),startProgress:I({progress:t=>0}),resetProgress:I({progress:t=>null}),addItem:I((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,u)=>o+u.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Ki(Bn().withConfig({actions:{sendProgress:It((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:It("UPLOAD_DONE"),sendError:It("UPLOAD_ERROR"),sendDestroy:It("REMOVE")}}).withContext({...Ot,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:I({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:fr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:fr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:fr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),ys=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})})}),ms=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})})}),gs=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Xe(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(gs);if(i!=null&&i.groups){const{protocol:s,host:o,port:u}=i.groups,c=Ts(e);return c||(o==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${s||"http"}://localhost:${u||1337}/v1/${e}`):u?`${s||"https"}://local.${e}.nhost.run:${u}/v1`:`${s||"https"}://local.${e}.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${e}.${n}.nhost.run/v1`}function ws(){return typeof window!="undefined"}function Es(){return typeof process!="undefined"&&process.env}function Ts(t){return ws()||!Es()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Ss(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Gn(t){const e="subdomain"in t?Xe(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new jn({url:e,...t})}function bs(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},c=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(a){return u[a.toLowerCase()]},has:function(a){return a.toLowerCase()in u}}}};for(var f in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,l,d){s.push(l=l.toLowerCase()),o.push([l,d]),u[l]=u[l]?u[l]+","+d:d}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(f,e.headers[f]);i.send(e.body||null)})}const Vn=Qi(Object.freeze(Object.defineProperty({__proto__:null,default:bs},Symbol.toStringTag,{value:"Module"})));var As=self.fetch||(self.fetch=Vn.default||Vn);const Hn=Wt(As);function Kn(t){const e="subdomain"in t?Xe(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new zn({url:e,...t})}class zn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,u;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s=Ss(this.url,e);try{const c=await Hn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let f;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?f=await c.json():f=await c.text(),{res:{data:f,status:c.status,statusText:c.statusText},error:null}}catch(c){const f=c;return{res:null,error:{message:f.message,status:f.name==="AbortError"?0:500,error:f.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ks(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Wn(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 Os(t){if(typeof t=="string"){let r;try{const n=Te.parse(t);r=Wn(n)}catch{}return{query:t,operationName:r}}const e=Wn(t);return{query:Te.print(t),operationName:e}}class Is{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=ks(e,n,i),{headers:o,...u}=i||{},{query:c,operationName:f}=Os(s.document);try{const a=await Hn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...o},...u});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:l,errors:d}=await a.json();return d?{data:null,error:d}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(a){const l=a;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Yn(t){const e="subdomain"in t?Xe(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Is({url:e,...t})}function Jn(t){const e="subdomain"in t?Xe(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new qn({url:e,...t})}const xs=t=>new Xn(t);class Xn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...f}){this.auth=Gn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...f}),this.storage=Jn({adminSecret:o,...f}),this.functions=Kn({adminSecret:o,...f}),this.graphql=Yn({adminSecret:o,...f}),this.auth.onAuthStateChanged((a,l)=>{if(a==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const d=l==null?void 0:l.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this.auth.onTokenChanged(a=>{const l=a==null?void 0:a.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}y.AuthClient=sr,y.AuthClientSSR=ls,y.AuthCookieClient=bn,y.CodifiedError=De,y.EMAIL_NEEDS_VERIFICATION=rn,y.HasuraAuthClient=jn,y.HasuraStorageApi=Fn,y.HasuraStorageClient=qn,y.INITIAL_FILE_CONTEXT=Ot,y.INITIAL_MACHINE_CONTEXT=Et,y.INVALID_EMAIL_ERROR=ue,y.INVALID_MFA_CODE_ERROR=Jr,y.INVALID_MFA_TICKET_ERROR=Xr,y.INVALID_MFA_TYPE_ERROR=Yr,y.INVALID_PASSWORD_ERROR=wt,y.INVALID_PHONE_NUMBER_ERROR=er,y.INVALID_REFRESH_TOKEN=nn,y.INVALID_SIGN_IN_METHOD=sn,y.MIN_PASSWORD_LENGTH=zr,y.NETWORK_ERROR_CODE=Qt,y.NHOST_JWT_EXPIRES_AT_KEY=me,y.NHOST_REFRESH_TOKEN_ID_KEY=ze,y.NHOST_REFRESH_TOKEN_KEY=Ne,y.NO_MFA_TICKET_ERROR=Qr,y.NO_REFRESH_TOKEN=Zr,y.NhostClient=Xn,y.NhostFunctionsClient=zn,y.OTHER_ERROR_CODE=Zt,y.REFRESH_TOKEN_MAX_ATTEMPTS=Xt,y.STATE_ERROR_CODE=Ue,y.TOKEN_REFRESHER_RUNNING_ERROR=en,y.TOKEN_REFRESH_MARGIN_SECONDS=Wr,y.USER_ALREADY_SIGNED_IN=ie,y.USER_NOT_ANONYMOUS=es,y.USER_UNAUTHENTICATED=tn,y.VALIDATION_ERROR_CODE=ne,y.activateMfaPromise=fs,y.addSecurityKeyPromise=An,y.appendImageTransformationParameters=kt,y.changeEmailPromise=kn,y.changePasswordPromise=On,y.createAuthClient=Gn,y.createAuthMachine=gn,y.createChangeEmailMachine=wn,y.createChangePasswordMachine=En,y.createEnableMfaMachine=us,y.createFileUploadMachine=Bn,y.createFunctionsClient=Kn,y.createGraphqlClient=Yn,y.createMultipleFilesUploadMachine=vs,y.createNhostClient=xs,y.createResetPasswordMachine=Tn,y.createSendVerificationEmailMachine=Sn,y.createStorageClient=Jn,y.elevateEmailSecurityKeyPromise=Nn,y.encodeQueryParameters=rr,y.generateQrCodePromise=ds,y.getAuthenticationResult=le,y.getFetch=yn,y.getParameterByName=Ye,y.getSession=We,y.isBrowser=bt,y.isValidEmail=de,y.isValidPassword=At,y.isValidPhoneNumber=ir,y.isValidTicket=mn,y.localStorageGetter=fn,y.localStorageSetter=hn,y.postFetch=te,y.removeParameterFromWindow=nr,y.resetPasswordPromise=In,y.rewriteRedirectTo=se,y.sendVerificationEmailPromise=xn,y.signInAnonymousPromise=Rn,y.signInEmailPasswordPromise=Pn,y.signInEmailPasswordlessPromise=or,y.signInEmailSecurityKeyPromise=_n,y.signInMfaTotpPromise=Un,y.signInPATPromise=Dn,y.signInSmsPasswordlessOtpPromise=Cn,y.signInSmsPasswordlessPromise=ar,y.signOutPromise=Mn,y.signUpEmailPasswordPromise=cr,y.signUpEmailSecurityKeyPromise=Ln,y.uploadFilePromise=ys,y.uploadMultipleFilesPromise=ms,y.urlFromSubdomain=Xe,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
|
|
14
|
+
***************************************************************************** */var g=function(){return g=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},g.apply(this,arguments)};function Pt(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 _(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function V(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var j;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(j||(j={}));var fe;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(fe||(fe={}));var Ze=j.Start,et=j.Stop,be=j.Raise,je=j.Send,_t=j.Cancel,vr=j.NullEvent,tt=j.Assign,ai=j.After,ci=j.DoneState,rt=j.Log,yr=j.Init,nt=j.Invoke,ui=j.ErrorExecution,Nt=j.ErrorPlatform,Ut=j.ErrorCustom,it=j.Update,gr=j.Choose,mr=j.Pure;const li=Object.freeze(Object.defineProperty({__proto__:null,after:ai,assign:tt,cancel:_t,choose:gr,doneState:ci,error:Ut,errorExecution:ui,errorPlatform:Nt,init:yr,invoke:nt,log:rt,nullEvent:vr,pure:mr,raise:be,send:je,start:Ze,stop:et,update:it},Symbol.toStringTag,{value:"Module"}));var wr=".",Er={},Dt="xstate.guard",di="",G=process.env.NODE_ENV==="production",st;function Ct(t,e,r){r===void 0&&(r=wr);var n=Le(t,r),i=Le(e,r);return U(i)?U(n)?i===n:!1:U(n)?n in i:Object.keys(n).every(function(s){return s in i?Ct(n[s],i[s]):!1})}function Tr(t){try{return U(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Mt(t,e){try{return Ae(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function fi(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function Le(t,e){if(fi(t))return t.value;if(Ae(t))return ot(t);if(typeof t!="string")return t;var r=Mt(t,e);return ot(r)}function ot(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function $e(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function Sr(t,e,r){var n,i,s={};try{for(var o=R(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,f=t[c];r(f)&&(s[c]=e(f,c,t))}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var hi=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 u=o.value;i=i[u]}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function pi(t,e){return function(r){var n,i,s=r;try{for(var o=R(t),u=o.next();!u.done;u=o.next()){var c=u.value;s=s[e][c]}}catch(f){n={error:f}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function at(t){if(!t)return[[]];if(U(t))return[[t]];var e=H(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:at(t[r]).map(function(i){return[r].concat(i)})}));return e}function H(t){var e;return(e=[]).concat.apply(e,V([],_(t),!1))}function br(t){return Ae(t)?t:[t]}function re(t){return t===void 0?[]:br(t)}function ct(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=R(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,f=t[c];N(f)?s[c]=f(e,r.data):s[c]=f}}catch(a){n={error:a}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function vi(t){return/^(done|error)\./.test(t)}function Ar(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function yi(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function gi(t,e){var r,n,i=_([[],[]],2),s=i[0],o=i[1];try{for(var u=R(t),c=u.next();!c.done;c=u.next()){var f=c.value;e(f)?s.push(f):o.push(f)}}catch(a){r={error:a}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[s,o]}function kr(t,e){return $e(t.states,function(r,n){if(r){var i=(U(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:kr(r,i)}}})}function mi(t,e){return{current:e,states:kr(t,e)}}function Or(t,e,r,n){G||Y(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var u,c,f=o.assignment,a={state:n,action:o,_event:e},l={};if(N(f))l=f(s,e.data,a);else try{for(var d=R(Object.keys(f)),h=d.next();!h.done;h=d.next()){var v=h.value,w=f[v];l[v]=N(w)?w(s,e.data,a):w}}catch(S){u={error:S}}finally{try{h&&!h.done&&(c=d.return)&&c.call(d)}finally{if(u)throw u.error}}return Object.assign({},s,l)},t);return i}var Y=function(){};G||(Y=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 Ae(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function U(t){return typeof t=="string"}function Ir(t,e){if(t)return U(t)?{type:Dt,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Dt,name:t.name,predicate:t}:t}function wi(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var he=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();st={},st[he]=function(){return this},st[Symbol.observable]=function(){return this};function ae(t){return!!t&&"__xstatenode"in t}function Ei(t){return!!t&&typeof t.send=="function"}var Ti=function(){var t=0;return function(){return t++,t.toString(16)}}();function ut(t,e){return U(t)||typeof t=="number"?g({type:t},e):t}function Q(t,e){if(!U(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=ut(t);return g({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function ke(t,e){var r=br(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||ae(n)?{target:n,event:t}:g(g({},n),{event:t})});return r}function Si(t){if(!(t===void 0||t===di))return re(t)}function bi(t,e,r){if(!G){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function xr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Dt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var u=s==null?void 0:s[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,o)}function Rr(t){return typeof t=="string"?{type:t}:t}function lt(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 dt(t,e){return"".concat(t,":invocation[").concat(e,"]")}function jt(t){return(t.type===be||t.type===je&&t.to===fe.Internal)&&typeof t.delay!="number"}var ye=Q({type:yr});function ft(t,e){return e&&e[t]||void 0}function Oe(t,e){var r;if(U(t)||typeof t=="number"){var n=ft(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=ft(t.type,e);if(N(n))r=g(g({},t),{exec:n});else if(n){var i=n.type||t.type;r=g(g(g({},n),t),{type:i})}else r=t}return r}var ce=function(t,e){if(!t)return[];var r=Ae(t)?t:[t];return r.map(function(n){return Oe(n,e)})};function ht(t){var e=Oe(t);return g(g({id:U(t)?t:e.id},e),{type:e.type})}function Pr(t,e){return{type:be,event:typeof t=="function"?t:ut(t),delay:e?e.delay:void 0,id:e==null?void 0:e.id}}function _r(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;return g(g({},t),{type:be,_event:s,delay:o})}function ge(t,e){return{to:e?e.to:void 0,type:je,event:N(t)?t:ut(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:Tr(t)}}function Nr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var c=N(t.to)?t.to(e,r.data,i):t.to;return g(g({},t),{to:c,_event:s,event:s.data,delay:o})}function Lt(t,e){return ge(t,g(g({},e),{to:fe.Parent}))}function Ai(t,e,r){return ge(e,g(g({},r),{to:t}))}function ki(){return Lt(it)}function Oi(t,e){return ge(t,g(g({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var Ii=function(t,e){return{context:t,event:e}};function xi(t,e){return t===void 0&&(t=Ii),{type:rt,label:e,expr:t}}var Ur=function(t,e,r){return g(g({},t),{value:U(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Dr=function(t){return{type:_t,sendId:t}};function Cr(t){var e=ht(t);return{type:j.Start,activity:e,exec:void 0}}function Mr(t){var e=N(t)?t:ht(t);return{type:j.Stop,activity:e,exec:void 0}}function jr(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:j.Stop,activity:i};return s}var Lr=function(t){return{type:tt,assignment:t}};function Ri(t){return typeof t=="object"&&"type"in t}function $r(t,e){var r=e?"#".concat(e):"";return"".concat(j.After,"(").concat(t,")").concat(r)}function Fe(t,e){var r="".concat(j.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function qe(t,e){var r="".concat(j.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Ie(t,e){var r="".concat(j.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Pi(t){return{type:j.Pure,get:t}}function _i(t,e){if(!G&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var s=typeof r=="function"?r.apply(void 0,V([],_(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 ge(function(n,i){return i},g(g({},e),{to:t}))}function Ni(t,e){return Lt(function(r,n,i){return{type:Ut,data:N(t)?t(r,n,i):t}},g(g({},e),{to:fe.Parent}))}function Ui(t){return{type:j.Choose,conds:t}}var Di=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,u=0;u<o.actions.length;){if(o.actions[u].type===tt){n.push(o.actions[u]),o.actions.splice(u,1);continue}u++}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function Ve(t,e,r,n,i,s,o){o===void 0&&(o=!1);var u=o?[]:Di(i),c=u.length?Or(r,n,u,e):r,f=o?[r]:void 0,a=[];function l(v,w){var S;switch(w.type){case be:{var E=_r(w,c,n,t.options.delays);return s&&typeof E.delay=="number"&&s(E,c,n),E}case je:var T=Nr(w,c,n,t.options.delays);if(!G){var b=w.delay;Y(!U(b)||typeof T.delay=="number","No delay reference for delay expression '".concat(b,"' was found on machine '").concat(t.id,"'"))}return s&&T.to!==fe.Internal&&(v==="entry"?a.push(T):s(T,c,n)),T;case rt:{var O=Ur(w,c,n);return s==null||s(O,c,n),O}case gr:{var $=w,C=(S=$.conds.find(function(p){var m=Ir(p.cond,t.options.guards);return!m||xr(t,m,c,n,s?void 0:e)}))===null||S===void 0?void 0:S.actions;if(!C)return[];var P=_(Ve(t,e,c,n,[{type:v,actions:ce(re(C),t.options.actions)}],s,o),2),L=P[0],x=P[1];return c=x,f==null||f.push(c),L}case mr:{var C=w.get(c,n.data);if(!C)return[];var K=_(Ve(t,e,c,n,[{type:v,actions:ce(re(C),t.options.actions)}],s,o),2),k=K[0],F=K[1];return c=F,f==null||f.push(c),k}case et:{var O=jr(w,c,n);return s==null||s(O,r,n),O}case tt:{c=Or(c,n,[w],s?void 0:e),f==null||f.push(c);break}default:var z=Oe(w,t.options.actions),B=z.exec;if(s)s(z,c,n);else if(B&&f){var Ee=f.length-1,Te=g(g({},z),{exec:function(p){for(var m=[],A=1;A<arguments.length;A++)m[A-1]=arguments[A];B.apply(void 0,V([f[Ee]],_(m),!1))}});z=Te}return z}}function d(v){var w,S,E=[];try{for(var T=R(v.actions),b=T.next();!b.done;b=T.next()){var O=b.value,$=l(v.type,O);$&&(E=E.concat($))}}catch(C){w={error:C}}finally{try{b&&!b.done&&(S=T.return)&&S.call(T)}finally{if(w)throw w.error}}return a.forEach(function(C){s(C,c,n)}),a.length=0,E}var h=H(i.map(d));return[h,c]}const Ci=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:li,after:$r,assign:Lr,cancel:Dr,choose:Ui,done:Fe,doneInvoke:qe,error:Ie,escalate:Ni,forwardTo:_i,getActionFunction:ft,initEvent:ye,isActionObject:Ri,log:xi,pure:Pi,raise:Pr,resolveActions:Ve,resolveLog:Ur,resolveRaise:_r,resolveSend:Nr,resolveStop:jr,respond:Oi,send:ge,sendParent:Lt,sendTo:Ai,sendUpdate:ki,start:Cr,stop:Mr,toActionObject:Oe,toActionObjects:ce,toActivityDefinition:ht},Symbol.toStringTag,{value:"Module"}));var pt=[],xe=function(t,e){pt.push(t);var r=e(t);return pt.pop(),r},Mi=function(t){return t(pt[pt.length-1])};function Fr(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 ji(t,e,r,n){var i,s=Rr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],u=t.data?ct(t.data,r,n):void 0,c=o?$t(o,t.id,u):Fr(t.id);return c.meta=t,c}function $t(t,e,r){var n=Fr(e);if(n.deferred=!0,ae(t)){var i=n.state=xe(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function Li(t){try{return typeof t.send=="function"}catch{return!1}}function $i(t){return Li(t)&&"id"in t}function Fi(t){var e;return g((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[he]=function(){return this},e),t)}var vt=function(t){return t.type==="atomic"||t.type==="final"};function qr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Be(t){return qr(t).filter(function(e){return e.type!=="history"})}function Vr(t){var e=[t];return vt(t)?e:e.concat(H(Be(t).map(Vr)))}function Ge(t,e){var r,n,i,s,o,u,c,f,a=new Set(t),l=Ft(a),d=new Set(e);try{for(var h=R(d),v=h.next();!v.done;v=h.next())for(var w=v.value,S=w.parent;S&&!d.has(S);)d.add(S),S=S.parent}catch(x){r={error:x}}finally{try{v&&!v.done&&(n=h.return)&&n.call(h)}finally{if(r)throw r.error}}var E=Ft(d);try{for(var T=R(d),b=T.next();!b.done;b=T.next()){var w=b.value;if(w.type==="compound"&&(!E.get(w)||!E.get(w).length))l.get(w)?l.get(w).forEach(function(K){return d.add(K)}):w.initialStateNodes.forEach(function(K){return d.add(K)});else if(w.type==="parallel")try{for(var O=(o=void 0,R(Be(w))),$=O.next();!$.done;$=O.next()){var C=$.value;d.has(C)||(d.add(C),l.get(C)?l.get(C).forEach(function(K){return d.add(K)}):C.initialStateNodes.forEach(function(K){return d.add(K)}))}}catch(K){o={error:K}}finally{try{$&&!$.done&&(u=O.return)&&u.call(O)}finally{if(o)throw o.error}}}}catch(x){i={error:x}}finally{try{b&&!b.done&&(s=T.return)&&s.call(T)}finally{if(i)throw i.error}}try{for(var P=R(d),L=P.next();!L.done;L=P.next())for(var w=L.value,S=w.parent;S&&!d.has(S);)d.add(S),S=S.parent}catch(x){c={error:x}}finally{try{L&&!L.done&&(f=P.return)&&f.call(P)}finally{if(c)throw c.error}}return d}function Br(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(vt(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Br(s,e)}),i}function Ft(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(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function qi(t,e){var r=Ge([t],e);return Br(t,Ft(r))}function He(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Vi(t){return V([],_(new Set(H(V([],_(t.map(function(e){return e.ownEvents})),!1)))),!1)}function yt(t,e){return e.type==="compound"?Be(e).some(function(r){return r.type==="final"&&He(t,r)}):e.type==="parallel"?Be(e).every(function(r){return yt(t,r)}):!1}function Bi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Gr(t){return new Set(H(t.map(function(e){return e.tags})))}function Hr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(U(t)||U(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Hr(t[i],e[i])})}function Gi(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Hi(t,e){var r=t.exec,n=g(g({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var oe=function(){function t(e){var r=this,n;this.actions=[],this.activities=Er,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||Er,this.meta=Bi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Vi(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=ye;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=ye;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),U(e))return[e];var i=Object.keys(e);return i.concat.apply(i,V([],_(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=Pt(e,["configuration","transitions","tags","machine"]);return g(g({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Ct(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;G&&Y(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),Ki={deferEvents:!1},Kr=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=g(g({},Ki),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),qt=new Map,zi=0,Ke={bookId:function(){return"x:".concat(zi++)},register:function(t,e){return qt.set(t,e),t},get:function(t){return qt.get(t)},free:function(t){qt.delete(t)}};function Vt(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;G||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function Ji(){var t=Vt();if(t&&"__xstate__"in t)return t.__xstate__}function Wi(t){if(Vt()){var e=Ji();e&&e.register(t)}}function Yi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var f=i.shift();r=t.transition(r,f,c),n.forEach(function(a){return a.next(r)})}s=!1}},u=Fi({id:e.id,send:function(f){i.push(f),o()},getSnapshot:function(){return r},subscribe:function(f,a,l){var d=lt(f,a,l);return n.add(d),d.next(r),{unsubscribe:function(){n.delete(d)}}}}),c={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(c):r,u}var Bt={sync:!1,autoForward:!1},J;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(J||(J={}));var Xi=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=J.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(a,l){if(Ae(a))return n.batch(a),n.state;var d=Q(ut(a,l));if(n.status===J.Stopped)return G||Y(!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!==J.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 h=n._nextState(d);n.update(h,d)}),n._state},this.sendTo=function(a,l,d){var h=n.parent&&(l===fe.Parent||n.parent.id===l),v=h?n.parent:U(l)?l===fe.Internal?n:n.children.get(l)||Ke.get(l):Ei(l)?l:void 0;if(!v){if(!h)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));G||Y(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(a.type));return}if("machine"in v){if(n.status!==J.Stopped||n.parent!==v||n.state.done){var w=g(g({},a),{name:a.name===Ut?"".concat(Ie(n.id)):a.name,origin:n.sessionId});!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,w]):v.send(w)}}else!d&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,a.data]):v.send(a.data)},this._exec=function(a,l,d,h){h===void 0&&(h=n.machine.options.actions);var v=a.exec||ft(a.type,h),w=N(v)?v:v?v.exec:a.exec;if(w)try{return w(l,d.data,n.machine.config.predictableActionArguments?{action:a,_event:d}:{action:a,state:n.state,_event:d})}catch(B){throw n.parent&&n.parent.send({type:"xstate.error",data:B}),B}switch(a.type){case be:{var S=a;n.defer(S);break}case je:var E=a;if(typeof E.delay=="number"){n.defer(E);return}else E.to?n.sendTo(E._event,E.to,d===ye):n.send(E._event);break;case _t:n.cancel(a.sendId);break;case Ze:{if(n.status!==J.Running)return;var T=a.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[T.id||T.type])break;if(T.type===j.Invoke){var b=Rr(T.src),O=n.machine.options.services?n.machine.options.services[b.type]:void 0,$=T.id,C=T.data;G||Y(!("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 P="autoForward"in T?T.autoForward:!!T.forward;if(!O){G||Y(!1,"No service found for invocation '".concat(T.src,"' in machine '").concat(n.machine.id,"'."));return}var L=C?ct(C,l,d):void 0;if(typeof O=="string")return;var x=N(O)?O(l,d.data,{data:L,src:b,meta:T.meta}):O;if(!x)return;var K=void 0;ae(x)&&(x=L?x.withContext(L):x,K={autoForward:P}),n.spawn(x,$,K)}else n.spawnActivity(T);break}case et:{n.stopChild(a.activity.id);break}case rt:var k=a,F=k.label,z=k.value;F?n.logger(F,z):n.logger(z);break;default:G||Y(!1,"No implementation found for action type '".concat(a.type,"'"));break}};var i=g(g({},t.defaultOptions),r),s=i.clock,o=i.logger,u=i.parent,c=i.id,f=c!==void 0?c:e.id;this.id=f,this.logger=o,this.clock=s,this.parent=u,this.options=i,this.scheduler=new Kr({deferEvents:this.options.deferEvents}),this.sessionId=Ke.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:xe(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return G||Y(this.status!==J.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var s=R(e.actions),o=s.next();!o.done;o=s.next()){var u=o.value;this.exec(u,e,r)}}catch(c){n={error:c}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,o,u,c,f,a,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===ye)&&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(x){l.state.children[x.id]=x}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var h=R(this.eventListeners),v=h.next();!v.done;v=h.next()){var w=v.value;w(e.event)}}catch(x){n={error:x}}finally{try{v&&!v.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}try{for(var S=R(this.listeners),E=S.next();!E.done;E=S.next()){var w=E.value;w(e,e.event)}}catch(x){s={error:x}}finally{try{E&&!E.done&&(o=S.return)&&o.call(S)}finally{if(s)throw s.error}}try{for(var T=R(this.contextListeners),b=T.next();!b.done;b=T.next()){var O=b.value;O(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(x){u={error:x}}finally{try{b&&!b.done&&(c=T.return)&&c.call(T)}finally{if(u)throw u.error}}if(this.state.done){var $=e.configuration.find(function(x){return x.type==="final"&&x.parent===l.machine}),C=$&&$.doneData?ct($.doneData,e.context,r):void 0;this._doneEvent=qe(this.id,C);try{for(var P=R(this.doneListeners),L=P.next();!L.done;L=P.next()){var w=L.value;w(this._doneEvent)}}catch(x){f={error:x}}finally{try{L&&!L.done&&(a=P.return)&&a.call(P)}finally{if(f)throw f.error}}this._stop(),this._stopChildren(),Ke.free(this.sessionId)}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===J.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,s=lt(e,r,n);this.listeners.add(s.next),this.status!==J.NotStarted&&s.next(this.state);var o=function(){i.doneListeners.delete(o),i.stopListeners.delete(o),s.complete()};return this.status===J.Stopped?s.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){i.listeners.delete(s.next),i.doneListeners.delete(o),i.stopListeners.delete(o)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.status===J.Stopped&&this._doneEvent?e(this._doneEvent):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===J.Running)return this;this.machine._init(),Ke.register(this.sessionId,this),this.initialized=!0,this.status=J.Running;var n=e===void 0?this.initialState:xe(this,function(){return Gi(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,ye)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){N(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,s,o,u,c,f,a;try{for(var l=R(this.listeners),d=l.next();!d.done;d=l.next()){var h=d.value;this.listeners.delete(h)}}catch(P){e={error:P}}finally{try{d&&!d.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=R(this.stopListeners),w=v.next();!w.done;w=v.next()){var h=w.value;h(),this.stopListeners.delete(h)}}catch(P){n={error:P}}finally{try{w&&!w.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var S=R(this.contextListeners),E=S.next();!E.done;E=S.next()){var h=E.value;this.contextListeners.delete(h)}}catch(P){s={error:P}}finally{try{E&&!E.done&&(o=S.return)&&o.call(S)}finally{if(s)throw s.error}}try{for(var T=R(this.doneListeners),b=T.next();!b.done;b=T.next()){var h=b.value;this.doneListeners.delete(h)}}catch(P){u={error:P}}finally{try{b&&!b.done&&(c=T.return)&&c.call(T)}finally{if(u)throw u.error}}if(!this.initialized)return this;this.initialized=!1,this.status=J.Stopped,this._initialState=void 0;try{for(var O=R(Object.keys(this.delayedEventsMap)),$=O.next();!$.done;$=O.next()){var C=$.value;this.clock.clearTimeout(this.delayedEventsMap[C])}}catch(P){f={error:P}}finally{try{$&&!$.done&&(a=O.return)&&a.call(O)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Kr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n;if(!(!((n=e._state)===null||n===void 0)&&n.done)){var i=Q({type:"xstate.stop"}),s=xe(e,function(){var o=H(V([],_(e.state.configuration),!1).sort(function(l,d){return d.order-l.order}).map(function(l){return ce(l.onExit,e.machine.options.actions)})),u=_(Ve(e.machine,e.state,e.state.context,i,[{type:"exit",actions:o}],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),c=u[0],f=u[1],a=new oe({value:e.state.value,context:f,_event:i,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:c.filter(function(l){return!jt(l)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return a.changed=!0,a});e.update(s,i),e._stopChildren(),Ke.free(e.sessionId)}}),this},t.prototype.batch=function(e){var r=this;if(this.status===J.NotStarted&&this.options.deferEvents)G||Y(!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!==J.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,u=!1,c=[],f=function(h){var v=Q(h);r.forward(v),o=xe(r,function(){return r.machine.transition(o,v,void 0,n||void 0)}),c.push.apply(c,V([],_(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(w){return Hi(w,o)})),!1)),u=u||!!o.changed};try{for(var a=R(e),l=a.next();!l.done;l=a.next()){var d=l.value;f(d)}}catch(h){i={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}o.changed=u,o.actions=c,r.update(o,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(Nt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(Nt)===0}))throw i.data.data;var s=xe(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,u=this.children.get(o);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));u.send(e)}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this,n=this.clock.setTimeout(function(){"to"in e&&e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay);e.id&&(this.delayedEventsMap[e.id]=n)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==J.Running)return $t(e,r);if(Ar(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if($i(e))return this.spawnActor(e,r);if(wi(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,g(g({},n),{id:r}));if(yi(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,g(g({},this.options),{parent:this,id:r.id||e.id})),s=g(g({},Bt),r);s.sync&&i.onTransition(function(u){n.send(it,{state:u,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Yi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(c){s||(o=c,i.removeChild(r),i.send(Q(qe(r,c),{origin:r})))},function(c){if(!s){i.removeChild(r);var f=Ie(r,c);try{i.send(Q(f,{origin:r}))}catch(a){bi(c,a,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(c,f,a){var l=lt(c,f,a),d=!1;return e.then(function(h){d||(l.next(h),!d&&l.complete())},function(h){d||l.error(h)}),{unsubscribe:function(){return d=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,u=new Set,c,f=function(d){c=d,u.forEach(function(h){return h(d)}),!s&&i.send(Q(d,{origin:r}))},a;try{a=e(f,function(d){o.add(d)})}catch(d){this.send(Ie(r,d))}if(Ar(a))return this.spawnPromise(a,r);var l=(n={id:r,send:function(d){return o.forEach(function(h){return h(d)})},subscribe:function(d){var h=lt(d);return u.add(h.next),{unsubscribe:function(){u.delete(h.next)}}},stop:function(){s=!0,N(a)&&a()},toJSON:function(){return{id:r}},getSnapshot:function(){return c}},n[he]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(c){s=c,i.send(Q(c,{origin:r}))},function(c){i.removeChild(r),i.send(Q(Ie(r,c),{origin:r}))},function(){i.removeChild(r),i.send(Q(qe(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(c,f,a){return e.subscribe(c,f,a)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[he]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){G||Y(!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=Vt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(g(g({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:g({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Wi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[he]=function(){return this},t.prototype.getSnapshot=function(){return this.status===J.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=Re,t}(),Qi=function(t){return U(t)?g(g({},Bt),{name:t}):g(g(g({},Bt),{name:Ti()}),t)};function Zi(t,e){var r=Qi(e);return Mi(function(n){if(!G){var i=ae(t)||N(t);Y(!!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):$t(t,r.name)})}function Re(t,e){var r=new Xi(t,e);return r}function es(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function gt(t){return g(g({type:nt},t),{toJSON:function(){t.onDone,t.onError;var e=Pt(t,["onDone","onError"]);return g(g({},e),{type:nt,src:es(t.src)})}})}var Pe="",Gt="#",ze="*",_e={},Ne=function(t){return t[0]===Gt},ts=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},rs=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(U(s.target)||ae(s.target))}),i=e===Pe?"the transient event":"event '".concat(e,"'");Y(!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.")},ns=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(ts(),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:wr),this.id=this.config.id||V([this.machine.key],_(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,G||Y(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?$e(this.config.states,function(f,a){var l,d=new t(f,{},void 0,{parent:s,key:a});return Object.assign(s.idMap,g((l={},l[d.id]=d,l),d.idMap)),d}):_e;var u=0;function c(f){var a,l;f.order=u++;try{for(var d=R(qr(f)),h=d.next();!h.done;h=d.next()){var v=h.value;c(v)}}catch(w){a={error:w}}finally{try{h&&!h.done&&(l=d.return)&&l.call(d)}finally{if(a)throw a.error}}}c(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(f){var a=f.event;return a===Pe}):Pe in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=re(this.config.entry||this.config.onEntry).map(function(f){return Oe(f)}),this.onExit=re(this.config.exit||this.config.onExit).map(function(f){return Oe(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=re(this.config.invoke).map(function(f,a){var l,d;if(ae(f)){var h=dt(s.id,a);return s.machine.options.services=g((l={},l[h]=f,l),s.machine.options.services),gt({src:h,id:h})}else if(U(f.src)){var h=f.id||dt(s.id,a);return gt(g(g({},f),{id:h,src:f.src}))}else if(ae(f.src)||N(f.src)){var h=f.id||dt(s.id,a);return s.machine.options.services=g((d={},d[h]=f.src,d),s.machine.options.services),gt(g(g({id:h},f),{src:h}))}else{var v=f.src;return gt(g(g({id:dt(s.id,a)},f),{src:v}))}}),this.activities=re(this.config.activities).concat(this.invoke).map(function(f){return ht(f)}),this.transition=this.transition.bind(this),this.tags=re(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Vr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,u=n.services,c=n.delays;return new t(this.config,{actions:g(g({},i),e.actions),activities:g(g({},s),e.activities),guards:g(g({},o),e.guards),services:g(g({},u),e.services),delays:g(g({},c),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:$e(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Pe,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===ze});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var u=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,c=$r(u,e.id);return e.onEntry.push(ge(c,{delay:s})),e.onExit.push(Dr(c)),c},i=Ae(r)?r.map(function(s,o){var u=n(s.delay,o);return g(g({},s),{event:u})}):H(Object.keys(r).map(function(s,o){var u=r[s],c=U(u)?{target:u}:u,f=isNaN(+s)?s:+s,a=n(f,o);return re(c).map(function(l){return g(g({},l),{event:a,delay:f})})}));return i.map(function(s){var o=s.delay;return g(g({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:Le(e,this.delimiter);if(U(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),u=[this];return u.push.apply(u,V([],_(H(o.map(function(c){return n.getStateNode(c).getStateNodes(i[c])}))),!1)),u},t.prototype.handles=function(e){var r=Tr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from(Ge([],this.getStateNodes(r.value)));return new oe(g(g({},r),{value:this.resolve(r.value),configuration:n,done:yt(n,this),tags:Gr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var u=R(Object.keys(e)),c=u.next();!c.done;c=u.next()){var f=c.value,a=e[f];if(a){var l=this.getStateNode(f),d=l._transition(a,r,n);d&&(o[f]=d)}}}catch(E){i={error:E}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(i)throw i.error}}var h=Object.keys(o).map(function(E){return o[E]}),v=H(h.map(function(E){return E.transitions})),w=h.some(function(E){return E.transitions.length>0});if(!w)return this.next(r,n);var S=H(Object.keys(o).map(function(E){return o[E].configuration}));return{transitions:v,exitSet:H(h.map(function(E){return E.exitSet})),configuration:S,source:r,actions:H(Object.keys(o).map(function(E){return o[E].actions}))}},t.prototype._transition=function(e,r,n){return U(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,u=[],c=[],f;try{for(var a=R(this.getCandidates(o)),l=a.next();!l.done;l=a.next()){var d=l.value,h=d.cond,v=d.in,w=e.context,S=v?U(v)&&Ne(v)?e.matches(Le(this.getStateNodeById(v).path,this.delimiter)):Ct(Le(v,this.delimiter),hi(this.path.slice(0,-2))(e.value)):!0,E=!1;try{E=!h||xr(this.machine,h,w,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(h.name||h.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
+
`).concat(O.message))}if(E&&S){d.target!==void 0&&(c=d.target),u.push.apply(u,V([],_(d.actions),!1)),f=d;break}}}catch(O){n={error:O}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}if(f){if(!c.length)return{transitions:[f],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var T=H(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),b=!!f.internal;return{transitions:[f],exitSet:b?[]:H(c.map(function(O){return s.getPotentiallyReenteringNodes(O)})),configuration:T,source:e,actions:u}}},t.prototype.getPotentiallyReenteringNodes=function(e){if(this.order<e.order)return[this];for(var r=[],n=this,i=e;n&&n!==i;)r.push(n),n=n.parent;return n!==i?[]:(r.push(i),r)},t.prototype.getActions=function(e,r,n,i,s,o,u){var c,f,a,l,d=this,h=o?Ge([],this.getStateNodes(o.value)):[],v=new Set;try{for(var w=R(Array.from(e).sort(function(k,F){return k.order-F.order})),S=w.next();!S.done;S=w.next()){var E=S.value;(!He(h,E)||He(n.exitSet,E)||E.parent&&v.has(E.parent))&&v.add(E)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(f=w.return)&&f.call(w)}finally{if(c)throw c.error}}try{for(var T=R(h),b=T.next();!b.done;b=T.next()){var E=b.value;(!He(e,E)||He(n.exitSet,E.parent))&&n.exitSet.push(E)}}catch(k){a={error:k}}finally{try{b&&!b.done&&(l=T.return)&&l.call(T)}finally{if(a)throw a.error}}n.exitSet.sort(function(k,F){return F.order-k.order});var O=Array.from(v).sort(function(k,F){return k.order-F.order}),$=new Set(n.exitSet),C=H(O.map(function(k){var F=[];if(k.type!=="final")return F;var z=k.parent;if(!z.parent)return F;F.push(Fe(k.id,k.doneData),Fe(z.id,k.doneData?ct(k.doneData,i,s):void 0));var B=z.parent;return B.type==="parallel"&&Be(B).every(function(Ee){return yt(n.configuration,Ee)})&&F.push(Fe(B.id)),F})),P=O.map(function(k){var F=k.onEntry,z=k.activities.map(function(B){return Cr(B)});return{type:"entry",actions:ce(u?V(V([],_(F),!1),_(z),!1):V(V([],_(z),!1),_(F),!1),d.machine.options.actions)}}).concat({type:"state_done",actions:C.map(function(k){return Pr(k)})}),L=Array.from($).map(function(k){return{type:"exit",actions:ce(V(V([],_(k.onExit),!1),_(k.activities.map(function(F){return Mr(F)})),!1),d.machine.options.actions)}}),x=L.concat({type:"transition",actions:ce(n.actions,this.machine.options.actions)}).concat(P);if(r){var K=ce(H(V([],_(e),!1).sort(function(k,F){return F.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return!jt(k)});return x.concat({type:"stop",actions:K})}return x},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=Q(r),o;if(e instanceof oe)o=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=U(e)?this.resolve(ot(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(oe.from(u,c))}if(!G&&s.name===ze)throw new Error("An event cannot have the wildcard type ('".concat(ze,"')"));if(this.strict&&!this.events.includes(s.name)&&!vi(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var f=this._transition(o.value,o,s)||{transitions:[],configuration:[],exitSet:[],source:o,actions:[]},a=Ge([],this.getStateNodes(o.value)),l=f.configuration.length?Ge(a,f.configuration):a;return f.configuration=V([],_(l),!1),this.resolveTransition(f,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,V([],_(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,u,c,f,a=this;s===void 0&&(s=ye);var l=e.configuration,d=!r||e.transitions.length>0,h=d?e.configuration:r?r.configuration:[],v=yt(h,this),w=d?qi(this.machine,l):void 0,S=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(h),v,e,n,s,r,i),T=r?g({},r.activities):{};try{for(var b=R(E),O=b.next();!O.done;O=b.next()){var $=O.value;try{for(var C=(c=void 0,R($.actions)),P=C.next();!P.done;P=C.next()){var L=P.value;L.type===Ze?T[L.activity.id||L.activity.type]=L:L.type===et&&(T[L.activity.id||L.activity.type]=!1)}}catch(ee){c={error:ee}}finally{try{P&&!P.done&&(f=C.return)&&f.call(C)}finally{if(c)throw c.error}}}}catch(ee){o={error:ee}}finally{try{O&&!O.done&&(u=b.return)&&u.call(b)}finally{if(o)throw o.error}}var x=_(Ve(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),K=x[0],k=x[1],F=_(gi(K,jt),2),z=F[0],B=F[1],Ee=K.filter(function(ee){var W;return ee.type===Ze&&((W=ee.activity)===null||W===void 0?void 0:W.type)===nt}),Te=Ee.reduce(function(ee,W){return ee[W.activity.id]=ji(W.activity,a.machine,k,s),ee},r?g({},r.children):{}),p=new oe({value:w||r.value,context:k,_event:s,_sessionid:r?r._sessionid:null,historyValue:w?S?mi(S,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?B:[],activities:w?T:r?r.activities:{},events:[],configuration:h,transitions:e.transitions,children:Te,done:v,tags:Gr(h),machine:this}),m=n!==k;p.changed=s.name===it||m;var A=p.history;A&&delete A.history;var q=!v&&(this._transient||l.some(function(ee){return ee._transient}));if(!d&&(!q||s.name===Pe))return p;var D=p;if(!v)for(q&&(D=this.resolveRaisedTransition(D,{type:vr},s,i));z.length;){var M=z.shift();D=this.resolveRaisedTransition(D,M._event,s,i)}var Me=D.changed||(A?!!D.actions.length||m||typeof A.value!=typeof D.value||!Hr(D.value,A.value):void 0);return D.changed=Me,D.history=A,D},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(Gt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Ne(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Mt(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||_e;switch(this.type){case"parallel":return $e(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):_e});case"compound":if(U(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?$e(e,function(s,o){return s?n.getStateNode(o).resolve(s):_e}):this.initialStateValue||{};default:return e||_e}},t.prototype.getResolvedPath=function(e){if(Ne(e)){var r=this.machine.idMap[e.slice(Gt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Mt(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=Sr(this.states,function(n){return n.initialStateValue||_e},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=vt(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,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;U(r.target)?e=Ne(r.target)?ot(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(vt(this))return[this];if(this.type==="compound"&&!this.initial)return G||Y(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=at(this.initialStateValue);return H(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=_(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:Sr(this.states,function(r,n){if(!e)return r.historyValue();var i=U(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?H(at(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=pi(n.path,"states")(e).current;return U(s)?[n.getStateNode(s)]:H(at(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=H(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var u=R(Object.keys(s)),c=u.next();!c.done;c=u.next()){var f=c.value,a=s[f];if(a.states)try{for(var l=(n=void 0,R(a.events)),d=l.next();!d.done;d=l.next()){var h=d.value;o.add("".concat(h))}}catch(v){n={error:v}}finally{try{d&&!d.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!U(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
+
`).concat(u.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Si(e.target),i="internal"in e?e.internal:n?n.some(function(c){return U(c)&&c[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),u=g(g({},e),{actions:ce(re(e.actions)),cond:Ir(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return g(g({},u),{target:u.target?u.target.map(function(c){return"#".concat(c.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=ze,u=s[o],c=u===void 0?[]:u,f=Pt(s,[typeof o=="symbol"?o:o+""]);i=H(Object.keys(f).map(function(T){!G&&T===Pe&&Y(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var b=ke(T,f[T]);return G||rs(n,T,b),b}).concat(ke(ze,c)))}var a=this.config.always?ke("",this.config.always):[],l=this.config.onDone?ke(String(Fe(this.id)),this.config.onDone):[];G||Y(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var d=H(this.invoke.map(function(T){var b=[];return T.onDone&&b.push.apply(b,V([],_(ke(String(qe(T.id)),T.onDone)),!1)),T.onError&&b.push.apply(b,V([],_(ke(String(Ie(T.id)),T.onError)),!1)),b})),h=this.after,v=H(V(V(V(V([],_(l),!1),_(d),!1),_(i),!1),_(a),!1).map(function(T){return re(T).map(function(b){return n.formatTransition(b)})}));try{for(var w=R(h),S=w.next();!S.done;S=w.next()){var E=S.value;v.push(E)}}catch(T){e={error:T}}finally{try{S&&!S.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),zr=!1;function pe(t,e){return!G&&!("predictableActionArguments"in t)&&!zr&&(zr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new ns(t,e)}var I=Lr,X=ge;/*! js-cookie v3.0.5 | MIT */function mt(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 is={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 Ht(t,e){function r(i,s,o){if(typeof document!="undefined"){o=mt({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var c in o)o[c]&&(u+="; "+c,o[c]!==!0&&(u+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+u}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},u=0;u<s.length;u++){var c=s[u].split("="),f=c.slice(1).join("=");try{var a=decodeURIComponent(c[0]);if(o[a]=t.read(f,a),i===a)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",mt({},s,{expires:-1}))},withAttributes:function(i){return Ht(this.converter,mt({},this.attributes,i))},withConverter:function(i){return Ht(mt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Kt=Ht(is,{path:"/"}),zt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Jt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ss(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Wt={exports:{}};(function(t,e){(function(r){function n(i){var s=i&&i.Promise||r.Promise,o=i&&i.XMLHttpRequest||r.XMLHttpRequest;return function(){var u=Object.create(r,{fetch:{value:void 0,writable:!0}});return function(c,f){f(e)}(this,function(c){var f=typeof u!="undefined"&&u||typeof self!="undefined"&&self||typeof f!="undefined"&&f,a={searchParams:"URLSearchParams"in f,iterable:"Symbol"in f&&"iterator"in Symbol,blob:"FileReader"in f&&"Blob"in f&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in f,arrayBuffer:"ArrayBuffer"in f};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(a.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(p){return p&&d.indexOf(Object.prototype.toString.call(p))>-1};function v(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function w(p){return typeof p!="string"&&(p=String(p)),p}function S(p){var m={next:function(){var A=p.shift();return{done:A===void 0,value:A}}};return a.iterable&&(m[Symbol.iterator]=function(){return m}),m}function E(p){this.map={},p instanceof E?p.forEach(function(m,A){this.append(A,m)},this):Array.isArray(p)?p.forEach(function(m){this.append(m[0],m[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(m){this.append(m,p[m])},this)}E.prototype.append=function(p,m){p=v(p),m=w(m);var A=this.map[p];this.map[p]=A?A+", "+m:m},E.prototype.delete=function(p){delete this.map[v(p)]},E.prototype.get=function(p){return p=v(p),this.has(p)?this.map[p]:null},E.prototype.has=function(p){return this.map.hasOwnProperty(v(p))},E.prototype.set=function(p,m){this.map[v(p)]=w(m)},E.prototype.forEach=function(p,m){for(var A in this.map)this.map.hasOwnProperty(A)&&p.call(m,this.map[A],A,this)},E.prototype.keys=function(){var p=[];return this.forEach(function(m,A){p.push(A)}),S(p)},E.prototype.values=function(){var p=[];return this.forEach(function(m){p.push(m)}),S(p)},E.prototype.entries=function(){var p=[];return this.forEach(function(m,A){p.push([A,m])}),S(p)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function T(p){if(p.bodyUsed)return s.reject(new TypeError("Already read"));p.bodyUsed=!0}function b(p){return new s(function(m,A){p.onload=function(){m(p.result)},p.onerror=function(){A(p.error)}})}function O(p){var m=new FileReader,A=b(m);return m.readAsArrayBuffer(p),A}function $(p){var m=new FileReader,A=b(m);return m.readAsText(p),A}function C(p){for(var m=new Uint8Array(p),A=new Array(m.length),q=0;q<m.length;q++)A[q]=String.fromCharCode(m[q]);return A.join("")}function P(p){if(p.slice)return p.slice(0);var m=new Uint8Array(p.byteLength);return m.set(new Uint8Array(p)),m.buffer}function L(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:a.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:a.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():a.arrayBuffer&&a.blob&&l(p)?(this._bodyArrayBuffer=P(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||h(p))?this._bodyArrayBuffer=P(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return s.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return s.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=T(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?s.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):s.resolve(this._bodyArrayBuffer))}else return this.blob().then(O)}),this.text=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(C(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return s.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(F)}),this.json=function(){return this.text().then(JSON.parse)},this}var x=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function K(p){var m=p.toUpperCase();return x.indexOf(m)>-1?m:p}function k(p,m){if(!(this instanceof k))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var A=m.body;if(p instanceof k){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,m.headers||(this.headers=new E(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!A&&p._bodyInit!=null&&(A=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new E(m.headers)),this.method=K(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var q=/([?&])_=[^&]*/;if(q.test(this.url))this.url=this.url.replace(q,"$1_="+new Date().getTime());else{var D=/\?/;this.url+=(D.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}k.prototype.clone=function(){return new k(this,{body:this._bodyInit})};function F(p){var m=new FormData;return p.trim().split("&").forEach(function(A){if(A){var q=A.split("="),D=q.shift().replace(/\+/g," "),M=q.join("=").replace(/\+/g," ");m.append(decodeURIComponent(D),decodeURIComponent(M))}}),m}function z(p){var m=new E,A=p.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(q){return q.indexOf(`
|
|
20
|
+
`)===0?q.substr(1,q.length):q}).forEach(function(q){var D=q.split(":"),M=D.shift().trim();if(M){var Me=D.join(":").trim();m.append(M,Me)}}),m}L.call(k.prototype);function B(p,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in m?m.statusText:"",this.headers=new E(m.headers),this.url=m.url||"",this._initBody(p)}L.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},B.error=function(){var p=new B(null,{status:0,statusText:""});return p.type="error",p};var Ee=[301,302,303,307,308];B.redirect=function(p,m){if(Ee.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:p}})},c.DOMException=f.DOMException;try{new c.DOMException}catch{c.DOMException=function(m,A){this.message=m,this.name=A;var q=Error(m);this.stack=q.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function Te(p,m){return new s(function(A,q){var D=new k(p,m);if(D.signal&&D.signal.aborted)return q(new c.DOMException("Aborted","AbortError"));var M=new o;function Me(){M.abort()}M.onload=function(){var W={status:M.status,statusText:M.statusText,headers:z(M.getAllResponseHeaders()||"")};W.url="responseURL"in M?M.responseURL:W.headers.get("X-Request-URL");var Rt="response"in M?M.response:M.responseText;setTimeout(function(){A(new B(Rt,W))},0)},M.onerror=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},M.ontimeout=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},M.onabort=function(){setTimeout(function(){q(new c.DOMException("Aborted","AbortError"))},0)};function ee(W){try{return W===""&&f.location.href?f.location.href:W}catch{return W}}M.open(D.method,ee(D.url),!0),D.credentials==="include"?M.withCredentials=!0:D.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&(a.blob?M.responseType="blob":a.arrayBuffer&&D.headers.get("Content-Type")&&D.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(M.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof E)?Object.getOwnPropertyNames(m.headers).forEach(function(W){M.setRequestHeader(W,w(m.headers[W]))}):D.headers.forEach(function(W,Rt){M.setRequestHeader(Rt,W)}),D.signal&&(D.signal.addEventListener("abort",Me),M.onreadystatechange=function(){M.readyState===4&&D.signal.removeEventListener("abort",Me)}),M.send(typeof D._bodyInit=="undefined"?null:D._bodyInit)})}Te.polyfill=!0,f.fetch||(f.fetch=Te,f.Headers=E,f.Request=k,f.Response=B),c.Headers=E,c.Request=k,c.Response=B,c.fetch=Te,Object.defineProperty(c,"__esModule",{value:!0})}),{fetch:u.fetch,Headers:u.Headers,Request:u.Request,Response:u.Response,DOMException:u.DOMException}}()}t.exports=n})(typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:zt)})(Wt,Wt.exports);var os=Wt.exports;const Yt=Jt(os),Ue="nhostRefreshToken",Je="nhostRefreshTokenId",me="nhostRefreshTokenExpiresAt",Jr=3,Wr=60,Xt=5,Qt=0,Zt=1,ne=10,De=20;class Ce extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Zt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:ne,error:"invalid-email",message:"Email is incorrectly formatted"},Yr={status:ne,error:"invalid-mfa-type",message:"MFA type is invalid"},Xr={status:ne,error:"invalid-mfa-code",message:"MFA code is invalid"},wt={status:ne,error:"invalid-password",message:"Password is incorrectly formatted"},er={status:ne,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:ne,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Zr={status:ne,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},en={status:ne,error:"no-refresh-token",message:"No refresh token has been provided"},tn={status:De,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},ie={status:De,error:"already-signed-in",message:"User is already signed in"},rn={status:De,error:"unauthenticated-user",message:"User is not authenticated"},as={status:De,error:"user-not-anonymous",message:"User is not anonymous"},nn={status:De,error:"unverified-user",message:"Email needs verification"},sn={status:ne,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},on={status:Zt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Et={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function cs(t){return new TextEncoder().encode(t)}function we(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 tr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let u=0;u<i.length;u++)o[u]=i.charCodeAt(u);return s}function an(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function cn(t){const{id:e}=t;return{...t,id:tr(e),transports:t.transports}}function un(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let Z=class extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}};function us({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 Z("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 Z("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 Z("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new Z("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new Z("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 Z('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new Z("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const s=window.location.hostname;if(un(s)){if(i.rp.id!==s)return new Z(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new Z(`${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 Z("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new Z("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class ls{createNewAbortSignal(){return this.controller&&this.controller.abort("Cancelling existing WebAuthn API call for new one"),this.controller=new AbortController,this.controller.signal}}const ln=new ls;async function dn(t){if(!an())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:tr(t.challenge),user:{...t.user,id:cs(t.user.id)},excludeCredentials:t.excludeCredentials.map(cn)}};e.signal=ln.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(c){throw us({error:c,options:e})}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:s,type:o}=r,u={id:n,rawId:we(i),response:{attestationObject:we(s.attestationObject),clientDataJSON:we(s.clientDataJSON)},type:o,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof s.getTransports=="function"&&(u.transports=s.getTransports()),u}function ds(t){return new TextDecoder("utf-8").decode(t)}async function fs(){const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function hs({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 Z("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new Z("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new Z("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(un(i)){if(n.rpId!==i)return new Z(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new Z(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new Z("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function fn(t,e=!1){var r,n;if(!an())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(cn));const s={...t,challenge:tr(t.challenge),allowCredentials:i},o={};if(e){if(!await fs())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=ln.createNewAbortSignal();let u;try{u=await navigator.credentials.get(o)}catch(h){throw hs({error:h,options:o})}if(!u)throw new Error("Authentication was not completed");const{id:c,rawId:f,response:a,type:l}=u;let d;return a.userHandle&&(d=ds(a.userHandle)),{id:c,rawId:we(f),response:{authenticatorData:we(a.authenticatorData),clientDataJSON:we(a.clientDataJSON),signature:we(a.signature),userHandle:d},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const Tt=typeof window!="undefined",St=new Map,ps=t=>{var e;return Tt&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=St.get(t))!=null?e:null},vs=(t,e)=>{Tt&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?St.set(t,e):St.has(t)&&St.delete(t)},hn=(t,e)=>{if(t==="localStorage"||t==="web")return ps;if(t==="cookie")return r=>{var n;return Tt&&(n=Kt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},pn=(t,e)=>{if(t==="localStorage"||t==="web")return vs;if(t==="cookie")return(r,n)=>{Tt&&(n?Kt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Kt.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}`)},We=t=>!t||!t.accessToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},le=({accessToken:t,refreshToken:e,isError:r,user:n,error:i})=>r?{session:null,error:i}:n&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:e,user:n},error:null}:{session:null,error:null},bt=()=>typeof window!="undefined";let vn=globalThis.fetch;typeof EdgeRuntime!="string"&&(vn=Yt().fetch);const yn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await vn(t,s);if(!o.ok){const u=await o.json();return Promise.reject({error:u})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:o})}},te=async(t,e,r)=>yn(t,"POST",{token:r,body:e}),gn=(t,e)=>yn(t,"GET",{token:e}),rr=(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},se=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(o.search);let c=Object.fromEntries(u);r.startsWith("/")&&(c={...s,...c});let f=i.pathname;return o.pathname.length>1&&(f+=o.pathname.slice(1)),{...n,redirectTo:rr(o.origin+f,c)}};function Ye(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function nr(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const 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,}))$/),At=t=>!!t&&typeof t=="string"&&t.length>=Jr,ir=t=>!!t&&typeof t=="string",mn=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),wn=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const u=hn(r,n),c=pn(r,n),f=async(a,l,d)=>(await te(`${t}${a}`,l,d)).data;return pe({schema:{context:{},events:{},services:{}},tsTypes:{},context:Et,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:I({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:I(()=>(c(me,null),c(Ue,null),c(Je,null),{...Et})),clearContextExceptRefreshToken:I(({refreshToken:{value:a}})=>(c(me,null),{...Et,refreshToken:{value:a}})),saveSession:I({user:(a,{data:l})=>{var d;return((d=l==null?void 0:l.session)==null?void 0:d.user)||null},accessToken:(a,{data:l})=>{if(l.session){const{accessTokenExpiresIn:d,accessToken:h}=l.session,v=new Date(Date.now()+d*1e3);return c(me,v.toISOString()),{value:h,expiresAt:v,expiresInSeconds:d}}return c(me,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:l})=>{var d,h;const v=((d=l.session)==null?void 0:d.refreshToken)||null,w=((h=l.session)==null?void 0:h.refreshTokenId)||null;return v&&c(Ue,v),w&&c(Je,w),{value:v}}}),savePATSession:I({user:(a,{data:l})=>{var d;return((d=l==null?void 0:l.session)==null?void 0:d.user)||null},accessToken:(a,{data:l})=>{if(l.session){const{accessTokenExpiresIn:d,accessToken:h}=l.session,v=new Date(Date.now()+d*1e3);return c(me,v.toISOString()),{value:h,expiresAt:v,expiresInSeconds:d}}return c(me,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:l})=>{var d,h;const v=((d=l.session)==null?void 0:d.refreshToken)||null,w=((h=l.session)==null?void 0:h.refreshTokenId)||null;return v&&c(Ue,v),w&&c(Je,w),{value:v,isPAT:!0}}}),saveMfaTicket:I({mfa:(a,l)=>{var d;return(d=l.data)==null?void 0:d.mfa}}),resetTimer:I({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:I({refreshTimer:(a,l)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:I({errors:({errors:a},{data:{error:l}})=>({...a,authentication:l})}),resetErrors:I({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:I({errors:({errors:a},{data:{error:l}})=>({...a,registration:l})}),destroyRefreshToken:I({refreshToken:a=>(c(Ue,null),c(Je,null),{value:null})}),cleanUrl:()=>{o&&Ye("refreshToken")&&(nr("refreshToken"),nr("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage(a.refreshToken.value)}catch{}}},guards:{isAnonymous:(a,l)=>{var d;return!!((d=a.user)!=null&&d.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var l;return!!((l=a.refreshToken)!=null&&l.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:l}=a.accessToken;if(!l)return!1;if(l.getTime()<Date.now())return!0;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>Xt?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const d=a.accessToken.expiresInSeconds;return d?l.getTime()-Date.now()-1e3*Math.min(Wr,d*.5)<=0:!1},shouldRetryImportToken:(a,l)=>a.importTokenAttempts<Xt&&(l.data.error.status===Qt||l.data.error.status>=500),unverified:(a,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(a,l)=>{var d;return!!((d=l.data)!=null&&d.session)},hasMfaTicket:(a,l)=>{var d;return!!((d=l.data)!=null&&d.mfa)}},services:{signInPassword:(a,{email:l,password:d})=>de(l)?At(d)?f("/signin/email-password",{email:l,password:d}):Promise.reject({error:wt}):Promise.reject({error:ue}),signInPAT:(a,{pat:l})=>f("/signin/pat",{personalAccessToken:l}),passwordlessSms:(a,{phoneNumber:l,options:d})=>{var h;return ir(l)?(h=a.user)!=null&&h.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:se(e,d)},a.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:se(e,d)}):Promise.reject({error:er})},passwordlessSmsOtp:(a,{phoneNumber:l,otp:d})=>ir(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:d}):Promise.reject({error:er}),passwordlessEmail:(a,{email:l,options:d})=>{var h;return de(l)?(h=a.user)!=null&&h.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:se(e,d)},a.accessToken.value):f("/signin/passwordless/email",{email:l,options:se(e,d)}):Promise.reject({error:ue})},signInAnonymous:a=>f("/signin/anonymous"),signInMfaTotp:(a,l)=>{var d;const h=l.ticket||((d=a.mfa)==null?void 0:d.ticket);return h?mn(h)?f("/signin/mfa/totp",{ticket:h,otp:l.otp}):Promise.reject({error:Qr}):Promise.reject({error:Zr})},signInSecurityKeyEmail:async(a,{email:l})=>{if(!de(l))throw new Ce(ue);const d=await f("/signin/webauthn",{email:l});let h;try{h=await fn(d)}catch(v){throw new Ce(v)}return f("/signin/webauthn/verify",{email:l,credential:h})},refreshToken:async(a,l)=>{const d=l.type==="TRY_TOKEN"?l.token:a.refreshToken.value;return{session:await f("/token",{refreshToken:d}),error:null}},signout:(a,l)=>f("/signout",{refreshToken:a.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(a,{email:l,password:d,options:h})=>{var v;return de(l)?At(d)?(v=a.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:d,options:se(e,h)},a.accessToken.value):f("/signup/email-password",{email:l,password:d,options:se(e,h)}):Promise.reject({error:wt}):Promise.reject({error:ue})},signUpSecurityKey:async(a,{email:l,options:d})=>{if(!de(l))return Promise.reject({error:ue});const h=d==null?void 0:d.nickname;h&&delete d.nickname;const v=await f("/signup/webauthn",{email:l,options:d});let w;try{w=await dn(v)}catch(S){throw new Ce(S)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:d==null?void 0:d.redirectTo,nickname:h}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let l=null;if(o){const h=Ye("refreshToken")||null;if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(v){l=v.error}else{const v=Ye("error");if(v)return Promise.reject({session:null,error:{status:ne,error:v,message:Ye("errorDescription")||v}})}}const d=await u(Ue);if(d)try{return{session:await f("/token",{refreshToken:d}),error:null}}catch(h){l=h.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},En=({backendUrl:t,clientUrl:e,interpreter:r})=>pe({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:I({error:n=>ue}),saveRequestError:I({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:s})=>(await te(`${t}/user/email/change`,{newEmail:i,options:se(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),Tn=({backendUrl:t,interpreter:e})=>pe({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:I({error:r=>wt}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!At(n)},services:{requestChange:(r,{password:n,ticket:i})=>te(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ys=({backendUrl:t,interpreter:e})=>pe({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:I({error:r=>Yr}),saveInvalidMfaCodeError:I({error:r=>Xr}),saveError:I({error:(r,{data:{error:n}})=>n}),saveGeneration:I({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:X((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS"),reportGeneratedSuccess:X("GENERATED"),reportGeneratedError:X(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 gn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>te(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Sn=({backendUrl:t,clientUrl:e})=>pe({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:I({error:r=>ue}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:se(e,i)})}}),bn=({backendUrl:t,clientUrl:e})=>pe({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:I({error:r=>ue}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await te(`${t}/user/email/send-verification-email`,{email:n,options:se(e,i)})).data}});class sr{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:u,...c}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=wn({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var a;const l=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||Re(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class An extends sr{constructor({...e}){super({...e,autoSignIn:bt()&&e.autoSignIn,autoRefreshToken:bt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const gs=An,kn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await te(`${t}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await dn(n)}catch(o){throw new Ce(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},On=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})})}),In=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})})}),ms=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:""})})}),ws=(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})})}),xn=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})})}),Rn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Pn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:ie,user:null,accessToken:null,refreshToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value,refreshToken:n.context.refreshToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),_n=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ie,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),or=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:ie,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})})}),Nn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:ie,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),Un=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:u}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let c;try{c=await fn(u)}catch(f){throw new Ce(f)}try{const{data:{session:f},error:a}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:c},o);f&&!a&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:f}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(f){const{error:a}=f;r({error:a,isError:!0,isSuccess:!1,elevated:!1})}}),Dn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ie,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Cn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:ie,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:ie,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Mn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:ie,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),jn=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:rn});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})})}),cr=(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:ie,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),Ln=(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:ie,accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Es=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.toUTCString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1,data:null}}};class $n{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:u=!0}){var c;this.url=e,this._client=new sr({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?le(await Ln(r,n,i)):le(await cr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Pn(r);return{...le(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=rr(`${this._client.backendUrl}/signin/provider/${n}`,se(this._client.clientUrl,i));return bt()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await _n(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:nn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...le(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Nn(r,e.email);return{...le(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await or(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Mn(r,e.phoneNumber,e.otp);return{...le(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Dn(r,e.otp,e.ticket);return{...le(n),mfa:null}}return{error:on,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Cn(r,e);return le(n)}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await jn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=Re(Sn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=Re(Tn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=Re(bn(this._client)).start(),{error:i}=await Rn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=Re(En(this._client)).start(),{error:i}=await On(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 or(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await cr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await kn(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Un(this._client,e),mfa:null}}async createPAT(e,r){return Es(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(We(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,We(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?oi(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:en});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:tn});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:sn}):o.event.type==="TOKEN_CHANGED"&&n({session:We(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return We((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Ts=typeof self=="object"?self.FormData:window.FormData;const ur=Jt(Ts);let Fn=globalThis.fetch;const lr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u,headers:c={}}={})=>{var f;const a={...c};s&&e.append("bucket-id",s),o&&(a["x-hasura-admin-secret"]=o),r&&(a.Authorization=`Bearer ${r}`);const l=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof ur&&(Fn=Yt().fetch);const d=await Fn(l,{method:"POST",headers:a,body:e}),h=await d.json();return d.ok?{fileMetadata:h,error:null}:{error:{status:d.status,message:((f=h==null?void 0:h.error)==null?void 0:f.message)||d.statusText,error:d.statusText},fileMetadata:null}}catch(d){return{error:{status:0,message:d.message,error:d.message},fileMetadata:null}}return new Promise(d=>{let h=new XMLHttpRequest;h.responseType="json",h.onload=()=>{var v,w,S,E,T;return h.status<200||h.status>=300?d({fileMetadata:null,error:{error:(w=(v=h.response)==null?void 0:v.error)!=null?w:h.response,message:(T=(E=(S=h.response)==null?void 0:S.error)==null?void 0:E.message)!=null?T:h.response,status:h.status}}):d({fileMetadata:h.response,error:null})},h.onerror=()=>d({fileMetadata:null,error:{error:h.statusText,message:h.statusText,status:h.status}}),u&&h.upload.addEventListener("progress",u,!1),h.open("POST",l,!0),Object.entries(a).forEach(([v,w])=>{h.setRequestHeader(v,w)}),h.send(e)})};function kt(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}let Xe;typeof Xe=="undefined"&&(Xe=Yt().fetch);class qn{constructor({url:e}){this.url=e}async uploadFormData({formData:e,headers:r,bucketId:n}){const{error:i,fileMetadata:s}=await lr(this.url,e,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:n,headers:r});return i?{fileMetadata:null,error:i}:s&&!("processedFiles"in s)?{fileMetadata:{processedFiles:[s]},error:null}:{fileMetadata:s,error:null}}async uploadFile({file:e,bucketId:r,id:n,name:i}){const s=typeof window=="undefined"?new ur:new FormData;s.append("file[]",e),s.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:o,fileMetadata:u}=await lr(this.url,s,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:r,fileId:n,name:i});return o?{fileMetadata:null,error:o}:u&&"processedFiles"in u?{fileMetadata:u.processedFiles[0],error:null}:{fileMetadata:u,error:null}}async downloadFile(e){try{const{fileId:r,headers:n={},...i}=e,s=kt(`${this.url}/files/${r}`,i),o=await Xe(s,{method:"GET",headers:{...this.generateAuthHeaders(),...n}});if(!o.ok)throw new Error(await o.text());return{file:await o.blob(),error:null}}catch(r){return{file:null,error:r}}}async getPresignedUrl(e){try{const{fileId:r}=e,n=await Xe(`${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 Xe(`${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}`}}}class Vn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new qn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return kt(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,...n}=e,{presignedUrl:i,error:s}=await this.api.getPresignedUrl(e);if(s)return{presignedUrl:null,error:s};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const o=kt(i.url,n);return{presignedUrl:{...i,url:o},error:null}}async download(e){const{file:r,error:n}=await this.api.downloadFile(e);return n?{file:null,error:n}:r?{file:r,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}let dr;typeof dr=="undefined"&&(dr=ur);const Ot={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Bn=()=>pe({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...Ot},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:I({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:I({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:I({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:I({progress:t=>null,loaded:t=>0}),resetContext:I(t=>Ot),addFile:I({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new dr;i.append("file[]",n);let s=0;return lr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o&&!("processedFiles"in o)){const{id:c,bucketId:f}=o;r({type:"UPLOAD_DONE",id:c,bucketId:f})}if(o&&"processedFiles"in o){const{id:c,bucketId:f}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:c,bucketId:f})}}),()=>{}}}}),{pure:fr,sendParent:It}=Ci,Ss=()=>pe({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:I((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:I({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:I({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:I({loaded:t=>0}),startProgress:I({progress:t=>0}),resetProgress:I({progress:t=>null}),addItem:I((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,u)=>o+u.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Zi(Bn().withConfig({actions:{sendProgress:It((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:It("UPLOAD_DONE"),sendError:It("UPLOAD_ERROR"),sendDestroy:It("REMOVE")}}).withContext({...Ot,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:I({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:fr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:fr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:fr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),bs=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})})}),As=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})})}),ks=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Qe(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(ks);if(i!=null&&i.groups){const{protocol:s,host:o,port:u}=i.groups,c=xs(e);return c||(o==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${s||"http"}://localhost:${u||1337}/v1/${e}`):u?`${s||"https"}://local.${e}.nhost.run:${u}/v1`:`${s||"https"}://local.${e}.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${e}.${n}.nhost.run/v1`}function Os(){return typeof window!="undefined"}function Is(){return typeof process!="undefined"&&process.env}function xs(t){return Os()||!Is()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Rs(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Gn(t){const e="subdomain"in t?Qe(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new $n({url:e,...t})}function Ps(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},c=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(a){return u[a.toLowerCase()]},has:function(a){return a.toLowerCase()in u}}}};for(var f in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,l,d){s.push(l=l.toLowerCase()),o.push([l,d]),u[l]=u[l]?u[l]+","+d:d}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(f,e.headers[f]);i.send(e.body||null)})}const Hn=ss(Object.freeze(Object.defineProperty({__proto__:null,default:Ps},Symbol.toStringTag,{value:"Module"})));var _s=self.fetch||(self.fetch=Hn.default||Hn);const Kn=Jt(_s);function zn(t){const e="subdomain"in t?Qe(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Jn({url:e,...t})}class Jn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,u;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s=Rs(this.url,e);try{const c=await Kn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let f;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?f=await c.json():f=await c.text(),{res:{data:f,status:c.status,statusText:c.statusText},error:null}}catch(c){const f=c;return{res:null,error:{message:f.message,status:f.name==="AbortError"?0:500,error:f.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function hr(t){this.message=t}hr.prototype=new Error,hr.prototype.name="InvalidCharacterError";var Wn=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new hr("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,n,i=0,s=0,o="";n=e.charAt(s++);~n&&(r=i%4?64*r+n:n,i++%4)?o+=String.fromCharCode(255&r>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return o};function Ns(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(Wn(r).replace(/(.)/g,function(n,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return Wn(e)}}function xt(t){this.message=t}function Us(t,e){if(typeof t!="string")throw new xt("Invalid token specified");var r=(e=e||{}).header===!0?0:1;try{return JSON.parse(Ns(t.split(".")[r]))}catch(n){throw new xt("Invalid token specified: "+n.message)}}xt.prototype=new Error,xt.prototype.name="InvalidTokenError";function Ds(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Yn(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 Cs(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Yn(n)}catch{}return{query:t,operationName:r}}const e=Yn(t);return{query:Se.print(t),operationName:e}}class Ms{constructor(e){this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const i=Us(this.accessToken);return i.exp!=null&&i.exp*1e3>Date.now()}catch(i){return console.error("Error decoding token:",i),!1}},this.awaitForValidAccessTokenOrNull=async()=>{if(this.isAccessTokenValidOrNull())return!0;const i=()=>this.isAccessTokenValidOrNull()?Promise.resolve(!0):new Promise(s=>{setTimeout(()=>i().then(s),100)});return i()};const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=Ds(e,n,i),{headers:o,...u}=i||{},{query:c,operationName:f}=Cs(s.document);process.env.TEST_MODE||await this.awaitForValidAccessTokenOrNull();try{const a=await Kn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...o},...u});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:l,errors:d}=await a.json();return d?{data:null,error:d}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(a){const l=a;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Xn(t){const e="subdomain"in t?Qe(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Ms({url:e,...t})}function Qn(t){const e="subdomain"in t?Qe(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Vn({url:e,...t})}const js=t=>new Zn(t);class Zn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...f}){this.auth=Gn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...f}),this.storage=Qn({adminSecret:o,...f}),this.functions=zn({adminSecret:o,...f}),this.graphql=Xn({adminSecret:o,...f}),this.auth.onAuthStateChanged((a,l)=>{if(a==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const d=l==null?void 0:l.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this.auth.onTokenChanged(a=>{const l=a==null?void 0:a.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}y.AuthClient=sr,y.AuthClientSSR=gs,y.AuthCookieClient=An,y.CodifiedError=Ce,y.EMAIL_NEEDS_VERIFICATION=nn,y.HasuraAuthClient=$n,y.HasuraStorageApi=qn,y.HasuraStorageClient=Vn,y.INITIAL_FILE_CONTEXT=Ot,y.INITIAL_MACHINE_CONTEXT=Et,y.INVALID_EMAIL_ERROR=ue,y.INVALID_MFA_CODE_ERROR=Xr,y.INVALID_MFA_TICKET_ERROR=Qr,y.INVALID_MFA_TYPE_ERROR=Yr,y.INVALID_PASSWORD_ERROR=wt,y.INVALID_PHONE_NUMBER_ERROR=er,y.INVALID_REFRESH_TOKEN=sn,y.INVALID_SIGN_IN_METHOD=on,y.MIN_PASSWORD_LENGTH=Jr,y.NETWORK_ERROR_CODE=Qt,y.NHOST_JWT_EXPIRES_AT_KEY=me,y.NHOST_REFRESH_TOKEN_ID_KEY=Je,y.NHOST_REFRESH_TOKEN_KEY=Ue,y.NO_MFA_TICKET_ERROR=Zr,y.NO_REFRESH_TOKEN=en,y.NhostClient=Zn,y.NhostFunctionsClient=Jn,y.OTHER_ERROR_CODE=Zt,y.REFRESH_TOKEN_MAX_ATTEMPTS=Xt,y.STATE_ERROR_CODE=De,y.TOKEN_REFRESHER_RUNNING_ERROR=tn,y.TOKEN_REFRESH_MARGIN_SECONDS=Wr,y.USER_ALREADY_SIGNED_IN=ie,y.USER_NOT_ANONYMOUS=as,y.USER_UNAUTHENTICATED=rn,y.VALIDATION_ERROR_CODE=ne,y.activateMfaPromise=ws,y.addSecurityKeyPromise=kn,y.appendImageTransformationParameters=kt,y.changeEmailPromise=On,y.changePasswordPromise=In,y.createAuthClient=Gn,y.createAuthMachine=wn,y.createChangeEmailMachine=En,y.createChangePasswordMachine=Tn,y.createEnableMfaMachine=ys,y.createFileUploadMachine=Bn,y.createFunctionsClient=zn,y.createGraphqlClient=Xn,y.createMultipleFilesUploadMachine=Ss,y.createNhostClient=js,y.createResetPasswordMachine=Sn,y.createSendVerificationEmailMachine=bn,y.createStorageClient=Qn,y.elevateEmailSecurityKeyPromise=Un,y.encodeQueryParameters=rr,y.generateQrCodePromise=ms,y.getAuthenticationResult=le,y.getFetch=gn,y.getParameterByName=Ye,y.getSession=We,y.isBrowser=bt,y.isValidEmail=de,y.isValidPassword=At,y.isValidPhoneNumber=ir,y.isValidTicket=mn,y.localStorageGetter=hn,y.localStorageSetter=pn,y.postFetch=te,y.removeParameterFromWindow=nr,y.resetPasswordPromise=xn,y.rewriteRedirectTo=se,y.sendVerificationEmailPromise=Rn,y.signInAnonymousPromise=Pn,y.signInEmailPasswordPromise=_n,y.signInEmailPasswordlessPromise=or,y.signInEmailSecurityKeyPromise=Nn,y.signInMfaTotpPromise=Dn,y.signInPATPromise=Cn,y.signInSmsPasswordlessOtpPromise=Mn,y.signInSmsPasswordlessPromise=ar,y.signOutPromise=jn,y.signUpEmailPasswordPromise=cr,y.signUpEmailSecurityKeyPromise=Ln,y.uploadFilePromise=bs,y.uploadMultipleFilesPromise=As,y.urlFromSubdomain=Qe,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
|
|
21
21
|
//# sourceMappingURL=nhost-js.umd.js.map
|