@nhost/nhost-js 1.1.8 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -29,7 +29,7 @@ Event: `).concat(JSON.stringify(f.data))),n.state;if(n.status!==H.Running&&!n.op
29
29
  Event: `).concat(JSON.stringify(f.data)));return n.scheduler.schedule(function(){n.forward(f);var l=n.nextState(f);n.update(l,f)}),n._state},this.sendTo=function(c,h){var f=n.parent&&(h===Ee.Parent||n.parent.id===h),l=f?n.parent:P(h)?n.children.get(h)||gt.get(h):Ai(h)?h:void 0;if(!l){if(!f)throw new Error("Unable to send event to child '".concat(h,"' from service '").concat(n.id,"'."));j||B(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(c.type));return}"machine"in l?l.send(g(g({},c),{name:c.name===Mr?"".concat(Oe(n.id)):c.name,origin:n.sessionId})):l.send(c.data)};var i=g(g({},t.defaultOptions),r),s=i.clock,a=i.logger,o=i.parent,u=i.id,d=u!==void 0?u:e.id;this.id=d,this.logger=a,this.clock=s,this.parent=o,this.options=i,this.scheduler=new zr({deferEvents:this.options.deferEvents}),this.sessionId=gt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:Ce(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return j||B(this.status!==H.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),a=s.next();!a.done;a=s.next()){var o=a.value;this.exec(o,e,r)}}catch(u){n={error:u}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,a,o,u,d,c,h=this;if(e._sessionid=this.sessionId,this._state=e,this.options.execute&&this.execute(this.state),this.children.forEach(function(A){h.state.children[A.id]=A}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var f=R(this.eventListeners),l=f.next();!l.done;l=f.next()){var p=l.value;p(e.event)}}catch(A){n={error:A}}finally{try{l&&!l.done&&(i=f.return)&&i.call(f)}finally{if(n)throw n.error}}try{for(var v=R(this.listeners),m=v.next();!m.done;m=v.next()){var p=m.value;p(e,e.event)}}catch(A){s={error:A}}finally{try{m&&!m.done&&(a=v.return)&&a.call(v)}finally{if(s)throw s.error}}try{for(var x=R(this.contextListeners),E=x.next();!E.done;E=x.next()){var T=E.value;T(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(A){o={error:A}}finally{try{E&&!E.done&&(u=x.return)&&u.call(x)}finally{if(o)throw o.error}}var O=Ie(e.configuration||[],this.machine);if(this.state.configuration&&O){var N=e.configuration.find(function(A){return A.type==="final"&&A.parent===h.machine}),M=N&&N.doneData?Te(N.doneData,e.context,r):void 0;try{for(var b=R(this.doneListeners),w=b.next();!w.done;w=b.next()){var p=w.value;p(Re(this.id,M))}}catch(A){d={error:A}}finally{try{w&&!w.done&&(c=b.return)&&c.call(b)}finally{if(d)throw d.error}}this.stop()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===H.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this;if(!e)return{unsubscribe:function(){}};var s,a=n;return typeof e=="function"?s=e:(s=e.next.bind(e),a=e.complete.bind(e)),this.listeners.add(s),this.status!==H.NotStarted&&s(this.state),a&&(this.status===H.Stopped?a():this.onDone(a)),{unsubscribe:function(){s&&i.listeners.delete(s),a&&i.doneListeners.delete(a)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===H.Running)return this;this.machine._init(),gt.register(this.sessionId,this),this.initialized=!0,this.status=H.Running;var n=e===void 0?this.initialState:Ce(this,function(){return Gi(e)?r.machine.resolveState(e):r.machine.resolveState(se.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,Ae)}),this},t.prototype.stop=function(){var e,r,n,i,s,a,o,u,d,c,h=this;try{for(var f=R(this.listeners),l=f.next();!l.done;l=f.next()){var p=l.value;this.listeners.delete(p)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(r=f.return)&&r.call(f)}finally{if(e)throw e.error}}try{for(var v=R(this.stopListeners),m=v.next();!m.done;m=v.next()){var p=m.value;p(),this.stopListeners.delete(p)}}catch(w){n={error:w}}finally{try{m&&!m.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var x=R(this.contextListeners),E=x.next();!E.done;E=x.next()){var p=E.value;this.contextListeners.delete(p)}}catch(w){s={error:w}}finally{try{E&&!E.done&&(a=x.return)&&a.call(x)}finally{if(s)throw s.error}}try{for(var T=R(this.doneListeners),O=T.next();!O.done;O=T.next()){var p=O.value;this.doneListeners.delete(p)}}catch(w){o={error:w}}finally{try{O&&!O.done&&(u=T.return)&&u.call(T)}finally{if(o)throw o.error}}if(!this.initialized)return this;k([],C(this.state.configuration),!1).sort(function(w,A){return A.order-w.order}).forEach(function(w){var A,q;try{for(var V=R(w.definition.exit),Q=V.next();!Q.done;Q=V.next()){var ge=Q.value;h.exec(ge,h.state)}}catch(It){A={error:It}}finally{try{Q&&!Q.done&&(q=V.return)&&q.call(V)}finally{if(A)throw A.error}}}),this.children.forEach(function(w){_(w.stop)&&w.stop()}),this.children.clear();try{for(var N=R(Object.keys(this.delayedEventsMap)),M=N.next();!M.done;M=N.next()){var b=M.value;this.clock.clearTimeout(this.delayedEventsMap[b])}}catch(w){d={error:w}}finally{try{M&&!M.done&&(c=N.return)&&c.call(N)}finally{if(d)throw d.error}}return this.scheduler.clear(),this.scheduler=new zr({deferEvents:this.options.deferEvents}),this.initialized=!1,this.status=H.Stopped,this._initialState=void 0,gt.free(this.sessionId),this},t.prototype.batch=function(e){var r=this;if(this.status===H.NotStarted&&this.options.deferEvents)j||B(!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.
30
30
  Event: `).concat(JSON.stringify(event)));else if(this.status!==H.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.'));this.scheduler.schedule(function(){var n,i,s=r.state,a=!1,o=[],u=function(f){var l=F(f);r.forward(l),s=Ce(r,function(){return r.machine.transition(s,l)}),o.push.apply(o,k([],C(s.actions.map(function(p){return Ji(p,s)})),!1)),a=a||!!s.changed};try{for(var d=R(e),c=d.next();!c.done;c=d.next()){var h=c.value;u(h)}}catch(f){n={error:f}}finally{try{c&&!c.done&&(i=d.return)&&i.call(d)}finally{if(n)throw n.error}}s.changed=a,s.actions=o,r.update(s,F(e[e.length-1]))})},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype.nextState=function(e){var r=this,n=F(e);if(n.name.indexOf(jr)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(jr)===0}))throw n.data.data;var i=Ce(this,function(){return r.machine.transition(r.state,n)});return i},t.prototype.forward=function(e){var r,n;try{for(var i=R(this.forwardTo),s=i.next();!s.done;s=i.next()){var a=s.value,o=this.children.get(a);if(!o)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(a,"'."));o.send(e)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions);var i=r.context,s=r._event,a=e.exec||Jt(e.type,n),o=_(a)?a:a?a.exec:e.exec;if(o)try{return o(i,s.data,{action:e,state:this.state,_event:s})}catch(O){throw this.parent&&this.parent.send({type:"xstate.error",data:O}),O}switch(e.type){case xe:var u=e;if(typeof u.delay=="number"){this.defer(u);return}else u.to?this.sendTo(u._event,u.to):this.send(u._event);break;case kt:this.cancel(e.sendId);break;case it:{if(this.status!==H.Running)return;var d=e.activity;if(!this.state.activities[d.id||d.type])break;if(d.type===I.Invoke){var c=Gt(d.src),h=this.machine.options.services?this.machine.options.services[c.type]:void 0,f=d.id,l=d.data;j||B(!("forward"in d),"`forward` property is deprecated (found in invocation of '".concat(d.src,"' in in machine '").concat(this.machine.id,"'). ")+"Please use `autoForward` instead.");var p="autoForward"in d?d.autoForward:!!d.forward;if(!h){j||B(!1,"No service found for invocation '".concat(d.src,"' in machine '").concat(this.machine.id,"'."));return}var v=l?Te(l,i,s):void 0;if(typeof h=="string")return;var m=_(h)?h(i,s.data,{data:v,src:c,meta:d.meta}):h;if(!m)return;var x=void 0;de(m)&&(m=v?m.withContext(v):m,x={autoForward:p}),this.spawn(m,f,x)}else this.spawnActivity(d);break}case Me:{this.stopChild(e.activity.id);break}case qt:var E=e.label,T=e.value;E?this.logger(E,T):this.logger(T);break;default:j||B(!1,"No implementation found for action type '".concat(e.type,"'"));break}},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);!r||(this.removeChild(e),_(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(Fr(e))return this.spawnPromise(Promise.resolve(e),r);if(_(e))return this.spawnCallback(e,r);if(Mi(e))return this.spawnActor(e,r);if(bi(e))return this.spawnObservable(e,r);if(de(e))return this.spawnMachine(e,g(g({},n),{id:r}));if(wi(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({},Sc),r);s.sync&&i.onTransition(function(o){n.send(at,{state:o,id:i.id})});var a=i;return this.children.set(i.id,a),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(o){n.removeChild(i.id),n.send(F(o,{origin:i.id}))}).start(),a},t.prototype.spawnBehavior=function(e,r){var n=zi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,a;e.then(function(u){s||(a=u,i.removeChild(r),i.send(F(Re(r,u),{origin:r})))},function(u){if(!s){i.removeChild(r);var d=Oe(r,u);try{i.send(F(d,{origin:r}))}catch(c){Oi(u,c,r),i.devTools&&i.devTools.send(d,i.state),i.machine.strict&&i.stop()}}});var o=(n={id:r,send:function(){},subscribe:function(u,d,c){var h=ft(u,d,c),f=!1;return e.then(function(l){f||(h.next(l),!f&&h.complete())},function(l){f||h.error(l)}),{unsubscribe:function(){return f=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return a}},n[fe]=function(){return this},n);return this.children.set(r,o),o},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,a=new Set,o=new Set,u,d=function(f){u=f,o.forEach(function(l){return l(f)}),!s&&i.send(F(f,{origin:r}))},c;try{c=e(d,function(f){a.add(f)})}catch(f){this.send(Oe(r,f))}if(Fr(c))return this.spawnPromise(c,r);var h=(n={id:r,send:function(f){return a.forEach(function(l){return l(f)})},subscribe:function(f){var l=ft(f);return o.add(l.next),{unsubscribe:function(){o.delete(l.next)}}},stop:function(){s=!0,_(c)&&c()},toJSON:function(){return{id:r}},getSnapshot:function(){return u}},n[fe]=function(){return this},n);return this.children.set(r,h),h},t.prototype.spawnObservable=function(e,r){var n,i=this,s,a=e.subscribe(function(u){s=u,i.send(F(u,{origin:r}))},function(u){i.removeChild(r),i.send(F(Oe(r,u),{origin:r}))},function(){i.removeChild(r),i.send(F(Re(r),{origin:r}))}),o=(n={id:r,send:function(){},subscribe:function(u,d,c){return e.subscribe(u,d,c)},stop:function(){return a.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[fe]=function(){return this},n);return this.children.set(r,o),o},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){j||B(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[fe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Wt();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)}$i(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[fe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===H.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=me,t}();function me(t,e){var r=new Wi(t,e);return r}function wc(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function Et(t){return g(g({type:st},t),{toJSON:function(){t.onDone,t.onError;var e=je(t,["onDone","onError"]);return g(g({},e),{type:st,src:wc(t.src)})}})}var Je="",Kr="#",St="*",He={},Ge=function(t){return t[0]===Kr},xc=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Tc=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(P(s.target)||de(s.target))}),i=e===Je?"the transient event":"event '".concat(e,"'");B(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Ki=function(){function t(e,r,n,i){var s=this;n===void 0&&(n="context"in e?e.context:void 0);var a;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(xc(),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:Ut),this.id=this.config.id||k([this.machine.key],C(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:(a=this.config.schema)!==null&&a!==void 0?a:{},this.description=this.config.description,j||B(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?Fe(this.config.states,function(d,c){var h,f=new t(d,{},void 0,{parent:s,key:c});return Object.assign(s.idMap,g((h={},h[f.id]=f,h),f.idMap)),f}):He;var o=0;function u(d){var c,h;d.order=o++;try{for(var f=R(Pe(d)),l=f.next();!l.done;l=f.next()){var p=l.value;u(p)}}catch(v){c={error:v}}finally{try{l&&!l.done&&(h=f.return)&&h.call(f)}finally{if(c)throw c.error}}}u(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(d){var c=d.event;return c===Je}):Je in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=ee(this.config.entry||this.config.onEntry).map(function(d){return Ve(d)}),this.onExit=ee(this.config.exit||this.config.onExit).map(function(d){return Ve(d)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=ee(this.config.invoke).map(function(d,c){var h,f;if(de(d)){var l=dt(s.id,c);return s.machine.options.services=g((h={},h[l]=d,h),s.machine.options.services),Et({src:l,id:l})}else if(P(d.src)){var l=d.id||dt(s.id,c);return Et(g(g({},d),{id:l,src:d.src}))}else if(de(d.src)||_(d.src)){var l=d.id||dt(s.id,c);return s.machine.options.services=g((f={},f[l]=d.src,f),s.machine.options.services),Et(g(g({id:l},d),{src:l}))}else{var p=d.src;return Et(g(g({id:dt(s.id,c)},d),{src:p}))}}),this.activities=ee(this.config.activities).concat(this.invoke).map(function(d){return zt(d)}),this.transition=this.transition.bind(this),this.tags=ee(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Gr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,a=n.guards,o=n.services,u=n.delays;return new t(this.config,{actions:g(g({},i),e.actions),activities:g(g({},s),e.activities),guards:g(g({},a),e.guards),services:g(g({},o),e.services),delays:g(g({},u),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return _(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:Fe(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===Je,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===St});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,a){var o=_(s)?"".concat(e.id,":delay[").concat(a,"]"):s,u=ki(o,e.id);return e.onEntry.push(pt(u,{delay:s})),e.onExit.push(Pi(u)),u},i=ve(r)?r.map(function(s,a){var o=n(s.delay,a);return g(g({},s),{event:o})}):U(Object.keys(r).map(function(s,a){var o=r[s],u=P(o)?{target:o}:o,d=isNaN(+s)?s:+s,c=n(d,a);return ee(u).map(function(h){return g(g({},h),{event:c,delay:d})})}));return i.map(function(s){var a=s.delay;return g(g({},e.formatTransition(s)),{delay:a})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof se?e.value:Be(e,this.delimiter);if(P(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var a=Object.keys(i),o=[this];return o.push.apply(o,k([],C(U(a.map(function(u){return n.getStateNode(u).getStateNodes(i[u])}))),!1)),o},t.prototype.handles=function(e){var r=Lt(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof se?e:se.create(e),n=Array.from(Ne([],this.getStateNodes(r.value)));return new se(g(g({},r),{value:this.resolve(r.value),configuration:n,done:Ie(n,this),tags:Jr(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]),a=s._transition(e[i[0]],r,n);return!a||!a.transitions.length?this.next(r,n):a},t.prototype.transitionParallelNode=function(e,r,n){var i,s,a={};try{for(var o=R(Object.keys(e)),u=o.next();!u.done;u=o.next()){var d=u.value,c=e[d];if(!!c){var h=this.getStateNode(d),f=h._transition(c,r,n);f&&(a[d]=f)}}}catch(E){i={error:E}}finally{try{u&&!u.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}var l=Object.keys(a).map(function(E){return a[E]}),p=U(l.map(function(E){return E.transitions})),v=l.some(function(E){return E.transitions.length>0});if(!v)return this.next(r,n);var m=U(l.map(function(E){return E.entrySet})),x=U(Object.keys(a).map(function(E){return a[E].configuration}));return{transitions:p,entrySet:m,exitSet:U(l.map(function(E){return E.exitSet})),configuration:x,source:r,actions:U(Object.keys(a).map(function(E){return a[E].actions}))}},t.prototype._transition=function(e,r,n){return P(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,F(r))},t.prototype.next=function(e,r){var n,i,s=this,a=r.name,o=[],u=[],d;try{for(var c=R(this.getCandidates(a)),h=c.next();!h.done;h=c.next()){var f=h.value,l=f.cond,p=f.in,v=e.context,m=p?P(p)&&Ge(p)?e.matches(Be(this.getStateNodeById(p).path,this.delimiter)):ut(Be(p,this.delimiter),yi(this.path.slice(0,-2))(e.value)):!0,x=!1;try{x=!l||Ht(this.machine,l,v,r,e)}catch(N){throw new Error("Unable to evaluate guard '".concat(l.name||l.type,"' in transition for event '").concat(a,"' in state node '").concat(this.id,`':
31
31
  `).concat(N.message))}if(x&&m){f.target!==void 0&&(u=f.target),o.push.apply(o,k([],C(f.actions),!1)),d=f;break}}}catch(N){n={error:N}}finally{try{h&&!h.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}if(!!d){if(!u.length)return{transitions:[d],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:o};var E=U(u.map(function(N){return s.getRelativeStateNodes(N,e.historyValue)})),T=!!d.internal,O=T?[]:U(E.map(function(N){return s.nodesFromChild(N)}));return{transitions:[d],entrySet:O,exitSet:T?[]:[this],configuration:E,source:e,actions:o}}},t.prototype.nodesFromChild=function(e){if(e.escapes(this))return[];for(var r=[],n=e;n&&n!==this;)r.push(n),n=n.parent;return r.push(this),r},t.prototype.escapes=function(e){if(this===e)return!1;for(var r=this.parent;r;){if(r===e)return!1;r=r.parent}return!0},t.prototype.getActions=function(e,r,n,i){var s,a,o,u,d=Ne([],i?this.getStateNodes(i.value):[this]),c=e.configuration.length?Ne(d,e.configuration):d;try{for(var h=R(c),f=h.next();!f.done;f=h.next()){var l=f.value;yt(d,l)||e.entrySet.push(l)}}catch(b){s={error:b}}finally{try{f&&!f.done&&(a=h.return)&&a.call(h)}finally{if(s)throw s.error}}try{for(var p=R(d),v=p.next();!v.done;v=p.next()){var l=v.value;(!yt(c,l)||yt(e.exitSet,l.parent))&&e.exitSet.push(l)}}catch(b){o={error:b}}finally{try{v&&!v.done&&(u=p.return)&&u.call(p)}finally{if(o)throw o.error}}var m=U(e.entrySet.map(function(b){var w=[];if(b.type!=="final")return w;var A=b.parent;if(!A.parent)return w;w.push(vt(b.id,b.doneData),vt(A.id,b.doneData?Te(b.doneData,r,n):void 0));var q=A.parent;return q.type==="parallel"&&Pe(q).every(function(V){return Ie(e.configuration,V)})&&w.push(vt(q.id)),w}));e.exitSet.sort(function(b,w){return w.order-b.order}),e.entrySet.sort(function(b,w){return b.order-w.order});var x=new Set(e.entrySet),E=new Set(e.exitSet),T=C([U(Array.from(x).map(function(b){return k(k([],C(b.activities.map(function(w){return Ni(w)})),!1),C(b.onEntry),!1)})).concat(m.map(Ci)),U(Array.from(E).map(function(b){return k(k([],C(b.onExit),!1),C(b.activities.map(function(w){return Ii(w)})),!1)}))],2),O=T[0],N=T[1],M=ht(N.concat(e.actions).concat(O),this.machine.options.actions);return M},t.prototype.transition=function(e,r,n){e===void 0&&(e=this.initialState);var i=F(r),s;if(e instanceof se)s=n===void 0?e:this.resolveState(se.from(e,n));else{var a=P(e)?this.resolve(ot(this.getResolvedPath(e))):this.resolve(e),o=n!=null?n:this.machine.context;s=this.resolveState(se.from(a,o))}if(!j&&i.name===St)throw new Error("An event cannot have the wildcard type ('".concat(St,"')"));if(this.strict&&!this.events.includes(i.name)&&!Si(i.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(i.name,"'"));var u=this._transition(s.value,s,i)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},d=Ne([],this.getStateNodes(s.value)),c=u.configuration.length?Ne(d,u.configuration):d;return u.configuration=k([],C(c),!1),this.resolveTransition(u,s,s.context,i)},t.prototype.resolveRaisedTransition=function(e,r,n){var i,s=e.actions;return e=this.transition(e,r),e._event=n,e.event=n.data,(i=e.actions).unshift.apply(i,k([],C(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i){var s,a,o=this;i===void 0&&(i=Ae);var u=e.configuration,d=!r||e.transitions.length>0,c=d?Fi(this.machine,u):void 0,h=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,f=this.getActions(e,n,i,r),l=r?g({},r.activities):{};try{for(var p=R(f),v=p.next();!v.done;v=p.next()){var m=v.value;m.type===it?l[m.activity.id||m.activity.type]=m:m.type===Me&&(l[m.activity.id||m.activity.type]=!1)}}catch(Z){s={error:Z}}finally{try{v&&!v.done&&(a=p.return)&&a.call(p)}finally{if(s)throw s.error}}var x=C($t(this,r,n,i,f,this.machine.config.preserveActionOrder),2),E=x[0],T=x[1],O=C(Ft(E,function(Z){return Z.type===Le||Z.type===xe&&Z.to===Ee.Internal}),2),N=O[0],M=O[1],b=E.filter(function(Z){var Ue;return Z.type===it&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===st}),w=b.reduce(function(Z,Ue){return Z[Ue.activity.id]=Ui(Ue.activity,o.machine,T,i),Z},r?g({},r.children):{}),A=d?e.configuration:r?r.configuration:[],q=Ie(A,this),V=new se({value:c||r.value,context:T,_event:i,_sessionid:r?r._sessionid:null,historyValue:c?h?Ti(h,c):void 0:r?r.historyValue:void 0,history:!c||e.source?r:void 0,actions:c?M:[],activities:c?l:r?r.activities:{},events:[],configuration:A,transitions:e.transitions,children:w,done:q,tags:Jr(A),machine:this}),Q=n!==T;V.changed=i.name===at||Q;var ge=V.history;ge&&delete ge.history;var It=!q&&(this._transient||u.some(function(Z){return Z._transient}));if(!d&&(!It||i.name===Je))return V;var ie=V;if(!q)for(It&&(ie=this.resolveRaisedTransition(ie,{type:di},i));N.length;){var tc=N.shift();ie=this.resolveRaisedTransition(ie,tc._event,i)}var rc=ie.changed||(ge?!!ie.actions.length||Q||typeof ge.value!=typeof ie.value||!$r(ie.value,ge.value):void 0);return ie.changed=rc,ie.history=ge,ie},t.prototype.getStateNode=function(e){if(Ge(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=Ge(e)?e.slice(Kr.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"&&Ge(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Bt(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||He;switch(this.type){case"parallel":return Fe(this.initialStateValue,function(s,a){return s?n.getStateNode(a).resolve(e[a]||s):He});case"compound":if(P(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?Fe(e,function(s,a){return s?n.getStateNode(a).resolve(s):He}):this.initialStateValue||{};default:return e||He}},t.prototype.getResolvedPath=function(e){if(Ge(e)){var r=this.machine.idMap[e.slice(Kr.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Bt(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=Br(this.states,function(n){return n.initialStateValue||He},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=mt(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet: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;P(r.target)?e=Ge(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(mt(this))return[this];if(this.type==="compound"&&!this.initial)return j||B(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=ct(this.initialStateValue);return U(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=C(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:Br(this.states,function(r,n){if(!e)return r.historyValue();var i=P(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?U(ct(i).map(function(a){return n.getFromRelativePath(a)})):n.initialStateNodes}var s=gi(n.path,"states")(e).current;return P(s)?[n.getStateNode(s)]:U(ct(s).map(function(a){return r.history==="deep"?n.getFromRelativePath(a):[n.states[a[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=U(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,a=new Set(this.ownEvents);if(s)try{for(var o=R(Object.keys(s)),u=o.next();!u.done;u=o.next()){var d=u.value,c=s[d];if(c.states)try{for(var h=(n=void 0,R(c.events)),f=h.next();!f.done;f=h.next()){var l=f.value;a.add("".concat(l))}}catch(p){n={error:p}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}}}catch(p){e={error:p}}finally{try{u&&!u.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(a)},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(!P(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 a=r.parent.getStateNodeByPath(s);return a}catch(o){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
32
- `).concat(o.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Ri(e.target),i="internal"in e?e.internal:n?n.some(function(u){return P(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,a=this.resolveTarget(n),o=g(g({},e),{actions:ht(ee(e.actions)),cond:Vt(e.cond,s),target:a,source:this,internal:i,eventType:e.event,toJSON:function(){return g(g({},o),{target:o.target?o.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return o},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,a=St,o=s[a],u=o===void 0?[]:o,d=je(s,[typeof a=="symbol"?a:a+""]);i=U(Object.keys(d).map(function(E){!j&&E===Je&&B(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var T=be(E,d[E]);return j||Tc(n,E,T),T}).concat(be(St,u)))}var c=this.config.always?be("",this.config.always):[],h=this.config.onDone?be(String(vt(this.id)),this.config.onDone):[];j||B(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var f=U(this.invoke.map(function(E){var T=[];return E.onDone&&T.push.apply(T,k([],C(be(String(Re(E.id)),E.onDone)),!1)),E.onError&&T.push.apply(T,k([],C(be(String(Oe(E.id)),E.onError)),!1)),T})),l=this.after,p=U(k(k(k(k([],C(h),!1),C(f),!1),C(i),!1),C(c),!1).map(function(E){return ee(E).map(function(T){return n.formatTransition(T)})}));try{for(var v=R(l),m=v.next();!m.done;m=v.next()){var x=m.value;p.push(x)}}catch(E){e={error:E}}finally{try{m&&!m.done&&(r=v.return)&&r.call(v)}finally{if(e)throw e.error}}return p},t}();function ae(t,e){return new Ki(t,e)}var D=_i,z=pt;var Kt="nhostRefreshToken",Xt="nhostRefreshTokenExpiresAt";var _e={status:10,error:"invalid-email",message:"Email is incorrectly formatted"};var wt={status:10,error:"invalid-password",message:"Password is incorrectly formatted"},Xi={status:10,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Yi={status:10,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Qi={status:10,error:"no-refresh-token",message:"No refresh token has been provided"},Zi={status:20,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."};var oa=nt(aa());var oe=t=>{let e=oa.default.create({baseURL:t});return e.interceptors.response.use(r=>r,r=>{var n,i,s,a,o,u,d,c,h,f;return Promise.reject({error:{message:(o=(a=(s=(i=(n=r.response)==null?void 0:n.data)==null?void 0:i.message)!=null?s:r.message)!=null?a:r.request.responseText)!=null?o:JSON.stringify(r),status:(h=(c=(u=r.response)==null?void 0:u.status)!=null?c:(d=r.response)==null?void 0:d.data.statusCode)!=null?h:0,error:((f=r.response)==null?void 0:f.data.error)||r.request.statusText||"network"}})}),e};function ir(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 gl={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 mn(t,e){function r(i,s,a){if(typeof document!="undefined"){a=ir({},e,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var u in a)!a[u]||(o+="; "+u,a[u]!==!0&&(o+="="+a[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+o}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],a={},o=0;o<s.length;o++){var u=s[o].split("="),d=u.slice(1).join("=");try{var c=decodeURIComponent(u[0]);if(a[c]=t.read(d,c),i===c)break}catch{}}return i?a[i]:a}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",ir({},s,{expires:-1}))},withAttributes:function(i){return mn(this.converter,ir({},this.attributes,i))},withConverter:function(i){return mn(ir({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var El=mn(gl,{path:"/"}),sr=El;var or=typeof window!="undefined",ar=new Map,Sl=t=>{var e;return or&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=ar.get(t))!=null?e:null},wl=(t,e)=>{or&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?ar.set(t,e):ar.has(t)&&ar.delete(t)};var ua=(t,e)=>{if(!e||t==="localStorage"||t==="web")return Sl;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==="cookie")return r=>{var n;return or&&(n=sr.get(r))!=null?n:null};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 getItem or getItemAsync property")}throw Error(`Unknown storage type: ${t}`)},ca=(t,e)=>{if(!e||t==="localStorage"||t==="web")return wl;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==="cookie")return(r,n)=>{or&&(n?sr.set(r,n):sr.remove(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}`)};var la=(t,e)=>{let r=e&&Object.entries(e).map(([n,i])=>{let s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{var r;return e!=null&&e.redirectTo?{...e,redirectTo:(r=e==null?void 0:e.redirectTo)!=null&&r.startsWith("/")?t+e.redirectTo:e==null?void 0:e.redirectTo}:e};function At(t,e){var i;if(!e){if(typeof window=="undefined")return;e=((i=window.location)==null?void 0:i.href)||""}t=t.replace(/[\[\]]/g,"\\$&");let r=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),n=r.exec(e);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}function yn(t){var r;if(typeof window=="undefined")return;let e=window==null?void 0:window.location;if(!!e&&e){let n=new URLSearchParams(e.search),i=new URLSearchParams((r=e.hash)==null?void 0:r.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)}}var Ke=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,}))$/),ur=t=>!!t&&typeof t=="string"&&t.length>=3,fa=t=>!!t&&typeof t=="string";var gn={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},errors:{}};var da=({backendUrl:t,clientUrl:e,interpreter:r})=>{let n=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:i=>_e}),saveRequestError:D({error:(i,{data:{error:s}})=>s}),reportError:z(i=>({type:"ERROR",error:i.error})),reportSuccess:z("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!Ke(s)},services:{requestChange:async(i,{email:s,options:a})=>(await n.post("/user/email/change",{newEmail:s,options:ne(e,a)},{headers:{authorization:`Bearer ${r==null?void 0:r.state.context.accessToken.value}`}})).data}})};var ha=({backendUrl:t,interpreter:e})=>{let r=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:n=>wt}),saveRequestError:D({error:(n,{data:{error:i}})=>(console.log(i),i)}),reportError:z(n=>({type:"ERROR",error:n.error})),reportSuccess:z("SUCCESS")},guards:{invalidPassword:(n,{password:i})=>!ur(i)},services:{requestChange:(n,{password:i})=>r.post("/user/password",{newPassword:i},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}})}})};var pa=({backendUrl:t,clientUrl:e})=>{let r=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:"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:{saveRequestError:D({error:(n,{data:{error:i}})=>(console.log(i),i)}),reportError:z(n=>({type:"ERROR",error:n.error})),reportSuccess:z("SUCCESS")},services:{requestChange:(n,{email:i,options:s})=>r.post("/user/password/reset",{email:i,options:ne(e,s)})}})};var va=({backendUrl:t,clientUrl:e,interpreter:r})=>{let n=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:i=>_e}),saveRequestError:D({error:(i,{data:{error:s}})=>s}),reportError:z(i=>({type:"ERROR",error:i.error})),reportSuccess:z("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!Ke(s)},services:{request:async(i,{email:s,options:a})=>(await n.post("/user/email/send-verification-email",{email:s,options:ne(e,a)})).data}})};var ma=({backendUrl:t,clientUrl:e,clientStorageGetter:r,clientStorageSetter:n,clientStorageType:i="web",clientStorage:s,refreshIntervalTime:a,autoRefreshToken:o=!0,autoSignIn:u=!0})=>{let d=r||ua(i,s),c=n||ca(i,s),h=oe(t),f=async(l,p,v)=>(await h.post(l,p,v)).data;return ae({schema:{context:{},events:{}},tsTypes:{},context:gn,preserveActionOrder:!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:{actions:["saveSession","reportTokenChanged"],target:"signedIn"},onError:{actions:["saveAuthenticationError"],target:"signedOut"}}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsEmailVerification:{},needsSmsOtp:{},needsMfa:{},failed:{exit:"resetAuthenticationError",initial:"server",states:{server:{},validation:{states:{password:{},email:{},phoneNumber:{}}}}},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed.server"}}}},on:{SIGNIN_PASSWORD:[{cond:"invalidEmail",actions:["saveInvalidEmail"],target:".failed.validation.email"},{cond:"invalidPassword",actions:["saveInvalidPassword"],target:".failed.validation.password"},"#nhost.authentication.authenticating.password"],SIGNIN_PASSWORDLESS_EMAIL:[{cond:"invalidEmail",actions:"saveInvalidEmail",target:".failed.validation.email"},"#nhost.authentication.authenticating.passwordlessEmail"],SIGNIN_PASSWORDLESS_SMS:[{cond:"invalidPhoneNumber",actions:"saveInvalidPhoneNumber",target:".failed.validation.phoneNumber"},"#nhost.authentication.authenticating.passwordlessSms"],SIGNIN_PASSWORDLESS_SMS_OTP:[{cond:"invalidPhoneNumber",actions:"saveInvalidPhoneNumber",target:".failed.validation.phoneNumber"},"#nhost.authentication.authenticating.passwordlessSmsOtp"],SIGNUP_EMAIL_PASSWORD:[{cond:"invalidEmail",actions:"saveInvalidSignUpEmail",target:".failed.validation.email"},{cond:"invalidPassword",actions:"saveInvalidSignUpPassword",target:".failed.validation.password"},"#nhost.authentication.registering"],SIGNIN_ANONYMOUS:"#nhost.authentication.authenticating.anonymous",SIGNIN_MFA_TOTP:[{cond:"noMfaTicket",actions:["saveNoMfaTicketError"],target:".failed"},"#nhost.authentication.authenticating.mfa.totp"]}},authenticating:{states:{passwordlessEmail:{invoke:{src:"signInPasswordlessEmail",id:"authenticatePasswordlessEmail",onDone:"#nhost.authentication.signedOut.needsEmailVerification",onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},passwordlessSms:{invoke:{src:"signInPasswordlessSms",id:"authenticatePasswordlessSms",onDone:"#nhost.authentication.signedOut.needsSmsOtp",onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},passwordlessSmsOtp:{invoke:{src:"signInPasswordlessSmsOtp",id:"authenticatePasswordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},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.needsEmailVerification"},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed.server"}}}}}}},registering:{entry:"resetSignUpError",invoke:{src:"registerUser",id:"registerUser",onDone:[{cond:"hasSession",target:"#nhost.authentication.signedIn",actions:["saveSession","reportTokenChanged"]},{target:"#nhost.authentication.signedOut.needsEmailVerification"}],onError:[{cond:"unverified",target:"#nhost.authentication.signedOut.needsEmailVerification"},{actions:"saveRegisrationError",target:"#nhost.authentication.signedOut.failed.server"}]}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken"],on:{SIGNOUT:"#nhost.authentication.signedOut.signingOut",DEANONYMIZE:{target:".deanonymizing"}},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{"1000":{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"}]}}}}}},deanonymizing:{initial:"error",states:{error:{},success:{}}}}}}},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"},{target:["#nhost.authentication.signedOut","idle.error"]}]}}}}}},{actions:{reportSignedIn:z("SIGNED_IN"),reportSignedOut:z("SIGNED_OUT"),reportTokenChanged:z("TOKEN_CHANGED"),clearContextExceptRefreshToken:D(({refreshToken:{value:l}})=>(c(Xt,null),{...gn,refreshToken:{value:l}})),saveSession:D({user:(l,{data:p})=>{var v;return(v=p==null?void 0:p.session)==null?void 0:v.user},accessToken:(l,{data:p})=>{var v,m;if(p.session.accessTokenExpiresIn){let x=new Date(Date.now()+p.session.accessTokenExpiresIn*1e3).toISOString();c(Xt,x)}else c(Xt,null);return{value:(v=p==null?void 0:p.session)==null?void 0:v.accessToken,expiresAt:new Date(Date.now()+((m=p==null?void 0:p.session)==null?void 0:m.accessTokenExpiresIn)*1e3)}},refreshToken:(l,{data:p})=>{var v;return c(Kt,p.session.refreshToken),{value:(v=p==null?void 0:p.session)==null?void 0:v.refreshToken}}}),saveMfaTicket:D({mfa:(l,p)=>{var v,m;return(m=(v=p.data)==null?void 0:v.mfa)!=null?m:null}}),resetTimer:D({refreshTimer:(l,p)=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:D({refreshTimer:(l,p)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:D({errors:({errors:l},{data:{error:p}})=>({...l,authentication:p})}),resetAuthenticationError:D({errors:({errors:{authentication:l,...p}})=>p}),saveInvalidEmail:D({errors:({errors:l})=>({...l,authentication:_e})}),saveInvalidPassword:D({errors:({errors:l})=>({...l,authentication:wt})}),saveInvalidPhoneNumber:D({errors:({errors:l})=>({...l,authentication:Xi})}),saveRegisrationError:D({errors:({errors:l},{data:{error:p}})=>({...l,registration:p})}),resetSignUpError:D({errors:({errors:{registration:l,...p}})=>p}),saveInvalidSignUpPassword:D({errors:({errors:l})=>({...l,registration:wt})}),saveInvalidSignUpEmail:D({errors:({errors:l})=>({...l,registration:_e})}),saveNoMfaTicketError:D({errors:({errors:l})=>({...l,registration:Yi})}),destroyRefreshToken:D({refreshToken:l=>(c(Kt,null),{value:null})}),cleanUrl:()=>{u&&At("refreshToken")&&(yn("refreshToken"),yn("type"))},broadcastToken:l=>{if(u)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,noMfaTicket:(l,{ticket:p})=>{var v;return!p&&!((v=l.mfa)!=null&&v.ticket)},hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{var x;let{expiresAt:p}=l.accessToken;return p?l.refreshTimer.lastAttempt?Date.now()-l.refreshTimer.lastAttempt.getTime()>5*1e3:a&&Date.now()-(((x=l.refreshTimer.startedAt)==null?void 0:x.getTime())||0)>a*1e3?!0:p.getTime()-Date.now()-1e3*300<=0:!1},unverified:(l,{data:{error:p}})=>p.status===401&&p.message==="Email is not verified",hasSession:(l,p)=>{var v;return!!((v=p.data)!=null&&v.session)},hasMfaTicket:(l,p)=>{var v;return!!((v=p.data)!=null&&v.mfa)},invalidEmail:(l,{email:p})=>!Ke(p),invalidPassword:(l,{password:p})=>!ur(p),invalidPhoneNumber:(l,{phoneNumber:p})=>!fa(p)},services:{signInPassword:(l,{email:p,password:v})=>f("/signin/email-password",{email:p,password:v}),signInPasswordlessSms:(l,{phoneNumber:p,options:v})=>f("/signin/passwordless/sms",{phoneNumber:p,options:ne(e,v)}),signInPasswordlessSmsOtp:(l,{phoneNumber:p,otp:v})=>f("/signin/passwordless/sms/otp",{phoneNumber:p,otp:v}),signInPasswordlessEmail:(l,{email:p,options:v})=>f("/signin/passwordless/email",{email:p,options:ne(e,v)}),signInAnonymous:l=>f("/signin/anonymous"),signInMfaTotp:(l,{ticket:p,otp:v})=>{var m;return f("/signin/mfa/totp",{ticket:p||((m=l.mfa)==null?void 0:m.ticket),otp:v})},refreshToken:async(l,p)=>{let v=p.type==="TRY_TOKEN"?p.token:l.refreshToken.value;return{session:await f("/token",{refreshToken:v})}},signout:(l,p)=>f("/signout",{refreshToken:l.refreshToken.value,all:!!p.all}),registerUser:(l,{email:p,password:v,options:m})=>f("/signup/email-password",{email:p,password:v,options:ne(e,m)}),importRefreshToken:async()=>{let l=null;if(u){let v=At("refreshToken")||null;if(v)try{return{session:await f("/token",{refreshToken:v})}}catch(m){l=m.error}else{let m=At("error");if(m)return Promise.reject({error:{status:10,error:m,message:At("errorDescription")||m}})}}let p=await d(Kt);if(p)try{return{session:await f("/token",{refreshToken:p})}}catch(v){l=v.error}return Promise.reject({error:l})}}})};var Xe=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:a,...o}){this._subscriptions=new Set;if(this.backendUrl=s,this.clientUrl=a,this.machine=ma({...o,backendUrl:s,clientUrl:a,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&(this.interpreter=me(this.machine),this.interpreter.start()),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",u=>{var c;let d=(c=this.interpreter)==null?void 0:c.state.context.refreshToken.value;this.interpreter&&u.data!==d&&this.interpreter.send({type:"TRY_TOKEN",token:u.data})})}catch{}}get interpreter(){return this._interpreter}set interpreter(e){this._interpreter=e,e&&this._subscriptions.forEach(r=>r(this))}onStart(e){this.interpreter?e(this):this._subscriptions.add(e)}};var ya=()=>typeof window!="undefined",we=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user};var ga={message:"User is already signed in",status:100},Rl={message:"User is not authenticated",status:101},Ol={message:"User is not anonymous",status:101},Cl={message:"Email needs verification",status:102},cr=class{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,autoLogin:i,clientStorage:s,clientStorageType:a,clientStorageGetter:o,clientStorageSetter:u,refreshIntervalTime:d,start:c=!0}){var h;this._client=new Xe({backendUrl:e,clientUrl:typeof window!="undefined"&&((h=window.location)==null?void 0:h.origin)||"",autoRefreshToken:r,autoSignIn:typeof i=="boolean"?i:n,start:c,clientStorage:s,clientStorageType:a,clientStorageGetter:o,clientStorageSetter:u,refreshIntervalTime:d})}async signUp(e){let r=await this.waitUntilReady(),{email:n,password:i,options:s}=e;return this.isAuthenticated()?{session:null,error:ga}:new Promise(a=>{r.send("SIGNUP_EMAIL_PASSWORD",{email:n,password:i,options:s}),r.onTransition(o=>{if(o.matches({authentication:{signedOut:"needsEmailVerification"}}))return a({session:null,error:null});if(o.matches({authentication:{signedOut:"failed"}}))return a({session:null,error:o.context.errors.registration||null});if(o.matches({authentication:"signedIn"}))return a({session:we(o.context),error:null})})})}async signIn(e){let r=await this.waitUntilReady();if(this.isAuthenticated())return{session:null,mfa:null,error:ga};if("provider"in e){let{provider:n,options:i}=e,s=la(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return ya()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}return"email"in e&&"password"in e?new Promise(n=>{r.send("SIGNIN_PASSWORD",e),r.onTransition(i=>{i.matches({authentication:"signedIn"})?n({session:we(i.context),mfa:null,error:null}):i.matches({authentication:{signedOut:"needsEmailVerification"}})?n({session:null,mfa:null,error:Cl}):i.matches({authentication:{signedOut:"needsMfa"}})?n({session:null,mfa:i.context.mfa,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"email"in e&&!("otp"in e)?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_EMAIL",e),r.onTransition(i=>{i.matches({authentication:{signedOut:"needsEmailVerification"}})?n({session:null,mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"phoneNumber"in e&&!("otp"in e)?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_SMS",e),r.onTransition(i=>{i.matches({authentication:{signedOut:"needsSmsOtp"}})?n({session:null,mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"otp"in e?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_SMS_OTP",e),r.onTransition(i=>{i.matches({authentication:"signedIn"})?n({session:we(i.context),mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):{session:null,mfa:null,error:{message:"Incorrect parameters",status:500}}}async signOut(e){let r=await this.waitUntilReady();return this.isAuthenticated()?new Promise(n=>{r.send("SIGNOUT",{all:e==null?void 0:e.all}),r.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?n({error:null}):i.matches({authentication:{signedOut:{failed:"server"}}})&&n({error:i.context.errors.signout||null})})}):{error:Rl}}async resetPassword({email:e,options:r}){return new Promise(n=>{let i=me(pa(this._client));i.onTransition(({event:s})=>{if(s.type==="ERROR")return n({error:s.error});if(s.type==="SUCCESS")return n({error:null})}),i.start(),i.send("REQUEST",{email:e,options:r})})}async changePassword(e){return new Promise(r=>{let n=me(ha(this._client));n.onTransition(({event:i})=>{if(i.type==="ERROR")return r({error:i.error});if(i.type==="SUCCESS")return r({error:null})}),n.start(),n.send("REQUEST",{password:e.newPassword})})}async sendVerificationEmail(e){return new Promise(r=>{let n=me(va(this._client));n.onTransition(({event:i})=>{if(i.type==="ERROR")return r({error:i.error});if(i.type==="SUCCESS")return r({error:null})}),n.start(),n.send("REQUEST",{email:e.email,options:e.options})})}async changeEmail({newEmail:e,options:r}){return new Promise(n=>{let i=me(da(this._client));i.onTransition(({event:s})=>{if(s.type==="ERROR")return n({error:s.error});if(s.type==="SUCCESS")return n({error:null})}),i.start(),i.send("REQUEST",{email:e,options:r})})}async deanonymize(e){let r=await this.waitUntilReady();return new Promise(n=>{var o;if(!this.isAuthenticated()||!((o=r.state.context.user)!=null&&o.isAnonymous))return{error:Ol};let{signInMethod:i,connection:s,...a}=e;r.send("DEANONYMIZE",{signInMethod:i,connection:s,options:a}),r.onTransition(u=>{u.matches({authentication:{signedIn:{deanonymizing:"success"}}})?n({error:null}):u.matches({authentication:{signedIn:{deanonymizing:"error"}}})&&n({error:u.context.errors.authentication||null})}),r.start()})}onTokenChanged(e){let r=n=>n.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(we(s))});if(this._client.interpreter){let n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}onAuthStateChanged(e){let r=n=>n.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,we(s))});if(this._client.interpreter){let n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onAuthStateChanged was added before the interpreter started. Cannot unsubscribe listener.")}}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.state.matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).state.matches({authentication:"signedIn"})}getAuthenticationStatus(){return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1}:{isAuthenticated:!1,isLoading:!0}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.state.context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){let e=this.getAccessToken();return e?fi(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{let r=await this.waitUntilReady();return r.state.matches({token:"idle"})?new Promise(n=>{let i=e||r.state.context.refreshToken.value;if(!i)return n({session:null,error:Qi});r.send("TRY_TOKEN",{token:i}),r==null||r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:{status:400,message:"Invalid refresh token"}}):s.event.type==="TOKEN_CHANGED"&&n({session:we(s.context),error:null})})}):{session:null,error:Zi}}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return we((r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){let r=this._client.interpreter;if(!r)throw Error("Auth interpreter not set");return r.state.hasTag("loading")?new Promise((n,i)=>{let s=setTimeout(()=>i(`The state machine is not yet ready after ${15} seconds.`),15e3);r.onTransition(a=>{if(!a.hasTag("loading"))return clearTimeout(s),n(r)})}):Promise.resolve(r)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.state)!=null&&r.hasTag("loading"))}get client(){return this._client}};var Co=nt(Oo()),Er=class{constructor({url:e}){this.url=e,this.httpClient=Co.default.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{fileMetadata:null,error:r}}}async getPresignedUrl(e){try{let{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{let{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){let{bucketId:r,name:n,id:i}=e,s={};return r&&(s["x-nhost-bucket-id"]=r),i&&(s["x-nhost-file-id"]=i),n&&(s["x-nhost-file-name"]=n),s}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}};var Sr=class{constructor({url:e}){this.url=e,this.api=new Er({url:e})}async upload(e){let r=new FormData;r.append("file",e.file);let{fileMetadata:n,error:i}=await this.api.upload({...e,file:r});return i?{fileMetadata:null,error:i}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){let{fileId:r}=e;return`${this.url}/files/${r}`}async getPresignedUrl(e){let{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){let{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}};var Du=nt(ni()),Cr=class{constructor(e){let{url:r}=e;this.accessToken=null,this.instance=Du.default.create({baseURL:r})}async call(e,r,n){let i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s;try{s=await this.instance.post(e,r,{...n,headers:i})}catch(a){if(a instanceof Error)return{res:null,error:a}}return s?{res:s,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var Zu=nt(ni()),ec=nt(Qu()),Dr=class{constructor(e){let{url:r}=e;this.url=r,this.accessToken=null,this.instance=Zu.default.create({baseURL:r})}async request(e,r,n){let i={...n==null?void 0:n.headers,...this.generateAccessTokenHeaders()};try{let s="",o=(await this.instance.post("",{operationName:s||void 0,query:typeof e=="string"?e:(0,ec.print)(e),variables:r},{...n,headers:i})).data,{data:u}=o;return o.errors?{data:null,error:o.errors}:typeof u!="object"||Array.isArray(u)||u===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:u,error:null}}catch(s){return s instanceof Error?{data:null,error:s}:(console.error(s),{data:null,error:new Error("Unable to get do GraphQL request")})}}getUrl(){return this.url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var qr=class{constructor({backendUrl:e,refreshIntervalTime:r,clientStorageGetter:n,clientStorageSetter:i,clientStorage:s,clientStorageType:a,autoRefreshToken:o,autoSignIn:u,start:d=!0}){if(!e)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");this.auth=new cr({url:`${e}/v1/auth`,refreshIntervalTime:r,clientStorageGetter:n,clientStorageSetter:i,clientStorage:s,clientStorageType:a,autoRefreshToken:o,autoSignIn:u,start:d}),this.storage=new Sr({url:`${e}/v1/storage`}),this.functions=new Cr({url:`${e}/v1/functions`}),this.graphql=new Dr({url:`${e}/v1/graphql`}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),this.auth.client.onStart(()=>{this.auth.onAuthStateChanged((c,h)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{this.storage.setAccessToken(c==null?void 0:c.accessToken),this.functions.setAccessToken(c==null?void 0:c.accessToken),this.graphql.setAccessToken(c==null?void 0:c.accessToken)})})}};var yg=t=>new qr(t);export{qr as NhostClient,Cr as NhostFunctionsClient,Dr as NhostGraphqlClient,yg as createClient};
32
+ `).concat(o.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Ri(e.target),i="internal"in e?e.internal:n?n.some(function(u){return P(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,a=this.resolveTarget(n),o=g(g({},e),{actions:ht(ee(e.actions)),cond:Vt(e.cond,s),target:a,source:this,internal:i,eventType:e.event,toJSON:function(){return g(g({},o),{target:o.target?o.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return o},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,a=St,o=s[a],u=o===void 0?[]:o,d=je(s,[typeof a=="symbol"?a:a+""]);i=U(Object.keys(d).map(function(E){!j&&E===Je&&B(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var T=be(E,d[E]);return j||Tc(n,E,T),T}).concat(be(St,u)))}var c=this.config.always?be("",this.config.always):[],h=this.config.onDone?be(String(vt(this.id)),this.config.onDone):[];j||B(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var f=U(this.invoke.map(function(E){var T=[];return E.onDone&&T.push.apply(T,k([],C(be(String(Re(E.id)),E.onDone)),!1)),E.onError&&T.push.apply(T,k([],C(be(String(Oe(E.id)),E.onError)),!1)),T})),l=this.after,p=U(k(k(k(k([],C(h),!1),C(f),!1),C(i),!1),C(c),!1).map(function(E){return ee(E).map(function(T){return n.formatTransition(T)})}));try{for(var v=R(l),m=v.next();!m.done;m=v.next()){var x=m.value;p.push(x)}}catch(E){e={error:E}}finally{try{m&&!m.done&&(r=v.return)&&r.call(v)}finally{if(e)throw e.error}}return p},t}();function ae(t,e){return new Ki(t,e)}var D=_i,z=pt;var Kt="nhostRefreshToken",Xt="nhostRefreshTokenExpiresAt";var _e={status:10,error:"invalid-email",message:"Email is incorrectly formatted"};var wt={status:10,error:"invalid-password",message:"Password is incorrectly formatted"},Xi={status:10,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Yi={status:10,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Qi={status:10,error:"no-refresh-token",message:"No refresh token has been provided"},Zi={status:20,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."};var oa=nt(aa());var oe=t=>{let e=oa.default.create({baseURL:t});return e.interceptors.response.use(r=>r,r=>{var n,i,s,a,o,u,d,c,h,f;return Promise.reject({error:{message:(o=(a=(s=(i=(n=r.response)==null?void 0:n.data)==null?void 0:i.message)!=null?s:r.message)!=null?a:r.request.responseText)!=null?o:JSON.stringify(r),status:(h=(c=(u=r.response)==null?void 0:u.status)!=null?c:(d=r.response)==null?void 0:d.data.statusCode)!=null?h:0,error:((f=r.response)==null?void 0:f.data.error)||r.request.statusText||"network"}})}),e};function ir(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 gl={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 mn(t,e){function r(i,s,a){if(typeof document!="undefined"){a=ir({},e,a),typeof a.expires=="number"&&(a.expires=new Date(Date.now()+a.expires*864e5)),a.expires&&(a.expires=a.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var u in a)!a[u]||(o+="; "+u,a[u]!==!0&&(o+="="+a[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+o}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],a={},o=0;o<s.length;o++){var u=s[o].split("="),d=u.slice(1).join("=");try{var c=decodeURIComponent(u[0]);if(a[c]=t.read(d,c),i===c)break}catch{}}return i?a[i]:a}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",ir({},s,{expires:-1}))},withAttributes:function(i){return mn(this.converter,ir({},this.attributes,i))},withConverter:function(i){return mn(ir({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var El=mn(gl,{path:"/"}),sr=El;var or=typeof window!="undefined",ar=new Map,Sl=t=>{var e;return or&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=ar.get(t))!=null?e:null},wl=(t,e)=>{or&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?ar.set(t,e):ar.has(t)&&ar.delete(t)},ua=(t,e)=>{if(t==="localStorage"||t==="web")return Sl;if(t==="cookie")return r=>{var n;return or&&(n=sr.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage 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 getItem or getItemAsync property")}throw Error(`Unknown storage type: ${t}`)},ca=(t,e)=>{if(t==="localStorage"||t==="web")return wl;if(t==="cookie")return(r,n)=>{or&&(n?sr.set(r,n):sr.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}`)};var la=(t,e)=>{let r=e&&Object.entries(e).map(([n,i])=>{let s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{var r;return e!=null&&e.redirectTo?{...e,redirectTo:(r=e==null?void 0:e.redirectTo)!=null&&r.startsWith("/")?t+e.redirectTo:e==null?void 0:e.redirectTo}:e};function At(t,e){var i;if(!e){if(typeof window=="undefined")return;e=((i=window.location)==null?void 0:i.href)||""}t=t.replace(/[\[\]]/g,"\\$&");let r=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),n=r.exec(e);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}function yn(t){var r;if(typeof window=="undefined")return;let e=window==null?void 0:window.location;if(!!e&&e){let n=new URLSearchParams(e.search),i=new URLSearchParams((r=e.hash)==null?void 0:r.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)}}var Ke=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,}))$/),ur=t=>!!t&&typeof t=="string"&&t.length>=3,fa=t=>!!t&&typeof t=="string";var gn={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},errors:{}};var da=({backendUrl:t,clientUrl:e,interpreter:r})=>{let n=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:i=>_e}),saveRequestError:D({error:(i,{data:{error:s}})=>s}),reportError:z(i=>({type:"ERROR",error:i.error})),reportSuccess:z("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!Ke(s)},services:{requestChange:async(i,{email:s,options:a})=>(await n.post("/user/email/change",{newEmail:s,options:ne(e,a)},{headers:{authorization:`Bearer ${r==null?void 0:r.state.context.accessToken.value}`}})).data}})};var ha=({backendUrl:t,interpreter:e})=>{let r=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:n=>wt}),saveRequestError:D({error:(n,{data:{error:i}})=>(console.log(i),i)}),reportError:z(n=>({type:"ERROR",error:n.error})),reportSuccess:z("SUCCESS")},guards:{invalidPassword:(n,{password:i})=>!ur(i)},services:{requestChange:(n,{password:i})=>r.post("/user/password",{newPassword:i},{headers:{authorization:`Bearer ${e==null?void 0:e.state.context.accessToken.value}`}})}})};var pa=({backendUrl:t,clientUrl:e})=>{let r=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:"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:{saveRequestError:D({error:(n,{data:{error:i}})=>(console.log(i),i)}),reportError:z(n=>({type:"ERROR",error:n.error})),reportSuccess:z("SUCCESS")},services:{requestChange:(n,{email:i,options:s})=>r.post("/user/password/reset",{email:i,options:ne(e,s)})}})};var va=({backendUrl:t,clientUrl:e,interpreter:r})=>{let n=oe(t);return ae({schema:{context:{},events:{}},tsTypes:{},preserveActionOrder:!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:D({error:i=>_e}),saveRequestError:D({error:(i,{data:{error:s}})=>s}),reportError:z(i=>({type:"ERROR",error:i.error})),reportSuccess:z("SUCCESS")},guards:{invalidEmail:(i,{email:s})=>!Ke(s)},services:{request:async(i,{email:s,options:a})=>(await n.post("/user/email/send-verification-email",{email:s,options:ne(e,a)})).data}})};var ma=({backendUrl:t,clientUrl:e,clientStorageGetter:r,clientStorageSetter:n,clientStorageType:i="web",clientStorage:s,refreshIntervalTime:a,autoRefreshToken:o=!0,autoSignIn:u=!0})=>{let d=r||ua(i,s),c=n||ca(i,s),h=oe(t),f=async(l,p,v)=>(await h.post(l,p,v)).data;return ae({schema:{context:{},events:{}},tsTypes:{},context:gn,preserveActionOrder:!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:{actions:["saveSession","reportTokenChanged"],target:"signedIn"},onError:{actions:["saveAuthenticationError"],target:"signedOut"}}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsEmailVerification:{},needsSmsOtp:{},needsMfa:{},failed:{exit:"resetAuthenticationError",initial:"server",states:{server:{},validation:{states:{password:{},email:{},phoneNumber:{}}}}},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed.server"}}}},on:{SIGNIN_PASSWORD:[{cond:"invalidEmail",actions:["saveInvalidEmail"],target:".failed.validation.email"},{cond:"invalidPassword",actions:["saveInvalidPassword"],target:".failed.validation.password"},"#nhost.authentication.authenticating.password"],SIGNIN_PASSWORDLESS_EMAIL:[{cond:"invalidEmail",actions:"saveInvalidEmail",target:".failed.validation.email"},"#nhost.authentication.authenticating.passwordlessEmail"],SIGNIN_PASSWORDLESS_SMS:[{cond:"invalidPhoneNumber",actions:"saveInvalidPhoneNumber",target:".failed.validation.phoneNumber"},"#nhost.authentication.authenticating.passwordlessSms"],SIGNIN_PASSWORDLESS_SMS_OTP:[{cond:"invalidPhoneNumber",actions:"saveInvalidPhoneNumber",target:".failed.validation.phoneNumber"},"#nhost.authentication.authenticating.passwordlessSmsOtp"],SIGNUP_EMAIL_PASSWORD:[{cond:"invalidEmail",actions:"saveInvalidSignUpEmail",target:".failed.validation.email"},{cond:"invalidPassword",actions:"saveInvalidSignUpPassword",target:".failed.validation.password"},"#nhost.authentication.registering"],SIGNIN_ANONYMOUS:"#nhost.authentication.authenticating.anonymous",SIGNIN_MFA_TOTP:[{cond:"noMfaTicket",actions:["saveNoMfaTicketError"],target:".failed"},"#nhost.authentication.authenticating.mfa.totp"]}},authenticating:{states:{passwordlessEmail:{invoke:{src:"signInPasswordlessEmail",id:"authenticatePasswordlessEmail",onDone:"#nhost.authentication.signedOut.needsEmailVerification",onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},passwordlessSms:{invoke:{src:"signInPasswordlessSms",id:"authenticatePasswordlessSms",onDone:"#nhost.authentication.signedOut.needsSmsOtp",onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},passwordlessSmsOtp:{invoke:{src:"signInPasswordlessSmsOtp",id:"authenticatePasswordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},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.needsEmailVerification"},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed.server"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed.server"}}}}}}},registering:{entry:"resetSignUpError",invoke:{src:"registerUser",id:"registerUser",onDone:[{cond:"hasSession",target:"#nhost.authentication.signedIn",actions:["saveSession","reportTokenChanged"]},{target:"#nhost.authentication.signedOut.needsEmailVerification"}],onError:[{cond:"unverified",target:"#nhost.authentication.signedOut.needsEmailVerification"},{actions:"saveRegisrationError",target:"#nhost.authentication.signedOut.failed.server"}]}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken"],on:{SIGNOUT:"#nhost.authentication.signedOut.signingOut",DEANONYMIZE:{target:".deanonymizing"}},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{"1000":{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"}]}}}}}},deanonymizing:{initial:"error",states:{error:{},success:{}}}}}}},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"},{target:["#nhost.authentication.signedOut","idle.error"]}]}}}}}},{actions:{reportSignedIn:z("SIGNED_IN"),reportSignedOut:z("SIGNED_OUT"),reportTokenChanged:z("TOKEN_CHANGED"),clearContextExceptRefreshToken:D(({refreshToken:{value:l}})=>(c(Xt,null),{...gn,refreshToken:{value:l}})),saveSession:D({user:(l,{data:p})=>{var v;return(v=p==null?void 0:p.session)==null?void 0:v.user},accessToken:(l,{data:p})=>{var v,m;if(p.session.accessTokenExpiresIn){let x=new Date(Date.now()+p.session.accessTokenExpiresIn*1e3).toISOString();c(Xt,x)}else c(Xt,null);return{value:(v=p==null?void 0:p.session)==null?void 0:v.accessToken,expiresAt:new Date(Date.now()+((m=p==null?void 0:p.session)==null?void 0:m.accessTokenExpiresIn)*1e3)}},refreshToken:(l,{data:p})=>{var v;return c(Kt,p.session.refreshToken),{value:(v=p==null?void 0:p.session)==null?void 0:v.refreshToken}}}),saveMfaTicket:D({mfa:(l,p)=>{var v,m;return(m=(v=p.data)==null?void 0:v.mfa)!=null?m:null}}),resetTimer:D({refreshTimer:(l,p)=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:D({refreshTimer:(l,p)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:D({errors:({errors:l},{data:{error:p}})=>({...l,authentication:p})}),resetAuthenticationError:D({errors:({errors:{authentication:l,...p}})=>p}),saveInvalidEmail:D({errors:({errors:l})=>({...l,authentication:_e})}),saveInvalidPassword:D({errors:({errors:l})=>({...l,authentication:wt})}),saveInvalidPhoneNumber:D({errors:({errors:l})=>({...l,authentication:Xi})}),saveRegisrationError:D({errors:({errors:l},{data:{error:p}})=>({...l,registration:p})}),resetSignUpError:D({errors:({errors:{registration:l,...p}})=>p}),saveInvalidSignUpPassword:D({errors:({errors:l})=>({...l,registration:wt})}),saveInvalidSignUpEmail:D({errors:({errors:l})=>({...l,registration:_e})}),saveNoMfaTicketError:D({errors:({errors:l})=>({...l,registration:Yi})}),destroyRefreshToken:D({refreshToken:l=>(c(Kt,null),{value:null})}),cleanUrl:()=>{u&&At("refreshToken")&&(yn("refreshToken"),yn("type"))},broadcastToken:l=>{if(u)try{new BroadcastChannel("nhost").postMessage(l.refreshToken.value)}catch{}}},guards:{isSignedIn:l=>!!l.user&&!!l.refreshToken.value&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,noMfaTicket:(l,{ticket:p})=>{var v;return!p&&!((v=l.mfa)!=null&&v.ticket)},hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{var x;let{expiresAt:p}=l.accessToken;return p?l.refreshTimer.lastAttempt?Date.now()-l.refreshTimer.lastAttempt.getTime()>5*1e3:a&&Date.now()-(((x=l.refreshTimer.startedAt)==null?void 0:x.getTime())||0)>a*1e3?!0:p.getTime()-Date.now()-1e3*300<=0:!1},unverified:(l,{data:{error:p}})=>p.status===401&&p.message==="Email is not verified",hasSession:(l,p)=>{var v;return!!((v=p.data)!=null&&v.session)},hasMfaTicket:(l,p)=>{var v;return!!((v=p.data)!=null&&v.mfa)},invalidEmail:(l,{email:p})=>!Ke(p),invalidPassword:(l,{password:p})=>!ur(p),invalidPhoneNumber:(l,{phoneNumber:p})=>!fa(p)},services:{signInPassword:(l,{email:p,password:v})=>f("/signin/email-password",{email:p,password:v}),signInPasswordlessSms:(l,{phoneNumber:p,options:v})=>f("/signin/passwordless/sms",{phoneNumber:p,options:ne(e,v)}),signInPasswordlessSmsOtp:(l,{phoneNumber:p,otp:v})=>f("/signin/passwordless/sms/otp",{phoneNumber:p,otp:v}),signInPasswordlessEmail:(l,{email:p,options:v})=>f("/signin/passwordless/email",{email:p,options:ne(e,v)}),signInAnonymous:l=>f("/signin/anonymous"),signInMfaTotp:(l,{ticket:p,otp:v})=>{var m;return f("/signin/mfa/totp",{ticket:p||((m=l.mfa)==null?void 0:m.ticket),otp:v})},refreshToken:async(l,p)=>{let v=p.type==="TRY_TOKEN"?p.token:l.refreshToken.value;return{session:await f("/token",{refreshToken:v})}},signout:(l,p)=>f("/signout",{refreshToken:l.refreshToken.value,all:!!p.all}),registerUser:(l,{email:p,password:v,options:m})=>f("/signup/email-password",{email:p,password:v,options:ne(e,m)}),importRefreshToken:async()=>{let l=null;if(u){let v=At("refreshToken")||null;if(v)try{return{session:await f("/token",{refreshToken:v})}}catch(m){l=m.error}else{let m=At("error");if(m)return Promise.reject({error:{status:10,error:m,message:At("errorDescription")||m}})}}let p=await d(Kt);if(p)try{return{session:await f("/token",{refreshToken:p})}}catch(v){l=v.error}return Promise.reject({error:l})}}})};var Xe=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:a,...o}){this._subscriptions=new Set;if(this.backendUrl=s,this.clientUrl=a,this.machine=ma({...o,backendUrl:s,clientUrl:a,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&(this.interpreter=me(this.machine),this.interpreter.start()),typeof window!="undefined"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",u=>{var c;let d=(c=this.interpreter)==null?void 0:c.state.context.refreshToken.value;this.interpreter&&u.data!==d&&this.interpreter.send({type:"TRY_TOKEN",token:u.data})})}catch{}}get interpreter(){return this._interpreter}set interpreter(e){this._interpreter=e,e&&this._subscriptions.forEach(r=>r(this))}onStart(e){this.interpreter?e(this):this._subscriptions.add(e)}};var ya=()=>typeof window!="undefined",we=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user};var ga={message:"User is already signed in",status:100},Rl={message:"User is not authenticated",status:101},Ol={message:"User is not anonymous",status:101},Cl={message:"Email needs verification",status:102},cr=class{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,autoLogin:i,clientStorage:s,clientStorageType:a,clientStorageGetter:o,clientStorageSetter:u,refreshIntervalTime:d,start:c=!0}){var h;this._client=new Xe({backendUrl:e,clientUrl:typeof window!="undefined"&&((h=window.location)==null?void 0:h.origin)||"",autoRefreshToken:r,autoSignIn:typeof i=="boolean"?i:n,start:c,clientStorage:s,clientStorageType:a,clientStorageGetter:o,clientStorageSetter:u,refreshIntervalTime:d})}async signUp(e){let r=await this.waitUntilReady(),{email:n,password:i,options:s}=e;return this.isAuthenticated()?{session:null,error:ga}:new Promise(a=>{r.send("SIGNUP_EMAIL_PASSWORD",{email:n,password:i,options:s}),r.onTransition(o=>{if(o.matches({authentication:{signedOut:"needsEmailVerification"}}))return a({session:null,error:null});if(o.matches({authentication:{signedOut:"failed"}}))return a({session:null,error:o.context.errors.registration||null});if(o.matches({authentication:"signedIn"}))return a({session:we(o.context),error:null})})})}async signIn(e){let r=await this.waitUntilReady();if(this.isAuthenticated())return{session:null,mfa:null,error:ga};if("provider"in e){let{provider:n,options:i}=e,s=la(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return ya()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}return"email"in e&&"password"in e?new Promise(n=>{r.send("SIGNIN_PASSWORD",e),r.onTransition(i=>{i.matches({authentication:"signedIn"})?n({session:we(i.context),mfa:null,error:null}):i.matches({authentication:{signedOut:"needsEmailVerification"}})?n({session:null,mfa:null,error:Cl}):i.matches({authentication:{signedOut:"needsMfa"}})?n({session:null,mfa:i.context.mfa,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"email"in e&&!("otp"in e)?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_EMAIL",e),r.onTransition(i=>{i.matches({authentication:{signedOut:"needsEmailVerification"}})?n({session:null,mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"phoneNumber"in e&&!("otp"in e)?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_SMS",e),r.onTransition(i=>{i.matches({authentication:{signedOut:"needsSmsOtp"}})?n({session:null,mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):"otp"in e?new Promise(n=>{r.send("SIGNIN_PASSWORDLESS_SMS_OTP",e),r.onTransition(i=>{i.matches({authentication:"signedIn"})?n({session:we(i.context),mfa:null,error:null}):i.matches({authentication:{signedOut:"failed"}})&&n({session:null,mfa:null,error:i.context.errors.authentication||null})})}):{session:null,mfa:null,error:{message:"Incorrect parameters",status:500}}}async signOut(e){let r=await this.waitUntilReady();return this.isAuthenticated()?new Promise(n=>{r.send("SIGNOUT",{all:e==null?void 0:e.all}),r.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?n({error:null}):i.matches({authentication:{signedOut:{failed:"server"}}})&&n({error:i.context.errors.signout||null})})}):{error:Rl}}async resetPassword({email:e,options:r}){return new Promise(n=>{let i=me(pa(this._client));i.onTransition(({event:s})=>{if(s.type==="ERROR")return n({error:s.error});if(s.type==="SUCCESS")return n({error:null})}),i.start(),i.send("REQUEST",{email:e,options:r})})}async changePassword(e){return new Promise(r=>{let n=me(ha(this._client));n.onTransition(({event:i})=>{if(i.type==="ERROR")return r({error:i.error});if(i.type==="SUCCESS")return r({error:null})}),n.start(),n.send("REQUEST",{password:e.newPassword})})}async sendVerificationEmail(e){return new Promise(r=>{let n=me(va(this._client));n.onTransition(({event:i})=>{if(i.type==="ERROR")return r({error:i.error});if(i.type==="SUCCESS")return r({error:null})}),n.start(),n.send("REQUEST",{email:e.email,options:e.options})})}async changeEmail({newEmail:e,options:r}){return new Promise(n=>{let i=me(da(this._client));i.onTransition(({event:s})=>{if(s.type==="ERROR")return n({error:s.error});if(s.type==="SUCCESS")return n({error:null})}),i.start(),i.send("REQUEST",{email:e,options:r})})}async deanonymize(e){let r=await this.waitUntilReady();return new Promise(n=>{var o;if(!this.isAuthenticated()||!((o=r.state.context.user)!=null&&o.isAnonymous))return{error:Ol};let{signInMethod:i,connection:s,...a}=e;r.send("DEANONYMIZE",{signInMethod:i,connection:s,options:a}),r.onTransition(u=>{u.matches({authentication:{signedIn:{deanonymizing:"success"}}})?n({error:null}):u.matches({authentication:{signedIn:{deanonymizing:"error"}}})&&n({error:u.context.errors.authentication||null})}),r.start()})}onTokenChanged(e){let r=n=>n.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(we(s))});if(this._client.interpreter){let n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}onAuthStateChanged(e){let r=n=>n.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,we(s))});if(this._client.interpreter){let n=r(this._client.interpreter);return()=>n.stop()}else return this._client.onStart(n=>{r(n.interpreter)}),()=>{console.log("onAuthStateChanged was added before the interpreter started. Cannot unsubscribe listener.")}}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.state.matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).state.matches({authentication:"signedIn"})}getAuthenticationStatus(){return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1}:{isAuthenticated:!1,isLoading:!0}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.state.context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){let e=this.getAccessToken();return e?fi(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{let r=await this.waitUntilReady();return r.state.matches({token:"idle"})?new Promise(n=>{let i=e||r.state.context.refreshToken.value;if(!i)return n({session:null,error:Qi});r.send("TRY_TOKEN",{token:i}),r==null||r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:{status:400,message:"Invalid refresh token"}}):s.event.type==="TOKEN_CHANGED"&&n({session:we(s.context),error:null})})}):{session:null,error:Zi}}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return we((r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.state)==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){let r=this._client.interpreter;if(!r)throw Error("Auth interpreter not set");return r.state.hasTag("loading")?new Promise((n,i)=>{let s=setTimeout(()=>i(`The state machine is not yet ready after ${15} seconds.`),15e3);r.onTransition(a=>{if(!a.hasTag("loading"))return clearTimeout(s),n(r)})}):Promise.resolve(r)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.state)!=null&&r.hasTag("loading"))}get client(){return this._client}};var Co=nt(Oo()),Er=class{constructor({url:e}){this.url=e,this.httpClient=Co.default.create({baseURL:this.url})}async upload(e){try{return{fileMetadata:(await this.httpClient.post("/files",e.file,{headers:{...this.generateUploadHeaders(e),...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{fileMetadata:null,error:r}}}async getPresignedUrl(e){try{let{fileId:r}=e;return{presignedUrl:(await this.httpClient.get(`/files/${r}/presignedurl`,{headers:{...this.generateAuthHeaders()}})).data,error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{let{fileId:r}=e;return await this.httpClient.delete(`/files/${r}`,{headers:{...this.generateAuthHeaders()}}),{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateUploadHeaders(e){let{bucketId:r,name:n,id:i}=e,s={};return r&&(s["x-nhost-bucket-id"]=r),i&&(s["x-nhost-file-id"]=i),n&&(s["x-nhost-file-name"]=n),s}generateAuthHeaders(){return!this.adminSecret&&!this.accessToken?null:this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}};var Sr=class{constructor({url:e}){this.url=e,this.api=new Er({url:e})}async upload(e){let r=new FormData;r.append("file",e.file);let{fileMetadata:n,error:i}=await this.api.upload({...e,file:r});return i?{fileMetadata:null,error:i}:n?{fileMetadata:n,error:null}:{fileMetadata:null,error:new Error("Invalid file returned")}}getUrl(e){return this.getPublicUrl(e)}getPublicUrl(e){let{fileId:r}=e;return`${this.url}/files/${r}`}async getPresignedUrl(e){let{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){let{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}};var Du=nt(ni()),Cr=class{constructor(e){let{url:r}=e;this.accessToken=null,this.instance=Du.default.create({baseURL:r})}async call(e,r,n){let i={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers},s;try{s=await this.instance.post(e,r,{...n,headers:i})}catch(a){if(a instanceof Error)return{res:null,error:a}}return s?{res:s,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var Zu=nt(ni()),ec=nt(Qu()),Dr=class{constructor(e){let{url:r}=e;this.url=r,this.accessToken=null,this.instance=Zu.default.create({baseURL:r})}async request(e,r,n){let i={...n==null?void 0:n.headers,...this.generateAccessTokenHeaders()};try{let s="",o=(await this.instance.post("",{operationName:s||void 0,query:typeof e=="string"?e:(0,ec.print)(e),variables:r},{...n,headers:i})).data,{data:u}=o;return o.errors?{data:null,error:o.errors}:typeof u!="object"||Array.isArray(u)||u===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:u,error:null}}catch(s){return s instanceof Error?{data:null,error:s}:(console.error(s),{data:null,error:new Error("Unable to get do GraphQL request")})}}getUrl(){return this.url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){if(!!this.accessToken)return{Authorization:`Bearer ${this.accessToken}`}}};var qr=class{constructor({backendUrl:e,refreshIntervalTime:r,clientStorageGetter:n,clientStorageSetter:i,clientStorage:s,clientStorageType:a,autoRefreshToken:o,autoSignIn:u,start:d=!0}){if(!e)throw new Error("Please specify a `backendUrl`. Docs: [todo]!");this.auth=new cr({url:`${e}/v1/auth`,refreshIntervalTime:r,clientStorageGetter:n,clientStorageSetter:i,clientStorage:s,clientStorageType:a,autoRefreshToken:o,autoSignIn:u,start:d}),this.storage=new Sr({url:`${e}/v1/storage`}),this.functions=new Cr({url:`${e}/v1/functions`}),this.graphql=new Dr({url:`${e}/v1/graphql`}),this.storage.setAccessToken(this.auth.getAccessToken()),this.functions.setAccessToken(this.auth.getAccessToken()),this.graphql.setAccessToken(this.auth.getAccessToken()),this.auth.client.onStart(()=>{this.auth.onAuthStateChanged((c,h)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{this.storage.setAccessToken(c==null?void 0:c.accessToken),this.functions.setAccessToken(c==null?void 0:c.accessToken),this.graphql.setAccessToken(c==null?void 0:c.accessToken)})})}};var yg=t=>new qr(t);export{qr as NhostClient,Cr as NhostFunctionsClient,Dr as NhostGraphqlClient,yg as createClient};
33
33
  /*! *****************************************************************************
34
34
  Copyright (c) Microsoft Corporation.
35
35