@nhost/nhost-js 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/umd/nhost-js.umd.js +1 -1
- package/umd/nhost-js.umd.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nhost/nhost-js",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.3",
|
|
4
4
|
"description": "Nhost JavaScript SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"cross-fetch": "^3.1.5",
|
|
47
47
|
"@nhost/hasura-auth-js": "2.0.0",
|
|
48
|
-
"@nhost/hasura-storage-js": "2.0.
|
|
48
|
+
"@nhost/hasura-storage-js": "2.0.1",
|
|
49
49
|
"@nhost/graphql-js": "0.0.3"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
package/umd/nhost-js.umd.js
CHANGED
|
@@ -16,5 +16,5 @@ Event: `).concat(JSON.stringify(h.data))),n.state;if(n.status!==Y.Running&&!n.op
|
|
|
16
16
|
Event: `).concat(JSON.stringify(h.data)));return n.scheduler.schedule(function(){n.forward(h);var y=n._nextState(h);n.update(y,h)}),n._state},this.sendTo=function(c,l,h){var y=n.parent&&(l===ie.Parent||n.parent.id===l),v=y?n.parent:L(l)?n.children.get(l)||dt.get(l):ei(l)?l:void 0;if(!v){if(!y)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));G||z(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(c.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var w=m(m({},c),{name:c.name===It?"".concat(Oe(n.id)):c.name,origin:n.sessionId});!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,w]):v.send(w)}}else!h&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,c.data]):v.send(c.data)},this._exec=function(c,l,h,y){y===void 0&&(y=n.machine.options.actions);var v=c.exec||st(c.type,y),w=B(v)?v:v?v.exec:c.exec;if(w)try{return w(l,h.data,n.machine.config.predictableActionArguments?{action:c,_event:h}:{action:c,state:n.state,_event:h})}catch(J){throw n.parent&&n.parent.send({type:"xstate.error",data:J}),J}switch(c.type){case ge:var T=c;if(typeof T.delay=="number"){n.defer(T);return}else T.to?n.sendTo(T._event,T.to,h===we):n.send(T._event);break;case kt:n.cancel(c.sendId);break;case Ye:{if(n.status!==Y.Running)return;var O=c.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[O.id||O.type])break;if(O.type===$.Invoke){var S=Er(O.src),A=n.machine.options.services?n.machine.options.services[S.type]:void 0,N=O.id,R=O.data;G||z(!("forward"in O),"`forward` property is deprecated (found in invocation of '".concat(O.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var q="autoForward"in O?O.autoForward:!!O.forward;if(!A){G||z(!1,"No service found for invocation '".concat(O.src,"' in machine '").concat(n.machine.id,"'."));return}var P=R?nt(R,l,h):void 0;if(typeof A=="string")return;var I=B(A)?A(l,h.data,{data:P,src:S,meta:O.meta}):A;if(!I)return;var j=void 0;ae(I)&&(I=P?I.withContext(P):I,j={autoForward:q}),n.spawn(I,N,j)}else n.spawnActivity(O);break}case We:{n.stopChild(c.activity.id);break}case Qe:var k=c.label,x=c.value;k?n.logger(k,x):n.logger(x);break;default:G||z(!1,"No implementation found for action type '".concat(c.type,"'"));break}};var i=m(m({},t.defaultOptions),r),o=i.clock,s=i.logger,u=i.parent,d=i.id,f=d!==void 0?d:e.id;this.id=f,this.logger=s,this.clock=o,this.parent=u,this.options=i,this.scheduler=new Lr({deferEvents:this.options.deferEvents}),this.sessionId=dt.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:ke(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return G||z(this.status!==Y.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var o=M(e.actions),s=o.next();!s.done;s=o.next()){var u=s.value;this.exec(u,e,r)}}catch(d){n={error:d}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,o,s,u,d,f,c,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===we)&&this.options.execute)this.execute(this.state);else for(var h=void 0;h=this._outgoingQueue.shift();)h[0].send(h[1]);if(this.children.forEach(function(j){l.state.children[j.id]=j}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var y=M(this.eventListeners),v=y.next();!v.done;v=y.next()){var w=v.value;w(e.event)}}catch(j){n={error:j}}finally{try{v&&!v.done&&(i=y.return)&&i.call(y)}finally{if(n)throw n.error}}try{for(var T=M(this.listeners),O=T.next();!O.done;O=T.next()){var w=O.value;w(e,e.event)}}catch(j){o={error:j}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.contextListeners),A=S.next();!A.done;A=S.next()){var N=A.value;N(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(j){u={error:j}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(this.state.done){var R=e.configuration.find(function(j){return j.type==="final"&&j.parent===l.machine}),q=R&&R.doneData?nt(R.doneData,e.context,r):void 0;try{for(var P=M(this.doneListeners),I=P.next();!I.done;I=P.next()){var w=I.value;w(Me(this.id,q))}}catch(j){f={error:j}}finally{try{I&&!I.done&&(c=P.return)&&c.call(P)}finally{if(f)throw f.error}}this._stop(),this._stopChildren()}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Y.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,o=it(e,r,n);this.listeners.add(o.next),this.status!==Y.NotStarted&&o.next(this.state);var s=function(){i.doneListeners.delete(s),i.stopListeners.delete(s),o.complete()};return this.status===Y.Stopped?o.complete():(this.onDone(s),this.onStop(s)),{unsubscribe:function(){i.listeners.delete(o.next),i.doneListeners.delete(s),i.stopListeners.delete(s)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===Y.Running)return this;this.machine._init(),dt.register(this.sessionId,this),this.initialized=!0,this.status=Y.Running;var n=e===void 0?this.initialState:ke(this,function(){return Ai(e)?r.machine.resolveState(e):r.machine.resolveState(oe.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,we)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){B(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,o,s,u,d,f,c;try{for(var l=M(this.listeners),h=l.next();!h.done;h=l.next()){var y=h.value;this.listeners.delete(y)}}catch(P){e={error:P}}finally{try{h&&!h.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=M(this.stopListeners),w=v.next();!w.done;w=v.next()){var y=w.value;y(),this.stopListeners.delete(y)}}catch(P){n={error:P}}finally{try{w&&!w.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var T=M(this.contextListeners),O=T.next();!O.done;O=T.next()){var y=O.value;this.contextListeners.delete(y)}}catch(P){o={error:P}}finally{try{O&&!O.done&&(s=T.return)&&s.call(T)}finally{if(o)throw o.error}}try{for(var S=M(this.doneListeners),A=S.next();!A.done;A=S.next()){var y=A.value;this.doneListeners.delete(y)}}catch(P){u={error:P}}finally{try{A&&!A.done&&(d=S.return)&&d.call(S)}finally{if(u)throw u.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Y.Stopped,this._initialState=void 0;try{for(var N=M(Object.keys(this.delayedEventsMap)),R=N.next();!R.done;R=N.next()){var q=R.value;this.clock.clearTimeout(this.delayedEventsMap[q])}}catch(P){f={error:P}}finally{try{R&&!R.done&&(c=N.return)&&c.call(N)}finally{if(f)throw f.error}}this.scheduler.clear(),this.scheduler=new Lr({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n=Q({type:"xstate.stop"}),i=ke(e,function(){var o=V(F([],D(e.state.configuration),!1).sort(function(c,l){return l.order-c.order}).map(function(c){return ce(c.onExit,e.machine.options.actions)})),s=D(Le(e.machine,e.state,e.state.context,n,[o],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),u=s[0],d=s[1],f=new oe({value:e.state.value,context:d,_event:n,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:u.filter(function(c){return c.type!==me&&(c.type!==ge||!!c.to&&c.to!==ie.Internal)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return f.changed=!0,f});e.update(i,n),e._stopChildren(),dt.free(e.sessionId)}),this},t.prototype.batch=function(e){var r=this;if(this.status===Y.NotStarted&&this.options.deferEvents)G||z(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,`" and are deferred. Make sure .start() is called for this service.
|
|
17
17
|
Event: `).concat(JSON.stringify(event)));else if(this.status!==Y.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,o,s=r.state,u=!1,d=[],f=function(y){var v=Q(y);r.forward(v),s=ke(r,function(){return r.machine.transition(s,v,void 0,n||void 0)}),d.push.apply(d,F([],D(r.machine.config.predictableActionArguments?s.actions:s.actions.map(function(w){return Oi(w,s)})),!1)),u=u||!!s.changed};try{for(var c=M(e),l=c.next();!l.done;l=c.next()){var h=l.value;f(h)}}catch(y){i={error:y}}finally{try{l&&!l.done&&(o=c.return)&&o.call(c)}finally{if(i)throw i.error}}s.changed=u,s.actions=d,r.update(s,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(xt)===0&&!this.state.nextEvents.some(function(s){return s.indexOf(xt)===0}))throw i.data.data;var o=ke(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return o},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=M(this.forwardTo),o=i.next();!o.done;o=i.next()){var s=o.value,u=this.children.get(s);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(s,"'."));u.send(e)}}catch(d){r={error:d}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this;this.delayedEventsMap[e.id]=this.clock.setTimeout(function(){e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),B(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return Nt(e,r);if(vr(e))return this.spawnPromise(Promise.resolve(e),r);if(B(e))return this.spawnCallback(e,r);if(wi(e))return this.spawnActor(e,r);if(Zn(e))return this.spawnObservable(e,r);if(ae(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(Jn(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),o=m(m({},jt),r);o.sync&&i.onTransition(function(u){n.send(Ze,{state:u,id:i.id})});var s=i;return this.children.set(i.id,s),o.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),s},t.prototype.spawnBehavior=function(e,r){var n=Pi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,o=!1,s;e.then(function(d){o||(s=d,i.removeChild(r),i.send(Q(Me(r,d),{origin:r})))},function(d){if(!o){i.removeChild(r);var f=Oe(r,d);try{i.send(Q(f,{origin:r}))}catch(c){ni(d,c,r),i.devTools&&i.devTools.send(f,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(d,f,c){var l=it(d,f,c),h=!1;return e.then(function(y){h||(l.next(y),!h&&l.complete())},function(y){h||l.error(y)}),{unsubscribe:function(){return h=!0}}},stop:function(){o=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return s}},n[fe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,o=!1,s=new Set,u=new Set,d,f=function(h){d=h,u.forEach(function(y){return y(h)}),!o&&i.send(Q(h,{origin:r}))},c;try{c=e(f,function(h){s.add(h)})}catch(h){this.send(Oe(r,h))}if(vr(c))return this.spawnPromise(c,r);var l=(n={id:r,send:function(h){return s.forEach(function(y){return y(h)})},subscribe:function(h){var y=it(h);return u.add(y.next),{unsubscribe:function(){u.delete(y.next)}}},stop:function(){o=!0,B(c)&&c()},toJSON:function(){return{id:r}},getSnapshot:function(){return d}},n[fe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,o,s=e.subscribe(function(d){o=d,i.send(Q(d,{origin:r}))},function(d){i.removeChild(r),i.send(Q(Oe(r,d),{origin:r}))},function(){i.removeChild(r),i.send(Q(Me(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(d,f,c){return e.subscribe(d,f,c)},stop:function(){return s.unsubscribe()},getSnapshot:function(){return o},toJSON:function(){return{id:r}}},n[fe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnActor=function(e,r){return this.children.set(r,e),e},t.prototype.spawnActivity=function(e){var r=this.machine.options&&this.machine.options.activities?this.machine.options.activities[e.type]:void 0;if(!r){G||z(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[fe]=function(){return this},n))},t.prototype.attachDev=function(){var e=Lt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Ri(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[fe]=function(){return this},t.prototype.getSnapshot=function(){return this.status===Y.NotStarted?this.initialState:this._state},t.defaultOptions={execute:!0,deferEvents:!0,clock:{setTimeout:function(e,r){return setTimeout(e,r)},clearTimeout:function(e){return clearTimeout(e)}},logger:console.log.bind(console),devTools:!1},t.interpret=xe,t}(),Ui=function(t){return L(t)?m(m({},jt),{name:t}):m(m(m({},jt),{name:ti()}),t)};function Di(t,e){var r=Ui(e);return yi(function(n){if(!G){var i=ae(t)||B(t);z(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(ae(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):Nt(t,r.name)})}function xe(t,e){var r=new _i(t,e);return r}function Ni(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function ht(t){return m(m({type:Xe},t),{toJSON:function(){t.onDone,t.onError;var e=Ot(t,["onDone","onError"]);return m(m({},e),{type:Xe,src:Ni(t.src)})}})}var Ie="",$t="#",Fe="*",Re={},Pe=function(t){return t[0]===$t},Ci=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},Mi=function(t,e,r){var n=r.slice(0,-1).some(function(o){return!("cond"in o)&&!("in"in o)&&(L(o.target)||ae(o.target))}),i=e===Ie?"the transient event":"event '".concat(e,"'");z(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},Li=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var o=this,s;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(Ci(),r),this.parent=i==null?void 0:i.parent,this.key=this.config.key||(i==null?void 0:i.key)||this.config.id||"(machine)",this.machine=this.parent?this.parent.machine:this,this.path=this.parent?this.parent.path.concat(this.key):[],this.delimiter=this.config.delimiter||(this.parent?this.parent.delimiter:lr),this.id=this.config.id||F([this.machine.key],D(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(s=this.config.schema)!==null&&s!==void 0?s:{},this.description=this.config.description,G||z(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?Ne(this.config.states,function(f,c){var l,h=new t(f,{},void 0,{parent:o,key:c});return Object.assign(o.idMap,m((l={},l[h.id]=h,l),h.idMap)),h}):Re;var u=0;function d(f){var c,l;f.order=u++;try{for(var h=M(Ur(f)),y=h.next();!y.done;y=h.next()){var v=y.value;d(v)}}catch(w){c={error:w}}finally{try{y&&!y.done&&(l=h.return)&&l.call(h)}finally{if(c)throw c.error}}}d(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(f){var c=f.event;return c===Ie}):Ie in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=te(this.config.entry||this.config.onEntry).map(function(f){return Ae(f)}),this.onExit=te(this.config.exit||this.config.onExit).map(function(f){return Ae(f)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=te(this.config.invoke).map(function(f,c){var l,h;if(ae(f)){var y=ot(o.id,c);return o.machine.options.services=m((l={},l[y]=f,l),o.machine.options.services),ht({src:y,id:y})}else if(L(f.src)){var y=f.id||ot(o.id,c);return ht(m(m({},f),{id:y,src:f.src}))}else if(ae(f.src)||B(f.src)){var y=f.id||ot(o.id,c);return o.machine.options.services=m((h={},h[y]=f.src,h),o.machine.options.services),ht(m(m({id:y},f),{src:y}))}else{var v=f.src;return ht(m(m({id:ot(o.id,c)},f),{src:v}))}}),this.activities=te(this.config.activities).concat(this.invoke).map(function(f){return at(f)}),this.transition=this.transition.bind(this),this.tags=te(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||Dr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,o=n.activities,s=n.guards,u=n.services,d=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},o),e.activities),guards:m(m({},s),e.guards),services:m(m({},u),e.services),delays:m(m({},d),e.delays)},r??this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return B(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:Ne(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===Ie,n=this.transitions.filter(function(i){var o=i.eventType===e;return r?o:o||i.eventType===Fe});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(o,s){var u=B(o)?"".concat(e.id,":delay[").concat(s,"]"):o,d=Pr(u,e.id);return e.onEntry.push(pe(d,{delay:o})),e.onExit.push(Or(d)),d},i=Te(r)?r.map(function(o,s){var u=n(o.delay,s);return m(m({},o),{event:u})}):V(Object.keys(r).map(function(o,s){var u=r[o],d=L(u)?{target:u}:u,f=isNaN(+o)?o:+o,c=n(f,s);return te(d).map(function(l){return m(m({},l),{event:c,delay:f})})}));return i.map(function(o){var s=o.delay;return m(m({},e.formatTransition(o)),{delay:s})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof oe?e.value:De(e,this.delimiter);if(L(i)){var o=this.getStateNode(i).initial;return o!==void 0?this.getStateNodes((r={},r[i]=o,r)):[this,this.states[i]]}var s=Object.keys(i),u=[this];return u.push.apply(u,F([],D(V(s.map(function(d){return n.getStateNode(d).getStateNodes(i[d])}))),!1)),u},t.prototype.handles=function(e){var r=hr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof oe?e:oe.create(e),n=Array.from($e([],this.getStateNodes(r.value)));return new oe(m(m({},r),{value:this.resolve(r.value),configuration:n,done:lt(n,this),tags:Cr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),o=i.next(r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),o=this.getStateNode(i[0]),s=o._transition(e[i[0]],r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionParallelNode=function(e,r,n){var i,o,s={};try{for(var u=M(Object.keys(e)),d=u.next();!d.done;d=u.next()){var f=d.value,c=e[f];if(c){var l=this.getStateNode(f),h=l._transition(c,r,n);h&&(s[f]=h)}}}catch(S){i={error:S}}finally{try{d&&!d.done&&(o=u.return)&&o.call(u)}finally{if(i)throw i.error}}var y=Object.keys(s).map(function(S){return s[S]}),v=V(y.map(function(S){return S.transitions})),w=y.some(function(S){return S.transitions.length>0});if(!w)return this.next(r,n);var T=V(y.map(function(S){return S.entrySet})),O=V(Object.keys(s).map(function(S){return s[S].configuration}));return{transitions:v,entrySet:T,exitSet:V(y.map(function(S){return S.exitSet})),configuration:O,source:r,actions:V(Object.keys(s).map(function(S){return s[S].actions}))}},t.prototype._transition=function(e,r,n){return L(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,o=this,s=r.name,u=[],d=[],f;try{for(var c=M(this.getCandidates(s)),l=c.next();!l.done;l=c.next()){var h=l.value,y=h.cond,v=h.in,w=e.context,T=v?L(v)&&Pe(v)?e.matches(De(this.getStateNodeById(v).path,this.delimiter)):Pt(De(v,this.delimiter),zn(this.path.slice(0,-2))(e.value)):!0,O=!1;try{O=!y||wr(this.machine,y,w,r,e)}catch(R){throw new Error("Unable to evaluate guard '".concat(y.name||y.type,"' in transition for event '").concat(s,"' in state node '").concat(this.id,`':
|
|
18
18
|
`).concat(R.message))}if(O&&T){h.target!==void 0&&(d=h.target),u.push.apply(u,F([],D(h.actions),!1)),f=h;break}}}catch(R){n={error:R}}finally{try{l&&!l.done&&(i=c.return)&&i.call(c)}finally{if(n)throw n.error}}if(f){if(!d.length)return{transitions:[f],entrySet:[],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var S=V(d.map(function(R){return o.getRelativeStateNodes(R,e.historyValue)})),A=!!f.internal,N=[];return A||d.forEach(function(R){N.push.apply(N,F([],D(o.getExternalReentryNodes(R)),!1))}),{transitions:[f],entrySet:N,exitSet:A?[]:[this],configuration:S,source:e,actions:u}}},t.prototype.getExternalReentryNodes=function(e){for(var r=[],n=D(e.order>this.order?[e,this]:[this,e],2),i=n[0],o=n[1];i&&i!==o;)r.push(i),i=i.parent;return i!==o?[]:(r.push(o),r)},t.prototype.getActions=function(e,r,n,i,o,s,u){var d,f,c,l,h=this,y=$e([],s?this.getStateNodes(s.value):[this]);try{for(var v=M(e),w=v.next();!w.done;w=v.next()){var T=w.value;(!Be(y,T)||Be(n.entrySet,T.parent))&&n.entrySet.push(T)}}catch(k){d={error:k}}finally{try{w&&!w.done&&(f=v.return)&&f.call(v)}finally{if(d)throw d.error}}try{for(var O=M(y),S=O.next();!S.done;S=O.next()){var T=S.value;(!Be(e,T)||Be(n.exitSet,T.parent))&&n.exitSet.push(T)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(l=O.return)&&l.call(O)}finally{if(c)throw c.error}}var A=V(n.entrySet.map(function(k){var x=[];if(k.type!=="final")return x;var J=k.parent;if(!J.parent)return x;x.push(Ce(k.id,k.doneData),Ce(J.id,k.doneData?nt(k.doneData,i,o):void 0));var K=J.parent;return K.type==="parallel"&&je(K).every(function(a){return lt(n.configuration,a)})&&x.push(Ce(K.id)),x}));n.exitSet.sort(function(k,x){return x.order-k.order}),n.entrySet.sort(function(k,x){return k.order-x.order});var N=new Set(n.entrySet),R=new Set(n.exitSet),q=Array.from(N).map(function(k){var x=k.onEntry,J=k.activities.map(function(K){return kr(K)});return ce(u?F(F([],D(x),!1),D(J),!1):F(F([],D(J),!1),D(x),!1),h.machine.options.actions)}).concat([A.map(Sr)]),P=Array.from(R).map(function(k){return ce(F(F([],D(k.onExit),!1),D(k.activities.map(function(x){return xr(x)})),!1),h.machine.options.actions)}),I=P.concat([ce(n.actions,this.machine.options.actions)]).concat(q);if(r){var j=ce(V(F([],D(e),!1).sort(function(k,x){return x.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return k.type!==me&&(k.type!==ge||!!k.to&&k.to!==ie.Internal)});return I.concat([j])}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var o=Q(r),s;if(e instanceof oe)s=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=L(e)?this.resolve(tt(this.getResolvedPath(e))):this.resolve(e),d=n??this.machine.context;s=this.resolveState(oe.from(u,d))}if(!G&&o.name===Fe)throw new Error("An event cannot have the wildcard type ('".concat(Fe,"')"));if(this.strict&&!this.events.includes(o.name)&&!Wn(o.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(o.name,"'"));var f=this._transition(s.value,s,o)||{transitions:[],configuration:[],entrySet:[],exitSet:[],source:s,actions:[]},c=$e([],this.getStateNodes(s.value)),l=f.configuration.length?$e(c,f.configuration):c;return f.configuration=F([],D(l),!1),this.resolveTransition(f,s,s.context,i,o)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var o,s=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(o=e.actions).unshift.apply(o,F([],D(s),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,o){var s,u,d,f,c=this;o===void 0&&(o=we);var l=e.configuration,h=!r||e.transitions.length>0,y=h?e.configuration:r?r.configuration:[],v=lt(y,this),w=h?Si(this.machine,l):void 0,T=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,O=this.getActions(new Set(y),v,e,n,o,r,i),S=r?m({},r.activities):{};try{for(var A=M(O),N=A.next();!N.done;N=A.next()){var R=N.value;try{for(var q=(d=void 0,M(R)),P=q.next();!P.done;P=q.next()){var I=P.value;I.type===Ye?S[I.activity.id||I.activity.type]=I:I.type===We&&(S[I.activity.id||I.activity.type]=!1)}}catch(Z){d={error:Z}}finally{try{P&&!P.done&&(f=q.return)&&f.call(q)}finally{if(d)throw d.error}}}}catch(Z){s={error:Z}}finally{try{N&&!N.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}var j=D(Le(this,r,n,o,O,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),k=j[0],x=j[1],J=D(Qn(k,function(Z){return Z.type===me||Z.type===ge&&Z.to===ie.Internal}),2),K=J[0],a=J[1],p=k.filter(function(Z){var Ue;return Z.type===Ye&&((Ue=Z.activity)===null||Ue===void 0?void 0:Ue.type)===Xe}),E=p.reduce(function(Z,Ue){return Z[Ue.activity.id]=mi(Ue.activity,c.machine,x,o),Z},r?m({},r.children):{}),C=new oe({value:w||r.value,context:x,_event:o,_sessionid:r?r._sessionid:null,historyValue:w?T?Xn(T,w):void 0:r?r.historyValue:void 0,history:!w||e.source?r:void 0,actions:w?a:[],activities:w?S:r?r.activities:{},events:[],configuration:y,transitions:e.transitions,children:E,done:v,tags:Cr(y),machine:this}),_=n!==x;C.changed=o.name===Ze||_;var b=C.history;b&&delete b.history;var ee=!v&&(this._transient||l.some(function(Z){return Z._transient}));if(!h&&(!ee||o.name===Ie))return C;var H=C;if(!v)for(ee&&(H=this.resolveRaisedTransition(H,{type:sr},o,i));K.length;){var he=K.shift();H=this.resolveRaisedTransition(H,he._event,o,i)}var yo=H.changed||(b?!!H.actions.length||_||typeof b.value!=typeof H.value||!Mr(H.value,b.value):void 0);return H.changed=yo,H.history=b,H},t.prototype.getStateNode=function(e){if(Pe(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Pe(e)?e.slice($t.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Pe(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=_t(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Re;switch(this.type){case"parallel":return Ne(this.initialStateValue,function(o,s){return o?n.getStateNode(s).resolve(e[s]||o):Re});case"compound":if(L(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?Ne(e,function(o,s){return o?n.getStateNode(s).resolve(o):Re}):this.initialStateValue||{};default:return e||Re}},t.prototype.getResolvedPath=function(e){if(Pe(e)){var r=this.machine.idMap[e.slice($t.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return _t(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=fr(this.states,function(n){return n.initialStateValue||Re},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=ut(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,entrySet:F([],D(n),!1),exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r??this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;L(r.target)?e=Pe(r.target)?tt(this.machine.getStateNodeById(r.target).path.slice(this.path.length-1)):r.target:e=r.target}return e},enumerable:!1,configurable:!0}),t.prototype.getRelativeStateNodes=function(e,r,n){return n===void 0&&(n=!0),n?e.type==="history"?e.resolveHistory(r):e.initialStateNodes:[e]},Object.defineProperty(t.prototype,"initialStateNodes",{get:function(){var e=this;if(ut(this))return[this];if(this.type==="compound"&&!this.initial)return G||z(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=rt(this.initialStateValue);return V(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=D(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var o=this.getStateNode(n);if(o.type==="history")return o.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:fr(this.states,function(r,n){if(!e)return r.historyValue();var i=L(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?V(rt(i).map(function(s){return n.getFromRelativePath(s)})):n.initialStateNodes}var o=Yn(n.path,"states")(e).current;return L(o)?[n.getStateNode(o)]:V(rt(o).map(function(s){return r.history==="deep"?n.getFromRelativePath(s):[n.states[s[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=V(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var o=this.states,s=new Set(this.ownEvents);if(o)try{for(var u=M(Object.keys(o)),d=u.next();!d.done;d=u.next()){var f=d.value,c=o[f];if(c.states)try{for(var l=(n=void 0,M(c.events)),h=l.next();!h.done;h=l.next()){var y=h.value;s.add("".concat(y))}}catch(v){n={error:v}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(s)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!L(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var o=i?r.key+n:n;if(r.parent)try{var s=r.parent.getStateNodeByPath(o);return s}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=ri(e.target),i="internal"in e?e.internal:n?n.some(function(d){return L(d)&&d[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=m(m({},e),{actions:ce(te(e.actions)),cond:gr(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(d){return"#".concat(d.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var o=this.config.on,s=Fe,u=o[s],d=u===void 0?[]:u,f=Ot(o,[typeof s=="symbol"?s:s+""]);i=V(Object.keys(f).map(function(S){!G&&S===Ie&&z(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var A=be(S,f[S]);return G||Mi(n,S,A),A}).concat(be(Fe,d)))}var c=this.config.always?be("",this.config.always):[],l=this.config.onDone?be(String(Ce(this.id)),this.config.onDone):[];G||z(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=V(this.invoke.map(function(S){var A=[];return S.onDone&&A.push.apply(A,F([],D(be(String(Me(S.id)),S.onDone)),!1)),S.onError&&A.push.apply(A,F([],D(be(String(Oe(S.id)),S.onError)),!1)),A})),y=this.after,v=V(F(F(F(F([],D(l),!1),D(h),!1),D(i),!1),D(c),!1).map(function(S){return te(S).map(function(A){return n.formatTransition(A)})}));try{for(var w=M(y),T=w.next();!T.done;T=w.next()){var O=T.value;v.push(O)}}catch(S){e={error:S}}finally{try{T&&!T.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),jr=!1;function ve(t,e){return!G&&!t.predictableActionArguments&&!jr&&(jr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Li(t,e)}var U=Rr,W=pe;/*! js-cookie v3.0.1 | MIT */function ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var ji={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Bt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=ft({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var d in s)s[d]&&(u+="; "+d,s[d]!==!0&&(u+="="+s[d].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var d=o[u].split("="),f=d.slice(1).join("=");try{var c=decodeURIComponent(d[0]);if(s[c]=t.read(f,c),i===c)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",ft({},o,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,ft({},this.attributes,i))},withConverter:function(i){return Bt(ft({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Ft=Bt(ji,{path:"/"}),$i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt={exports:{}};(function(t,e){var r=typeof self<"u"?self:$i,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(p,E){this.message=p,this.name=E;var C=Error(p);this.stack=C.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(qt,qt.exports);const Gt=Bi(qt.exports),qe="nhostRefreshToken",Ge="nhostRefreshTokenExpiresAt",$r=3,Br=300,Vt=5,Ht=0,Kt=1,re=10,_e=20;class Ve extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Kt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},Fr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},qr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},pt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},zt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Gr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Vr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Hr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Kr={status:_e,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:_e,error:"already-signed-in",message:"User is already signed in"},zr={status:_e,error:"unauthenticated-user",message:"User is not authenticated"},Fi={status:_e,error:"user-not-anonymous",message:"User is not anonymous"},Yr={status:_e,error:"unverified-user",message:"Email needs verification"},Wr={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Jr={status:Kt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},vt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qi(t){return new TextEncoder().encode(t)}function Ee(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function Qr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Xr(t){const{id:e}=t;return{...t,id:Yt(e),transports:t.transports}}function Zr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class X extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Gi({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new X("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(Zr(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Vi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Vi;async function en(t){if(!Qr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Yt(t.challenge),user:{...t.user,id:qi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Xr)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(d){throw Gi({error:d,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function Hi(t){return new TextDecoder("utf-8").decode(t)}async function Ki(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function zi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Zr(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Yi(t,e=!1){var r,n;if(!Qr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Xr));const o={...t,challenge:Yt(t.challenge),allowCredentials:i},s={};if(e){if(!await Ki())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=yt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(y){throw zi({error:y,options:s})}finally{yt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:d,rawId:f,response:c,type:l}=u;let h;return c.userHandle&&(h=Hi(c.userHandle)),{id:d,rawId:Ee(f),response:{authenticatorData:Ee(c.authenticatorData),clientDataJSON:Ee(c.clientDataJSON),signature:Ee(c.signature),userHandle:h},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const mt=typeof window<"u",gt=new Map,Wi=t=>mt&&typeof localStorage<"u"?localStorage.getItem(t):gt.get(t)??null,Ji=(t,e)=>{mt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?gt.set(t,e):gt.has(t)&>.delete(t)},tn=(t,e)=>{if(t==="localStorage"||t==="web")return Wi;if(t==="cookie")return r=>mt?Ft.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},rn=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return(r,n)=>{mt&&(n?Ft.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Ft.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ye=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},wt=()=>typeof window<"u",nn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Gt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const s={message:"Network Error",status:Ht,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>nn(t,"POST",{token:r,body:e}),on=(t,e)=>nn(t,"GET",{token:e}),Wt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let d=Object.fromEntries(u);r.startsWith("/")&&(d={...o,...d});let f=i.pathname;return s.pathname.length>1&&(f+=s.pathname.slice(1)),{...n,redirectTo:Wt(s.origin+f,d)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Jt(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Et=t=>!!t&&typeof t=="string"&&t.length>=$r,Qt=t=>!!t&&typeof t=="string",sn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),an=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=tn(r,n),d=rn(r,n),f=async(c,l,h)=>(await le(`${t}${c}`,l,h)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:vt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:W("SIGNED_IN"),reportSignedOut:W("SIGNED_OUT"),reportTokenChanged:W("TOKEN_CHANGED"),incrementTokenImportAttempts:U({importTokenAttempts:({importTokenAttempts:c})=>c+1}),clearContext:U(()=>(d(Ge,null),d(qe,null),{...vt})),clearContextExceptRefreshToken:U(({refreshToken:{value:c}})=>(d(Ge,null),{...vt,refreshToken:{value:c}})),saveSession:U({user:(c,{data:l})=>{var h;return((h=l==null?void 0:l.session)==null?void 0:h.user)||null},accessToken:(c,{data:l})=>{if(l.session){const{accessTokenExpiresIn:h,accessToken:y}=l.session,v=new Date(Date.now()+h*1e3);return d(Ge,v.toISOString()),{value:y,expiresAt:v}}return d(Ge,null),{value:null,expiresAt:null}},refreshToken:(c,{data:l})=>{var h;const y=((h=l.session)==null?void 0:h.refreshToken)||null;return y&&d(qe,y),{value:y}}}),saveMfaTicket:U({mfa:(c,l)=>{var h;return(h=l.data)==null?void 0:h.mfa}}),resetTimer:U({refreshTimer:c=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:U({refreshTimer:(c,l)=>({startedAt:c.refreshTimer.startedAt,attempts:c.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:U({errors:({errors:c},{data:{error:l}})=>({...c,authentication:l})}),resetErrors:U({errors:c=>({}),importTokenAttempts:c=>0}),saveRegistrationError:U({errors:({errors:c},{data:{error:l}})=>({...c,registration:l})}),destroyRefreshToken:U({refreshToken:c=>(d(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Jt("refreshToken"),Jt("type"))},broadcastToken:c=>{if(s)try{new BroadcastChannel("nhost").postMessage(c.refreshToken.value)}catch{}}},guards:{isAnonymous:(c,l)=>{var h;return!!((h=c.user)!=null&&h.isAnonymous)},isSignedIn:c=>!!c.user&&!!c.refreshToken.value&&!!c.accessToken.value,noToken:c=>!c.refreshToken.value,hasRefreshToken:c=>!!c.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:c=>{const{expiresAt:l}=c.accessToken;return l?c.refreshTimer.lastAttempt?c.refreshTimer.attempts>Vt?!1:Date.now()-c.refreshTimer.lastAttempt.getTime()>Math.pow(2,c.refreshTimer.attempts-1)*5e3:i&&Date.now()-c.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Br<=0:!1},shouldRetryImportToken:(c,l)=>c.importTokenAttempts<Vt&&(l.data.error.status===Ht||l.data.error.status>=500),unverified:(c,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(c,l)=>{var h;return!!((h=l.data)!=null&&h.session)},hasMfaTicket:(c,l)=>{var h;return!!((h=l.data)!=null&&h.mfa)}},services:{signInPassword:(c,{email:l,password:h})=>de(l)?Et(h)?f("/signin/email-password",{email:l,password:h}):Promise.reject({error:pt}):Promise.reject({error:ue}),passwordlessSms:(c,{phoneNumber:l,options:h})=>{var y;return Qt(l)?(y=c.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:ne(e,h)},c.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:ne(e,h)}):Promise.reject({error:zt})},passwordlessSmsOtp:(c,{phoneNumber:l,otp:h})=>Qt(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:h}):Promise.reject({error:zt}),passwordlessEmail:(c,{email:l,options:h})=>{var y;return de(l)?(y=c.user)!=null&&y.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:ne(e,h)},c.accessToken.value):f("/signin/passwordless/email",{email:l,options:ne(e,h)}):Promise.reject({error:ue})},signInAnonymous:c=>f("/signin/anonymous"),signInMfaTotp:(c,l)=>{var h;const y=l.ticket||((h=c.mfa)==null?void 0:h.ticket);return y?sn(y)?f("/signin/mfa/totp",{ticket:y,otp:l.otp}):Promise.reject({error:Gr}):Promise.reject({error:Vr})},signInSecurityKeyEmail:async(c,{email:l})=>{if(!de(l))throw new Ve(ue);const h=await f("/signin/webauthn",{email:l});let y;try{y=await Yi(h)}catch(v){throw new Ve(v)}return f("/signin/webauthn/verify",{email:l,credential:y})},refreshToken:async(c,l)=>{const h=l.type==="TRY_TOKEN"?l.token:c.refreshToken.value;return{session:await f("/token",{refreshToken:h}),error:null}},signout:(c,l)=>f("/signout",{refreshToken:c.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(c,{email:l,password:h,options:y})=>{var v;return de(l)?Et(h)?(v=c.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:h,options:ne(e,y)},c.accessToken.value):f("/signup/email-password",{email:l,password:h,options:ne(e,y)}):Promise.reject({error:pt}):Promise.reject({error:ue})},signUpSecurityKey:async(c,{email:l,options:h})=>{if(!de(l))return Promise.reject({error:ue});const y=h==null?void 0:h.nickname;y&&delete h.nickname;const v=await f("/signup/webauthn",{email:l,options:h});let w;try{w=await en(v)}catch(T){throw new Ve(T)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:h==null?void 0:h.redirectTo,nickname:y}})},importRefreshToken:async c=>{if(c.user&&c.refreshToken.value&&c.accessToken.value&&c.accessToken.expiresAt)return{session:{accessToken:c.accessToken.value,accessTokenExpiresIn:c.accessToken.expiresAt.getTime()-Date.now(),refreshToken:c.refreshToken.value,user:c.user},error:null};let l=null;if(s){const y=Ke("refreshToken")||null;if(y)try{return{session:await f("/token",{refreshToken:y}),error:null}}catch(v){l=v.error}else{const v=Ke("error");if(v)return Promise.reject({session:null,error:{status:re,error:v,message:Ke("errorDescription")||v}})}}const h=await u(qe);if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(y){l=y.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:c})=>Math.pow(2,c-1)*5e3}})},cn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:n=>ue}),saveRequestError:U({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),un=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:U({error:r=>pt}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!Et(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:U({error:r=>Fr}),saveInvalidMfaCodeError:U({error:r=>qr}),saveError:U({error:(r,{data:{error:n}})=>n}),saveGeneration:U({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:W((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS"),reportGeneratedSuccess:W("GENERATED"),reportGeneratedError:W(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await on(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ln=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),dn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let Xt=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...d}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=an({...d,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var c;const l=(c=this.interpreter)==null?void 0:c.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||xe(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}};class hn extends Xt{constructor({...e}){super({...e,autoSignIn:wt()&&e.autoSignIn,autoRefreshToken:wt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=hn,fn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await en(n)}catch(s){throw new Ve(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},pn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),vn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Zi=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),eo=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),yn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),mn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),gn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),Zt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),En=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),er=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),bn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:zr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),tr=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),An=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class On{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var d;this.url=e,this._client=new Xt({backendUrl:e,clientUrl:typeof window<"u"&&((d=window.location)==null?void 0:d.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await An(r,n,i)):ye(await tr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await gn(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Wt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return wt()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await wn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Yr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await En(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await Zt(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await Tn(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Sn(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:Jr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await bn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(ln(this._client)).start(),{error:i}=await yn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(un(this._client)).start(),{error:i}=await vn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(dn(this._client)).start(),{error:i}=await mn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(cn(this._client)).start(),{error:i}=await pn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Zt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await tr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await fn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Bn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Hr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Kr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:Wr}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var kn=typeof self=="object"?self.FormData:window.FormData,to=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rr={exports:{}};(function(t,e){var r=typeof self<"u"?self:to,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,p){this.message=a,this.name=p;var E=Error(a);this.stack=E.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(rr,rr.exports);const nr=ro(rr.exports),no=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},xn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const d={};i&&(d["x-nhost-file-id"]=i),o&&(d["x-nhost-bucket-id"]=o),n&&(d["x-nhost-file-name"]=no(n)),s&&(d["x-hasura-admin-secret"]=s),r&&(d.Authorization=`Bearer ${r}`);const f=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const c=await nr(f,{method:"POST",headers:d,body:e});return c.ok?{fileMetadata:await c.json(),error:null}:{error:{status:c.status,message:await c.text(),error:c.statusText},fileMetadata:null}}catch(c){return{error:{status:0,message:c.message,error:c.message},fileMetadata:null}}return new Promise(c=>{console.log("NOOOOOOO");let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):c({fileMetadata:l.response,error:null}),l.onerror=()=>c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),u&&l.upload.addEventListener("progress",u,!1),l.open("POST",f,!0),Object.entries(d).forEach(([h,y])=>{l.setRequestHeader(h,y)}),l.send(e)})};class In{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return xn(this.url,r,{accessToken:this.accessToken,adminSecret:this.accessToken,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const Rn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Pn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new In({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new kn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Rn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const St={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},_n=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...St},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:U({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:U({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:U({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:U({progress:t=>null,loaded:t=>0}),resetContext:U(t=>St),addFile:U({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new kn;i.append("file",n);let o=0;return xn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,d=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:d})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:d,bucketId:f}=s;r({type:"UPLOAD_DONE",id:d,bucketId:f})}}),()=>{}}}}),{pure:ir,sendParent:Tt}=vi,io=()=>ve({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:U((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:U({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:U({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:U({loaded:t=>0}),startProgress:U({progress:t=>0}),resetProgress:U({progress:t=>null}),addItem:U((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Di(_n().withConfig({actions:{sendProgress:Tt((u,{additions:d})=>({type:"UPLOAD_PROGRESS",additions:d})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...St,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:U({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:ir(t=>t.files.map(e=>W({type:"DESTROY"},{to:e.id}))),upload:ir((t,e)=>t.files.map(r=>W(e,{to:r.id}))),cancel:ir(t=>t.files.map(e=>W({type:"CANCEL"},{to:e.id})))}}),oo=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),so=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ao=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function bt(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const o=n.match(ao);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:d=1337}=o.groups,f=lo(e);return f||`${s}://${u}:${d}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function co(){return typeof window<"u"}function uo(){return typeof process<"u"&&process.env}function lo(t){return co()||!uo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Un(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new On({url:e,...t})}function Dn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Nn({url:e,...t})}class Nn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Gt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ho(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Cn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function fo(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Cn(n)}catch{}return{query:t,operationName:r}}const e=Cn(t);return{query:Se.print(t),operationName:e}}class po{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,o=ho(e,n,i),{headers:s,...u}=i||{},{query:d,operationName:f}=fo(o.document);try{const c=await Gt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:d,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!c.ok)return{data:null,error:{error:c.statusText,message:c.statusText,status:c.status}};const{data:l,errors:h}=await c.json();return h?{data:null,error:h}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(c){const l=c;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Mn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new po({url:e,...t})}function Ln(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pn({url:e,...t})}const vo=t=>new jn(t);class jn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:d=!0,...f}){this.auth=Un({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:d,...f}),this.storage=Ln({adminSecret:s,...f}),this.functions=Dn({adminSecret:s,...f}),this.graphql=Mn({adminSecret:s,...f}),this.auth.onAuthStateChanged((c,l)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Xt,g.AuthClientSSR=Xi,g.AuthCookieClient=hn,g.CodifiedError=Ve,g.EMAIL_NEEDS_VERIFICATION=Yr,g.HasuraAuthClient=On,g.HasuraStorageApi=In,g.HasuraStorageClient=Pn,g.INITIAL_FILE_CONTEXT=St,g.INITIAL_MACHINE_CONTEXT=vt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=qr,g.INVALID_MFA_TICKET_ERROR=Gr,g.INVALID_MFA_TYPE_ERROR=Fr,g.INVALID_PASSWORD_ERROR=pt,g.INVALID_PHONE_NUMBER_ERROR=zt,g.INVALID_REFRESH_TOKEN=Wr,g.INVALID_SIGN_IN_METHOD=Jr,g.MIN_PASSWORD_LENGTH=$r,g.NETWORK_ERROR_CODE=Ht,g.NHOST_JWT_EXPIRES_AT_KEY=Ge,g.NHOST_REFRESH_TOKEN_KEY=qe,g.NO_MFA_TICKET_ERROR=Vr,g.NO_REFRESH_TOKEN=Hr,g.NhostClient=jn,g.NhostFunctionsClient=Nn,g.OTHER_ERROR_CODE=Kt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Vt,g.STATE_ERROR_CODE=_e,g.TOKEN_REFRESHER_RUNNING_ERROR=Kr,g.TOKEN_REFRESH_MARGIN=Br,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=Fi,g.USER_UNAUTHENTICATED=zr,g.VALIDATION_ERROR_CODE=re,g.activateMfaPromise=eo,g.addSecurityKeyPromise=fn,g.appendImageTransformationParameters=Rn,g.changeEmailPromise=pn,g.changePasswordPromise=vn,g.createAuthClient=Un,g.createAuthMachine=an,g.createChangeEmailMachine=cn,g.createChangePasswordMachine=un,g.createEnableMfaMachine=Qi,g.createFileUploadMachine=_n,g.createFunctionsClient=Dn,g.createGraphqlClient=Mn,g.createMultipleFilesUploadMachine=io,g.createNhostClient=vo,g.createResetPasswordMachine=ln,g.createSendVerificationEmailMachine=dn,g.createStorageClient=Ln,g.encodeQueryParameters=Wt,g.generateQrCodePromise=Zi,g.getAuthenticationResult=ye,g.getFetch=on,g.getParameterByName=Ke,g.getSession=He,g.isBrowser=wt,g.isValidEmail=de,g.isValidPassword=Et,g.isValidPhoneNumber=Qt,g.isValidTicket=sn,g.localStorageGetter=tn,g.localStorageSetter=rn,g.postFetch=le,g.removeParameterFromWindow=Jt,g.resetPasswordPromise=yn,g.rewriteRedirectTo=ne,g.sendVerificationEmailPromise=mn,g.signInAnonymousPromise=gn,g.signInEmailPasswordPromise=wn,g.signInEmailPasswordlessPromise=Zt,g.signInEmailSecurityKeyPromise=En,g.signInMfaTotpPromise=Sn,g.signInSmsPasswordlessOtpPromise=Tn,g.signInSmsPasswordlessPromise=er,g.signOutPromise=bn,g.signUpEmailPasswordPromise=tr,g.signUpEmailSecurityKeyPromise=An,g.uploadFilePromise=oo,g.uploadMultipleFilesPromise=so,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
19
|
+
`).concat(u.message))}else return r.getStateNodeByPath(o)})},t.prototype.formatTransition=function(e){var r=this,n=ri(e.target),i="internal"in e?e.internal:n?n.some(function(d){return L(d)&&d[0]===r.delimiter}):!0,o=this.machine.options.guards,s=this.resolveTarget(n),u=m(m({},e),{actions:ce(te(e.actions)),cond:gr(e.cond,o),target:s,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(d){return"#".concat(d.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var o=this.config.on,s=Fe,u=o[s],d=u===void 0?[]:u,f=Ot(o,[typeof s=="symbol"?s:s+""]);i=V(Object.keys(f).map(function(S){!G&&S===Ie&&z(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var A=be(S,f[S]);return G||Mi(n,S,A),A}).concat(be(Fe,d)))}var c=this.config.always?be("",this.config.always):[],l=this.config.onDone?be(String(Ce(this.id)),this.config.onDone):[];G||z(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var h=V(this.invoke.map(function(S){var A=[];return S.onDone&&A.push.apply(A,F([],D(be(String(Me(S.id)),S.onDone)),!1)),S.onError&&A.push.apply(A,F([],D(be(String(Oe(S.id)),S.onError)),!1)),A})),y=this.after,v=V(F(F(F(F([],D(l),!1),D(h),!1),D(i),!1),D(c),!1).map(function(S){return te(S).map(function(A){return n.formatTransition(A)})}));try{for(var w=M(y),T=w.next();!T.done;T=w.next()){var O=T.value;v.push(O)}}catch(S){e={error:S}}finally{try{T&&!T.done&&(r=w.return)&&r.call(w)}finally{if(e)throw e.error}}return v},t}(),jr=!1;function ve(t,e){return!G&&!t.predictableActionArguments&&!jr&&(jr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new Li(t,e)}var U=Rr,W=pe;/*! js-cookie v3.0.1 | MIT */function ft(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var ji={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Bt(t,e){function r(i,o,s){if(!(typeof document>"u")){s=ft({},e,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var d in s)s[d]&&(u+="; "+d,s[d]!==!0&&(u+="="+s[d].split(";")[0]));return document.cookie=i+"="+t.write(o,i)+u}}function n(i){if(!(typeof document>"u"||arguments.length&&!i)){for(var o=document.cookie?document.cookie.split("; "):[],s={},u=0;u<o.length;u++){var d=o[u].split("="),f=d.slice(1).join("=");try{var c=decodeURIComponent(d[0]);if(s[c]=t.read(f,c),i===c)break}catch{}}return i?s[i]:s}}return Object.create({set:r,get:n,remove:function(i,o){r(i,"",ft({},o,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,ft({},this.attributes,i))},withConverter:function(i){return Bt(ft({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Ft=Bt(ji,{path:"/"}),$i=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qt={exports:{}};(function(t,e){var r=typeof self<"u"?self:$i,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(p,E){this.message=p,this.name=E;var C=Error(p);this.stack=C.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(qt,qt.exports);const Gt=Bi(qt.exports),qe="nhostRefreshToken",Ge="nhostRefreshTokenExpiresAt",$r=3,Br=300,Vt=5,Ht=0,Kt=1,re=10,_e=20;class Ve extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Kt,message:e.message}):(this.name=e.error,this.error=e)}}const ue={status:re,error:"invalid-email",message:"Email is incorrectly formatted"},Fr={status:re,error:"invalid-mfa-type",message:"MFA type is invalid"},qr={status:re,error:"invalid-mfa-code",message:"MFA code is invalid"},pt={status:re,error:"invalid-password",message:"Password is incorrectly formatted"},zt={status:re,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Gr={status:re,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Vr={status:re,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},Hr={status:re,error:"no-refresh-token",message:"No refresh token has been provided"},Kr={status:_e,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},se={status:_e,error:"already-signed-in",message:"User is already signed in"},zr={status:_e,error:"unauthenticated-user",message:"User is not authenticated"},Fi={status:_e,error:"user-not-anonymous",message:"User is not anonymous"},Yr={status:_e,error:"unverified-user",message:"Email needs verification"},Wr={status:re,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},Jr={status:Kt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},vt={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qi(t){return new TextEncoder().encode(t)}function Ee(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yt(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),o=new ArrayBuffer(i.length),s=new Uint8Array(o);for(let u=0;u<i.length;u++)s[u]=i.charCodeAt(u);return o}function Qr(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Xr(t){const{id:e}=t;return{...t,id:Yt(e),transports:t.transports}}function Zr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class X extends Error{constructor(e,r="WebAuthnError"){super(e),this.name=r}}function Gi({error:t,options:e}){var r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Registration ceremony was sent an abort signal","AbortError")}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new X("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new X("User verification was required but no available authenticator supported it","ConstraintError")}else{if(t.name==="InvalidStateError")return new X("The authenticator was previously registered","InvalidStateError");if(t.name==="NotAllowedError")return new X("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new X('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new X("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(t.name==="SecurityError"){const o=window.location.hostname;if(Zr(o)){if(i.rp.id!==o)return new X(`The RP ID "${i.rp.id}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X("User ID was not between 1 and 64 characters","TypeError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return t}class Vi{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const yt=new Vi;async function en(t){if(!Qr())throw new Error("WebAuthn is not supported in this browser");const e={publicKey:{...t,challenge:Yt(t.challenge),user:{...t.user,id:qi(t.user.id)},excludeCredentials:t.excludeCredentials.map(Xr)}};e.signal=yt.createNewAbortSignal();let r;try{r=await navigator.credentials.create(e)}catch(d){throw Gi({error:d,options:e})}finally{yt.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:o,type:s}=r,u={id:n,rawId:Ee(i),response:{attestationObject:Ee(o.attestationObject),clientDataJSON:Ee(o.clientDataJSON)},type:s,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof o.getTransports=="function"&&(u.transports=o.getTransports()),u}function Hi(t){return new TextDecoder("utf-8").decode(t)}async function Ki(){if(navigator.credentials.conditionalMediationSupported)return!0;const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable!==void 0&&t.isConditionalMediationAvailable()}function zi({error:t,options:e}){var r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal===new AbortController().signal)return new X("Authentication ceremony was sent an abort signal","AbortError")}else{if(t.name==="NotAllowedError")return!((r=n.allowCredentials)===null||r===void 0)&&r.length?new X("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new X("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(t.name==="SecurityError"){const i=window.location.hostname;if(Zr(i)){if(n.rpId!==i)return new X(`The RP ID "${n.rpId}" is invalid for this domain`,"SecurityError")}else return new X(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(t.name==="UnknownError")return new X("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return t}async function Yi(t,e=!1){var r,n;if(!Qr())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)===null||r===void 0?void 0:r.length)!==0&&(i=(n=t.allowCredentials)===null||n===void 0?void 0:n.map(Xr));const o={...t,challenge:Yt(t.challenge),allowCredentials:i},s={};if(e){if(!await Ki())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');s.mediation="conditional",o.allowCredentials=[]}s.publicKey=o,s.signal=yt.createNewAbortSignal();let u;try{u=await navigator.credentials.get(s)}catch(y){throw zi({error:y,options:s})}finally{yt.reset()}if(!u)throw new Error("Authentication was not completed");const{id:d,rawId:f,response:c,type:l}=u;let h;return c.userHandle&&(h=Hi(c.userHandle)),{id:d,rawId:Ee(f),response:{authenticatorData:Ee(c.authenticatorData),clientDataJSON:Ee(c.clientDataJSON),signature:Ee(c.signature),userHandle:h},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:u.authenticatorAttachment}}const mt=typeof window<"u",gt=new Map,Wi=t=>mt&&typeof localStorage<"u"?localStorage.getItem(t):gt.get(t)??null,Ji=(t,e)=>{mt&&typeof localStorage<"u"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?gt.set(t,e):gt.has(t)&>.delete(t)},tn=(t,e)=>{if(t==="localStorage"||t==="web")return Wi;if(t==="cookie")return r=>mt?Ft.get(r)??null:null;if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},rn=(t,e)=>{if(t==="localStorage"||t==="web")return Ji;if(t==="cookie")return(r,n)=>{mt&&(n?Ft.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Ft.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,o;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(o=e.remove)==null?void 0:o.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.deleteItemAsync)==null?void 0:o.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,o;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,o;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(o=e.removeItem)==null?void 0:o.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},He=t=>!t||!t.accessToken.value||!t.refreshToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ye=({accessToken:t,isError:e,user:r,error:n})=>e?{session:null,error:n}:r&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:"",user:r},error:null}:{session:null,error:null},wt=()=>typeof window<"u",nn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const o={method:e,headers:i};n&&(o.body=JSON.stringify(n));try{const s=await Gt(t,o);if(!s.ok){const u=await s.json();return Promise.reject({error:u})}try{return{data:await s.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const s={message:"Network Error",status:Ht,error:"network"};return Promise.reject({error:s})}},le=async(t,e,r)=>nn(t,"POST",{token:r,body:e}),on=(t,e)=>nn(t,"GET",{token:e}),Wt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const o=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(o)}`}).join("&");return r?`${t}?${r}`:t},ne=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),o=Object.fromEntries(new URLSearchParams(i.search)),s=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(s.search);let d=Object.fromEntries(u);r.startsWith("/")&&(d={...o,...d});let f=i.pathname;return s.pathname.length>1&&(f+=s.pathname.slice(1)),{...n,redirectTo:Wt(s.origin+f,d)}};function Ke(t,e){var r;if(!e){if(typeof window>"u")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function Jt(t){var e;if(typeof window>"u")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let o=window.location.pathname;Array.from(n).length&&(o+=`?${n.toString()}`),Array.from(i).length&&(o+=`#${i.toString()}`),window.history.pushState({},"",o)}}const de=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),Et=t=>!!t&&typeof t=="string"&&t.length>=$r,Qt=t=>!!t&&typeof t=="string",sn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),an=({backendUrl:t,clientUrl:e,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:o=!0,autoSignIn:s=!0})=>{const u=tn(r,n),d=rn(r,n),f=async(c,l,h)=>(await le(`${t}${c}`,l,h)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:vt,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:W("SIGNED_IN"),reportSignedOut:W("SIGNED_OUT"),reportTokenChanged:W("TOKEN_CHANGED"),incrementTokenImportAttempts:U({importTokenAttempts:({importTokenAttempts:c})=>c+1}),clearContext:U(()=>(d(Ge,null),d(qe,null),{...vt})),clearContextExceptRefreshToken:U(({refreshToken:{value:c}})=>(d(Ge,null),{...vt,refreshToken:{value:c}})),saveSession:U({user:(c,{data:l})=>{var h;return((h=l==null?void 0:l.session)==null?void 0:h.user)||null},accessToken:(c,{data:l})=>{if(l.session){const{accessTokenExpiresIn:h,accessToken:y}=l.session,v=new Date(Date.now()+h*1e3);return d(Ge,v.toISOString()),{value:y,expiresAt:v}}return d(Ge,null),{value:null,expiresAt:null}},refreshToken:(c,{data:l})=>{var h;const y=((h=l.session)==null?void 0:h.refreshToken)||null;return y&&d(qe,y),{value:y}}}),saveMfaTicket:U({mfa:(c,l)=>{var h;return(h=l.data)==null?void 0:h.mfa}}),resetTimer:U({refreshTimer:c=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:U({refreshTimer:(c,l)=>({startedAt:c.refreshTimer.startedAt,attempts:c.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:U({errors:({errors:c},{data:{error:l}})=>({...c,authentication:l})}),resetErrors:U({errors:c=>({}),importTokenAttempts:c=>0}),saveRegistrationError:U({errors:({errors:c},{data:{error:l}})=>({...c,registration:l})}),destroyRefreshToken:U({refreshToken:c=>(d(qe,null),{value:null})}),cleanUrl:()=>{s&&Ke("refreshToken")&&(Jt("refreshToken"),Jt("type"))},broadcastToken:c=>{if(s)try{new BroadcastChannel("nhost").postMessage(c.refreshToken.value)}catch{}}},guards:{isAnonymous:(c,l)=>{var h;return!!((h=c.user)!=null&&h.isAnonymous)},isSignedIn:c=>!!c.user&&!!c.refreshToken.value&&!!c.accessToken.value,noToken:c=>!c.refreshToken.value,hasRefreshToken:c=>!!c.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:c=>{const{expiresAt:l}=c.accessToken;return l?c.refreshTimer.lastAttempt?c.refreshTimer.attempts>Vt?!1:Date.now()-c.refreshTimer.lastAttempt.getTime()>Math.pow(2,c.refreshTimer.attempts-1)*5e3:i&&Date.now()-c.refreshTimer.startedAt.getTime()>i*1e3?!0:l.getTime()-Date.now()-1e3*Br<=0:!1},shouldRetryImportToken:(c,l)=>c.importTokenAttempts<Vt&&(l.data.error.status===Ht||l.data.error.status>=500),unverified:(c,{data:{error:l}})=>l.status===401&&(l.message==="Email is not verified"||l.error==="unverified-user"),hasSession:(c,l)=>{var h;return!!((h=l.data)!=null&&h.session)},hasMfaTicket:(c,l)=>{var h;return!!((h=l.data)!=null&&h.mfa)}},services:{signInPassword:(c,{email:l,password:h})=>de(l)?Et(h)?f("/signin/email-password",{email:l,password:h}):Promise.reject({error:pt}):Promise.reject({error:ue}),passwordlessSms:(c,{phoneNumber:l,options:h})=>{var y;return Qt(l)?(y=c.user)!=null&&y.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:l,options:ne(e,h)},c.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:l,options:ne(e,h)}):Promise.reject({error:zt})},passwordlessSmsOtp:(c,{phoneNumber:l,otp:h})=>Qt(l)?f("/signin/passwordless/sms/otp",{phoneNumber:l,otp:h}):Promise.reject({error:zt}),passwordlessEmail:(c,{email:l,options:h})=>{var y;return de(l)?(y=c.user)!=null&&y.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:l,options:ne(e,h)},c.accessToken.value):f("/signin/passwordless/email",{email:l,options:ne(e,h)}):Promise.reject({error:ue})},signInAnonymous:c=>f("/signin/anonymous"),signInMfaTotp:(c,l)=>{var h;const y=l.ticket||((h=c.mfa)==null?void 0:h.ticket);return y?sn(y)?f("/signin/mfa/totp",{ticket:y,otp:l.otp}):Promise.reject({error:Gr}):Promise.reject({error:Vr})},signInSecurityKeyEmail:async(c,{email:l})=>{if(!de(l))throw new Ve(ue);const h=await f("/signin/webauthn",{email:l});let y;try{y=await Yi(h)}catch(v){throw new Ve(v)}return f("/signin/webauthn/verify",{email:l,credential:y})},refreshToken:async(c,l)=>{const h=l.type==="TRY_TOKEN"?l.token:c.refreshToken.value;return{session:await f("/token",{refreshToken:h}),error:null}},signout:(c,l)=>f("/signout",{refreshToken:c.refreshToken.value,all:!!l.all}),signUpEmailPassword:async(c,{email:l,password:h,options:y})=>{var v;return de(l)?Et(h)?(v=c.user)!=null&&v.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:l,password:h,options:ne(e,y)},c.accessToken.value):f("/signup/email-password",{email:l,password:h,options:ne(e,y)}):Promise.reject({error:pt}):Promise.reject({error:ue})},signUpSecurityKey:async(c,{email:l,options:h})=>{if(!de(l))return Promise.reject({error:ue});const y=h==null?void 0:h.nickname;y&&delete h.nickname;const v=await f("/signup/webauthn",{email:l,options:h});let w;try{w=await en(v)}catch(T){throw new Ve(T)}return f("/signup/webauthn/verify",{credential:w,options:{redirectTo:h==null?void 0:h.redirectTo,nickname:y}})},importRefreshToken:async c=>{if(c.user&&c.refreshToken.value&&c.accessToken.value&&c.accessToken.expiresAt)return{session:{accessToken:c.accessToken.value,accessTokenExpiresIn:c.accessToken.expiresAt.getTime()-Date.now(),refreshToken:c.refreshToken.value,user:c.user},error:null};let l=null;if(s){const y=Ke("refreshToken")||null;if(y)try{return{session:await f("/token",{refreshToken:y}),error:null}}catch(v){l=v.error}else{const v=Ke("error");if(v)return Promise.reject({session:null,error:{status:re,error:v,message:Ke("errorDescription")||v}})}}const h=await u(qe);if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(y){l=y.error}return l?Promise.reject({error:l,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:c})=>Math.pow(2,c-1)*5e3}})},cn=({backendUrl:t,clientUrl:e,interpreter:r})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changeEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:n=>ue}),saveRequestError:U({error:(n,{data:{error:i}})=>i}),reportError:W(n=>({type:"ERROR",error:n.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!de(i)},services:{requestChange:async(n,{email:i,options:o})=>(await le(`${t}/user/email/change`,{newEmail:i,options:ne(e,o)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),un=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidPassword",actions:"saveInvalidPasswordError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidPasswordError:U({error:r=>pt}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!Et(n)},services:{requestChange:(r,{password:n,ticket:i})=>le(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Qi=({backendUrl:t,interpreter:e})=>ve({schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,id:"enableMfa",initial:"idle",context:{error:null,imageUrl:null,secret:null},states:{idle:{initial:"initial",on:{GENERATE:"generating"},states:{initial:{},error:{}}},generating:{invoke:{src:"generate",id:"generate",onDone:{target:"generated",actions:["reportGeneratedSuccess","saveGeneration"]},onError:{actions:["saveError","reportGeneratedError"],target:"idle.error"}}},generated:{initial:"idle",states:{idle:{initial:"idle",on:{ACTIVATE:[{cond:"invalidMfaType",actions:"saveInvalidMfaTypeError",target:".error"},{cond:"invalidMfaCode",actions:"saveInvalidMfaCodeError",target:".error"},{target:"activating"}]},states:{idle:{},error:{}}},activating:{invoke:{src:"activate",id:"activate",onDone:{target:"activated",actions:"reportSuccess"},onError:{actions:["saveError","reportError"],target:"idle.error"}}},activated:{type:"final"}}}}},{actions:{saveInvalidMfaTypeError:U({error:r=>Fr}),saveInvalidMfaCodeError:U({error:r=>qr}),saveError:U({error:(r,{data:{error:n}})=>n}),saveGeneration:U({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:W((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS"),reportGeneratedSuccess:W("GENERATED"),reportGeneratedError:W(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await on(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>le(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ln=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"changePassword",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"requestChange",id:"requestChange",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{requestChange:(r,{email:n,options:i})=>le(`${t}/user/password/reset`,{email:n,options:ne(e,i)})}}),dn=({backendUrl:t,clientUrl:e})=>ve({schema:{context:{},events:{},services:{}},tsTypes:{},predictableActionArguments:!0,id:"sendVerificationEmail",initial:"idle",context:{error:null},states:{idle:{on:{REQUEST:[{cond:"invalidEmail",actions:"saveInvalidEmailError",target:".error"},{target:"requesting"}]},initial:"initial",states:{initial:{},success:{},error:{}}},requesting:{invoke:{src:"request",id:"request",onDone:{target:"idle.success",actions:"reportSuccess"},onError:{actions:["saveRequestError","reportError"],target:"idle.error"}}}}},{actions:{saveInvalidEmailError:U({error:r=>ue}),saveRequestError:U({error:(r,{data:{error:n}})=>n}),reportError:W(r=>({type:"ERROR",error:r.error})),reportSuccess:W("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!de(n)},services:{request:async(r,{email:n,options:i})=>(await le(`${t}/user/email/send-verification-email`,{email:n,options:ne(e,i)})).data}});let Xt=class{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:o,clientUrl:s,devTools:u,...d}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=o,this.clientUrl=s,this._machine=an({...d,backendUrl:o,clientUrl:s,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window<"u"&&r)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var c;const l=(c=this.interpreter)==null?void 0:c.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==l&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){const i={...this.machine.context};r&&(i.user=r.user,i.refreshToken.value=r.refreshToken??null,i.accessToken.value=r.accessToken??null,i.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const o=this.machine.withContext(i);this._interpreter||(this._interpreter=n||xe(o,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(s=>s())),this._interpreter.start(o.initialState),this._subscriptionsQueue.forEach(s=>s(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}};class hn extends Xt{constructor({...e}){super({...e,autoSignIn:wt()&&e.autoSignIn,autoRefreshToken:wt()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xi=hn,fn=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await le("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await en(n)}catch(s){throw new Ve(s)}const{data:o}=await le(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:o,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},pn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),vn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),Zi=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),eo=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),yn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),mn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),gn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null})})}),wn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:s.context.mfa,user:null}):s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.context.user})})}),Zt=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({error:o.context.errors.registration||null,isError:!0,isSuccess:!1}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),En=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,error:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:"signedIn"})&&r({accessToken:o.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Sn=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:o.accessToken.value,error:se,isError:!0,isSuccess:!1,user:o.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):s.matches({authentication:"signedIn"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:s.context.user})})}),er=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(o=>{o.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):o.matches("registration.incomplete.failed")&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Tn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null});t.onTransition(o=>{o.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:o.context.user,accessToken:o.context.accessToken.value}):o.matches({registration:{incomplete:"failed"}})&&n({error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),bn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:zr});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),tr=(t,e,r,n)=>new Promise(i=>{const{changed:o,context:s}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!o)return i({error:se,accessToken:s.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),An=(t,e,r)=>new Promise(n=>{const{changed:i,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:se,accessToken:o.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({accessToken:null,error:s.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:s.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})});class On{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:o,refreshIntervalTime:s,start:u=!0}){var d;this.url=e,this._client=new Xt({backendUrl:e,clientUrl:typeof window<"u"&&((d=window.location)==null?void 0:d.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:o,refreshIntervalTime:s})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ye(await An(r,n,i)):ye(await tr(r,n,e.password,i))}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await gn(r);return{...ye(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,o=Wt(`${this._client.backendUrl}/signin/provider/${n}`,ne(this._client.clientUrl,i));return wt()&&(window.location.href=o),{providerUrl:o,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await wn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:Yr}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ye(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await En(r,e.email);return{...ye(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:o}=await Zt(r,n,i);return{session:null,mfa:null,error:o}}if("phoneNumber"in e&&"otp"in e){const n=await Tn(r,e.phoneNumber,e.otp);return{...ye(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Sn(r,e.otp,e.ticket);return{...ye(n),mfa:null}}return{error:Jr,mfa:null,session:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await bn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(ln(this._client)).start(),{error:i}=await yn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(un(this._client)).start(),{error:i}=await vn(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(dn(this._client)).start(),{error:i}=await mn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(cn(this._client)).start(),{error:i}=await pn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await Zt(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await er(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await tr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await fn(this._client,e);return{error:r,key:n}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{i.type==="TOKEN_CHANGED"&&e(He(o))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:o})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,He(o))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Bn(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:Hr});const{changed:o}=r.send("TRY_TOKEN",{token:i});if(!o)return n({session:null,error:Kr});r.onTransition(s=>{s.matches({token:{idle:"error"}})?n({session:null,error:Wr}):s.event.type==="TOKEN_CHANGED"&&n({session:He(s.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return He((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);e.onTransition(o=>{if(!o.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var kn=typeof self=="object"?self.FormData:window.FormData,to=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var rr={exports:{}};(function(t,e){var r=typeof self<"u"?self:to,n=function(){function o(){this.fetch=!1,this.DOMException=r.DOMException}return o.prototype=r,new o}();(function(o){(function(s){var u={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function d(a){return a&&DataView.prototype.isPrototypeOf(a)}if(u.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(a){return a&&f.indexOf(Object.prototype.toString.call(a))>-1};function l(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(a))throw new TypeError("Invalid character in header field name");return a.toLowerCase()}function h(a){return typeof a!="string"&&(a=String(a)),a}function y(a){var p={next:function(){var E=a.shift();return{done:E===void 0,value:E}}};return u.iterable&&(p[Symbol.iterator]=function(){return p}),p}function v(a){this.map={},a instanceof v?a.forEach(function(p,E){this.append(E,p)},this):Array.isArray(a)?a.forEach(function(p){this.append(p[0],p[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(p){this.append(p,a[p])},this)}v.prototype.append=function(a,p){a=l(a),p=h(p);var E=this.map[a];this.map[a]=E?E+", "+p:p},v.prototype.delete=function(a){delete this.map[l(a)]},v.prototype.get=function(a){return a=l(a),this.has(a)?this.map[a]:null},v.prototype.has=function(a){return this.map.hasOwnProperty(l(a))},v.prototype.set=function(a,p){this.map[l(a)]=h(p)},v.prototype.forEach=function(a,p){for(var E in this.map)this.map.hasOwnProperty(E)&&a.call(p,this.map[E],E,this)},v.prototype.keys=function(){var a=[];return this.forEach(function(p,E){a.push(E)}),y(a)},v.prototype.values=function(){var a=[];return this.forEach(function(p){a.push(p)}),y(a)},v.prototype.entries=function(){var a=[];return this.forEach(function(p,E){a.push([E,p])}),y(a)},u.iterable&&(v.prototype[Symbol.iterator]=v.prototype.entries);function w(a){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}function T(a){return new Promise(function(p,E){a.onload=function(){p(a.result)},a.onerror=function(){E(a.error)}})}function O(a){var p=new FileReader,E=T(p);return p.readAsArrayBuffer(a),E}function S(a){var p=new FileReader,E=T(p);return p.readAsText(a),E}function A(a){for(var p=new Uint8Array(a),E=new Array(p.length),C=0;C<p.length;C++)E[C]=String.fromCharCode(p[C]);return E.join("")}function N(a){if(a.slice)return a.slice(0);var p=new Uint8Array(a.byteLength);return p.set(new Uint8Array(a)),p.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(a){this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:u.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:u.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():u.arrayBuffer&&u.blob&&d(a)?(this._bodyArrayBuffer=N(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):u.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||c(a))?this._bodyArrayBuffer=N(a):this._bodyText=a=Object.prototype.toString.call(a):this._bodyText="",this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):u.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},u.blob&&(this.blob=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?w(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(O)}),this.text=function(){var a=w(this);if(a)return a;if(this._bodyBlob)return S(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(A(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},u.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var q=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function P(a){var p=a.toUpperCase();return q.indexOf(p)>-1?p:a}function I(a,p){p=p||{};var E=p.body;if(a instanceof I){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,p.headers||(this.headers=new v(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!E&&a._bodyInit!=null&&(E=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=p.credentials||this.credentials||"same-origin",(p.headers||!this.headers)&&(this.headers=new v(p.headers)),this.method=P(p.method||this.method||"GET"),this.mode=p.mode||this.mode||null,this.signal=p.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&E)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(E)}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function j(a){var p=new FormData;return a.trim().split("&").forEach(function(E){if(E){var C=E.split("="),_=C.shift().replace(/\+/g," "),b=C.join("=").replace(/\+/g," ");p.append(decodeURIComponent(_),decodeURIComponent(b))}}),p}function k(a){var p=new v,E=a.replace(/\r?\n[\t ]+/g," ");return E.split(/\r?\n/).forEach(function(C){var _=C.split(":"),b=_.shift().trim();if(b){var ee=_.join(":").trim();p.append(b,ee)}}),p}R.call(I.prototype);function x(a,p){p||(p={}),this.type="default",this.status=p.status===void 0?200:p.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in p?p.statusText:"OK",this.headers=new v(p.headers),this.url=p.url||"",this._initBody(a)}R.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new v(this.headers),url:this.url})},x.error=function(){var a=new x(null,{status:0,statusText:""});return a.type="error",a};var J=[301,302,303,307,308];x.redirect=function(a,p){if(J.indexOf(p)===-1)throw new RangeError("Invalid status code");return new x(null,{status:p,headers:{location:a}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(a,p){this.message=a,this.name=p;var E=Error(a);this.stack=E.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function K(a,p){return new Promise(function(E,C){var _=new I(a,p);if(_.signal&&_.signal.aborted)return C(new s.DOMException("Aborted","AbortError"));var b=new XMLHttpRequest;function ee(){b.abort()}b.onload=function(){var H={status:b.status,statusText:b.statusText,headers:k(b.getAllResponseHeaders()||"")};H.url="responseURL"in b?b.responseURL:H.headers.get("X-Request-URL");var he="response"in b?b.response:b.responseText;E(new x(he,H))},b.onerror=function(){C(new TypeError("Network request failed"))},b.ontimeout=function(){C(new TypeError("Network request failed"))},b.onabort=function(){C(new s.DOMException("Aborted","AbortError"))},b.open(_.method,_.url,!0),_.credentials==="include"?b.withCredentials=!0:_.credentials==="omit"&&(b.withCredentials=!1),"responseType"in b&&u.blob&&(b.responseType="blob"),_.headers.forEach(function(H,he){b.setRequestHeader(he,H)}),_.signal&&(_.signal.addEventListener("abort",ee),b.onreadystatechange=function(){b.readyState===4&&_.signal.removeEventListener("abort",ee)}),b.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=v,o.Request=I,o.Response=x),s.Headers=v,s.Request=I,s.Response=x,s.fetch=K,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=n;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e})(rr,rr.exports);const nr=ro(rr.exports),no=t=>{try{return btoa(t),t}catch{return encodeURIComponent(t)}},xn=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:o,adminSecret:s,onUploadProgress:u}={})=>{const d={};i&&(d["x-nhost-file-id"]=i),o&&(d["x-nhost-bucket-id"]=o),n&&(d["x-nhost-file-name"]=no(n)),s&&(d["x-hasura-admin-secret"]=s),r&&(d.Authorization=`Bearer ${r}`);const f=`${t}/files`;if(typeof XMLHttpRequest>"u")try{const c=await nr(f,{method:"POST",headers:d,body:e});return c.ok?{fileMetadata:await c.json(),error:null}:{error:{status:c.status,message:await c.text(),error:c.statusText},fileMetadata:null}}catch(c){return{error:{status:0,message:c.message,error:c.message},fileMetadata:null}}return new Promise(c=>{let l=new XMLHttpRequest;l.responseType="json",l.onload=()=>l.status<200&&l.status>=300?c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}):c({fileMetadata:l.response,error:null}),l.onerror=()=>c({fileMetadata:null,error:{error:l.statusText,message:l.statusText,status:l.status}}),u&&l.upload.addEventListener("progress",u,!1),l.open("POST",f,!0),Object.entries(d).forEach(([h,y])=>{l.setRequestHeader(h,y)}),l.send(e)})};class In{constructor({url:e}){this.url=e}async upload(e){const{formData:r}=e;return xn(this.url,r,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:e.bucketId,fileId:e.id,name:e.name})}async getPresignedUrl(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{presignedUrl:await n.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r}=e,n=await nr(`${this.url}/files/${r}`,{method:"DELETE",headers:this.generateAuthHeaders()});if(!n.ok)throw new Error(await n.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}const Rn=(t,e)=>{const r=Object.entries(e).map(([n,i])=>`${Array.from(n)[0]}=${i}`).join("&");return r?`${t}?${r}`:t};class Pn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new In({url:e}),this.setAdminSecret(r)}async upload(e){let r;return"file"in e?(r=new kn,r.append("file",e.file)):r=e.formData,this.api.upload({...e,formData:r})}getPublicUrl(e){const{fileId:r,...n}=e;return Rn(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{presignedUrl:r,error:n}=await this.api.getPresignedUrl(e);return n?{presignedUrl:null,error:n}:r?{presignedUrl:r,error:null}:{presignedUrl:null,error:new Error("Invalid file id")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}}const St={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},_n=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...St},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:U({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:U({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:U({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:U({progress:t=>null,loaded:t=>0}),resetContext:U(t=>St),addFile:U({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new kn;i.append("file",n);let o=0;return xn(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:s=>{const u=s.total?Math.round(s.loaded*n.size/s.total):0,d=u-o;o=u,r({type:"UPLOAD_PROGRESS",progress:s.total?Math.round(u*100/s.total):0,loaded:u,additions:d})}}).then(({fileMetadata:s,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),s){const{id:d,bucketId:f}=s;r({type:"UPLOAD_DONE",id:d,bucketId:f})}}),()=>{}}}}),{pure:ir,sendParent:Tt}=vi,io=()=>ve({id:"files-list",schema:{context:{},events:{}},tsTypes:{},predictableActionArguments:!0,context:{progress:null,files:[],loaded:0,total:0},initial:"idle",on:{UPLOAD:{cond:"hasFileToDownload",actions:"addItem",target:"uploading"},ADD:{actions:"addItem"},REMOVE:{actions:"removeItem"}},states:{idle:{entry:["resetProgress","resetLoaded","resetTotal"],on:{CLEAR:{actions:"clearList",target:"idle"}}},uploading:{entry:["upload","startProgress","resetLoaded","resetTotal"],on:{UPLOAD_PROGRESS:{actions:["incrementProgress"]},UPLOAD_DONE:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],UPLOAD_ERROR:[{cond:"isAllUploaded",target:"uploaded"},{cond:"isAllUploadedOrError",target:"error"}],CANCEL:{actions:"cancel",target:"idle"}}},uploaded:{entry:"setUploaded",on:{CLEAR:{actions:"clearList",target:"idle"}}},error:{on:{CLEAR:{actions:"clearList",target:"idle"}}}}},{guards:{hasFileToDownload:(t,e)=>t.files.some(r=>r.getSnapshot().matches("idle"))||!!e.files,isAllUploaded:t=>t.files.every(e=>{var r;return(r=e.getSnapshot())==null?void 0:r.matches("uploaded")}),isAllUploadedOrError:t=>t.files.every(e=>{const r=e.getSnapshot();return(r==null?void 0:r.matches("error"))||(r==null?void 0:r.matches("uploaded"))})},actions:{incrementProgress:U((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:U({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:U({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:U({loaded:t=>0}),startProgress:U({progress:t=>0}),resetProgress:U({progress:t=>null}),addItem:U((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"length"in e?Array.from(e):[e]:[],i=t.total+n.reduce((s,u)=>s+u.size,0),o=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(s=>Di(_n().withConfig({actions:{sendProgress:Tt((u,{additions:d})=>({type:"UPLOAD_PROGRESS",additions:d})),sendDone:Tt("UPLOAD_DONE"),sendError:Tt("UPLOAD_ERROR"),sendDestroy:Tt("REMOVE")}}).withContext({...St,file:s,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:o}}),removeItem:U({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:ir(t=>t.files.map(e=>W({type:"DESTROY"},{to:e.id}))),upload:ir((t,e)=>t.files.map(r=>W(e,{to:r.id}))),cancel:ir(t=>t.files.map(e=>W({type:"CANCEL"},{to:e.id})))}}),oo=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),so=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var o;return(o=i.getSnapshot())==null?void 0:o.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ao=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function bt(t,e){const{backendUrl:r,subdomain:n,region:i}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const o=n.match(ao);if(o!=null&&o.groups){const{protocol:s="http",host:u,port:d=1337}=o.groups,f=lo(e);return f||`${s}://${u}:${d}/v1/${e}`}if(!i)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${i}.nhost.run/v1`}function co(){return typeof window<"u"}function uo(){return typeof process<"u"&&process.env}function lo(t){return co()||!uo()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function Un(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new On({url:e,...t})}function Dn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Nn({url:e,...t})}class Nn{constructor(e){const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};try{const o=await Gt(e,{body:JSON.stringify(r),headers:i,method:"POST"});if(!o.ok)throw new Error(o.statusText);let s;try{s=await o.json()}catch{s=await o.text()}return{res:{data:s,status:o.status,statusText:o.statusText},error:null}}catch(o){const s=o;return{res:null,error:{message:s.message,status:s.name==="AbortError"?0:500,error:s.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ho(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function Cn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function fo(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Cn(n)}catch{}return{query:t,operationName:r}}const e=Cn(t);return{query:Se.print(t),operationName:e}}class po{constructor(e){const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,o=ho(e,n,i),{headers:s,...u}=i||{},{query:d,operationName:f}=fo(o.document);try{const c=await Gt(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:f,query:d,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s},...u});if(!c.ok)return{data:null,error:{error:c.statusText,message:c.statusText,status:c.status}};const{data:l,errors:h}=await c.json();return h?{data:null,error:h}:typeof l!="object"||Array.isArray(l)||l===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:l,error:null}}catch(c){const l=c;return{data:null,error:{message:l.message,status:l.name==="AbortError"?0:500,error:l.name==="AbortError"?"abort-error":"unknown"}}}}get httpUrl(){return this._url}get wsUrl(){return this._url.replace(/^(http)(s?):\/\//,"ws$2://")}get url(){return this._url}getUrl(){return this._url}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Mn(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new po({url:e,...t})}function Ln(t){const e="subdomain"in t||"backendUrl"in t?bt(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Pn({url:e,...t})}const vo=t=>new jn(t);class jn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,adminSecret:s,devTools:u,start:d=!0,...f}){this.auth=Un({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:o,start:d,...f}),this.storage=Ln({adminSecret:s,...f}),this.functions=Dn({adminSecret:s,...f}),this.graphql=Mn({adminSecret:s,...f}),this.auth.onAuthStateChanged((c,l)=>{c==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(c=>{const l=c==null?void 0:c.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=s,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}g.AuthClient=Xt,g.AuthClientSSR=Xi,g.AuthCookieClient=hn,g.CodifiedError=Ve,g.EMAIL_NEEDS_VERIFICATION=Yr,g.HasuraAuthClient=On,g.HasuraStorageApi=In,g.HasuraStorageClient=Pn,g.INITIAL_FILE_CONTEXT=St,g.INITIAL_MACHINE_CONTEXT=vt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=qr,g.INVALID_MFA_TICKET_ERROR=Gr,g.INVALID_MFA_TYPE_ERROR=Fr,g.INVALID_PASSWORD_ERROR=pt,g.INVALID_PHONE_NUMBER_ERROR=zt,g.INVALID_REFRESH_TOKEN=Wr,g.INVALID_SIGN_IN_METHOD=Jr,g.MIN_PASSWORD_LENGTH=$r,g.NETWORK_ERROR_CODE=Ht,g.NHOST_JWT_EXPIRES_AT_KEY=Ge,g.NHOST_REFRESH_TOKEN_KEY=qe,g.NO_MFA_TICKET_ERROR=Vr,g.NO_REFRESH_TOKEN=Hr,g.NhostClient=jn,g.NhostFunctionsClient=Nn,g.OTHER_ERROR_CODE=Kt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Vt,g.STATE_ERROR_CODE=_e,g.TOKEN_REFRESHER_RUNNING_ERROR=Kr,g.TOKEN_REFRESH_MARGIN=Br,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=Fi,g.USER_UNAUTHENTICATED=zr,g.VALIDATION_ERROR_CODE=re,g.activateMfaPromise=eo,g.addSecurityKeyPromise=fn,g.appendImageTransformationParameters=Rn,g.changeEmailPromise=pn,g.changePasswordPromise=vn,g.createAuthClient=Un,g.createAuthMachine=an,g.createChangeEmailMachine=cn,g.createChangePasswordMachine=un,g.createEnableMfaMachine=Qi,g.createFileUploadMachine=_n,g.createFunctionsClient=Dn,g.createGraphqlClient=Mn,g.createMultipleFilesUploadMachine=io,g.createNhostClient=vo,g.createResetPasswordMachine=ln,g.createSendVerificationEmailMachine=dn,g.createStorageClient=Ln,g.encodeQueryParameters=Wt,g.generateQrCodePromise=Zi,g.getAuthenticationResult=ye,g.getFetch=on,g.getParameterByName=Ke,g.getSession=He,g.isBrowser=wt,g.isValidEmail=de,g.isValidPassword=Et,g.isValidPhoneNumber=Qt,g.isValidTicket=sn,g.localStorageGetter=tn,g.localStorageSetter=rn,g.postFetch=le,g.removeParameterFromWindow=Jt,g.resetPasswordPromise=yn,g.rewriteRedirectTo=ne,g.sendVerificationEmailPromise=mn,g.signInAnonymousPromise=gn,g.signInEmailPasswordPromise=wn,g.signInEmailPasswordlessPromise=Zt,g.signInEmailSecurityKeyPromise=En,g.signInMfaTotpPromise=Sn,g.signInSmsPasswordlessOtpPromise=Tn,g.signInSmsPasswordlessPromise=er,g.signOutPromise=bn,g.signUpEmailPasswordPromise=tr,g.signUpEmailSecurityKeyPromise=An,g.uploadFilePromise=oo,g.uploadMultipleFilesPromise=so,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
20
20
|
//# sourceMappingURL=nhost-js.umd.js.map
|