@nhost/nhost-js 3.2.4 → 3.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +24 -24
- package/dist/index.esm.js.map +1 -1
- package/package.json +2 -2
- package/umd/nhost-js.umd.js +7 -7
- package/umd/nhost-js.umd.js.map +1 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
12
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
13
|
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},m.apply(this,arguments)};function _t(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function x(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function P(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function q(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var j;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(j||(j={}));var fe;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(fe||(fe={}));var et=j.Start,tt=j.Stop,be=j.Raise,Le=j.Send,Pt=j.Cancel,vr=j.NullEvent,rt=j.Assign,oi=j.After,ai=j.DoneState,nt=j.Log,yr=j.Init,it=j.Invoke,ci=j.ErrorExecution,Nt=j.ErrorPlatform,Ut=j.ErrorCustom,st=j.Update,gr=j.Choose,mr=j.Pure;const ui=Object.freeze(Object.defineProperty({__proto__:null,after:oi,assign:rt,cancel:Pt,choose:gr,doneState:ai,error:Ut,errorExecution:ci,errorPlatform:Nt,init:yr,invoke:it,log:nt,nullEvent:vr,pure:mr,raise:be,send:Le,start:et,stop:tt,update:st},Symbol.toStringTag,{value:"Module"}));var Er=".",wr={},Dt="xstate.guard",li="",K=process.env.NODE_ENV==="production",ot;function Ct(t,e,r){r===void 0&&(r=Er);var n=je(t,r),i=je(e,r);return U(i)?U(n)?i===n:!1:U(n)?n in i:Object.keys(n).every(function(s){return s in i?Ct(n[s],i[s]):!1})}function Tr(t){try{return U(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Mt(t,e){try{return ke(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function di(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function je(t,e){if(di(t))return t.value;if(ke(t))return at(t);if(typeof t!="string")return t;var r=Mt(t,e);return at(r)}function at(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function $e(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function Sr(t,e,r){var n,i,s={};try{for(var o=x(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,d=t[c];r(d)&&(s[c]=e(d,c,t))}}catch(h){n={error:h}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var hi=function(t){return function(e){var r,n,i=e;try{for(var s=x(t),o=s.next();!o.done;o=s.next()){var u=o.value;i=i[u]}}catch(c){r={error:c}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function fi(t,e){return function(r){var n,i,s=r;try{for(var o=x(t),u=o.next();!u.done;u=o.next()){var c=u.value;s=s[e][c]}}catch(d){n={error:d}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function ct(t){if(!t)return[[]];if(U(t))return[[t]];var e=G(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:ct(t[r]).map(function(i){return[r].concat(i)})}));return e}function G(t){var e;return(e=[]).concat.apply(e,q([],P(t),!1))}function br(t){return ke(t)?t:[t]}function se(t){return t===void 0?[]:br(t)}function ut(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=x(Object.keys(t)),u=o.next();!u.done;u=o.next()){var c=u.value,d=t[c];N(d)?s[c]=d(e,r.data):s[c]=d}}catch(h){n={error:h}}finally{try{u&&!u.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function pi(t){return/^(done|error)\./.test(t)}function kr(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function vi(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function yi(t,e){var r,n,i=P([[],[]],2),s=i[0],o=i[1];try{for(var u=x(t),c=u.next();!c.done;c=u.next()){var d=c.value;e(d)?s.push(d):o.push(d)}}catch(h){r={error:h}}finally{try{c&&!c.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}return[s,o]}function Ar(t,e){return $e(t.states,function(r,n){if(r){var i=(U(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:Ar(r,i)}}})}function gi(t,e){return{current:e,states:Ar(t,e)}}function Or(t,e,r,n){K||J(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var u,c,d=o.assignment,h={state:n,action:o,_event:e},l={};if(N(d))l=d(s,e.data,h);else try{for(var a=x(Object.keys(d)),f=a.next();!f.done;f=a.next()){var v=f.value,y=d[v];l[v]=N(y)?y(s,e.data,h):y}}catch(S){u={error:S}}finally{try{f&&!f.done&&(c=a.return)&&c.call(a)}finally{if(u)throw u.error}}return Object.assign({},s,l)},t);return i}var J=function(){};K||(J=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function ke(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function U(t){return typeof t=="string"}function Ir(t,e){if(t)return U(t)?{type:Dt,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Dt,name:t.name,predicate:t}:t}function mi(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var pe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();ot={},ot[pe]=function(){return this},ot[Symbol.observable]=function(){return this};function le(t){return!!t&&"__xstatenode"in t}function Ei(t){return!!t&&typeof t.send=="function"}var wi=function(){var t=0;return function(){return t++,t.toString(16)}}();function lt(t,e){return U(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!U(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=lt(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function Ae(t,e){var r=br(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||le(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function Ti(t){if(!(t===void 0||t===li))return se(t)}function Si(t,e,r){if(!K){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function Rr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Dt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var u=s==null?void 0:s[e.type];if(!u)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return u(r,n.data,o)}function xr(t){return typeof t=="string"?{type:t}:t}function dt(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function ht(t,e){return"".concat(t,":invocation[").concat(e,"]")}function Lt(t){return(t.type===be||t.type===Le&&t.to===fe.Internal)&&typeof t.delay!="number"}var ge=Q({type:yr});function ft(t,e){return e&&e[t]||void 0}function Oe(t,e){var r;if(U(t)||typeof t=="number"){var n=ft(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=ft(t.type,e);if(N(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var de=function(t,e){if(!t)return[];var r=ke(t)?t:[t];return r.map(function(n){return Oe(n,e)})};function pt(t){var e=Oe(t);return m(m({id:U(t)?t:e.id},e),{type:e.type})}function _r(t,e){return{type:be,event:typeof t=="function"?t:lt(t),delay:e?e.delay:void 0,id:e==null?void 0:e.id}}function Pr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;return m(m({},t),{type:be,_event:s,delay:o})}function me(t,e){return{to:e?e.to:void 0,type:Le,event:N(t)?t:lt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:Tr(t)}}function Nr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var u=n&&n[t.delay];o=N(u)?u(e,r.data,i):u}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var c=N(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:c,_event:s,event:s.data,delay:o})}function jt(t,e){return me(t,m(m({},e),{to:fe.Parent}))}function bi(t,e,r){return me(e,m(m({},r),{to:t}))}function ki(){return jt(st)}function Ai(t,e){return me(t,m(m({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var Oi=function(t,e){return{context:t,event:e}};function Ii(t,e){return t===void 0&&(t=Oi),{type:nt,label:e,expr:t}}var Ur=function(t,e,r){return m(m({},t),{value:U(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Dr=function(t){return{type:Pt,sendId:t}};function Cr(t){var e=pt(t);return{type:j.Start,activity:e,exec:void 0}}function Mr(t){var e=N(t)?t:pt(t);return{type:j.Stop,activity:e,exec:void 0}}function Lr(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:j.Stop,activity:i};return s}var jr=function(t){return{type:rt,assignment:t}};function Ri(t){return typeof t=="object"&&"type"in t}function $r(t,e){var r=e?"#".concat(e):"";return"".concat(j.After,"(").concat(t,")").concat(r)}function Fe(t,e){var r="".concat(j.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function He(t,e){var r="".concat(j.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Ie(t,e){var r="".concat(j.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function xi(t){return{type:j.Pure,get:t}}function _i(t,e){if(!K&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var s=typeof r=="function"?r.apply(void 0,q([],P(n),!1)):r;if(!s)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return s}}return me(function(n,i){return i},m(m({},e),{to:t}))}function Pi(t,e){return jt(function(r,n,i){return{type:Ut,data:N(t)?t(r,n,i):t}},m(m({},e),{to:fe.Parent}))}function Ni(t){return{type:j.Choose,conds:t}}var Ui=function(t){var e,r,n=[];try{for(var i=x(t),s=i.next();!s.done;s=i.next())for(var o=s.value,u=0;u<o.actions.length;){if(o.actions[u].type===rt){n.push(o.actions[u]),o.actions.splice(u,1);continue}u++}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function qe(t,e,r,n,i,s,o){o===void 0&&(o=!1);var u=o?[]:Ui(i),c=u.length?Or(r,n,u,e):r,d=o?[r]:void 0,h=[];function l(v,y){var S;switch(y.type){case be:{var w=Pr(y,c,n,t.options.delays);return s&&typeof w.delay=="number"&&s(w,c,n),w}case Le:var T=Nr(y,c,n,t.options.delays);if(!K){var b=y.delay;J(!U(b)||typeof T.delay=="number","No delay reference for delay expression '".concat(b,"' was found on machine '").concat(t.id,"'"))}return s&&T.to!==fe.Internal&&(v==="entry"?h.push(T):s(T,c,n)),T;case nt:{var O=Ur(y,c,n);return s==null||s(O,c,n),O}case gr:{var M=y,D=(S=M.conds.find(function(p){var E=Ir(p.cond,t.options.guards);return!E||Rr(t,E,c,n,s?void 0:e)}))===null||S===void 0?void 0:S.actions;if(!D)return[];var _=P(qe(t,e,c,n,[{type:v,actions:de(se(D),t.options.actions)}],s,o),2),$=_[0],R=_[1];return c=R,d==null||d.push(c),$}case mr:{var D=y.get(c,n.data);if(!D)return[];var B=P(qe(t,e,c,n,[{type:v,actions:de(se(D),t.options.actions)}],s,o),2),A=B[0],F=B[1];return c=F,d==null||d.push(c),A}case tt:{var O=Lr(y,c,n);return s==null||s(O,r,n),O}case rt:{c=Or(c,n,[y],s?void 0:e),d==null||d.push(c);break}default:var z=Oe(y,t.options.actions),V=z.exec;if(s)s(z,c,n);else if(V&&d){var we=d.length-1,Te=m(m({},z),{exec:function(p){for(var E=[],k=1;k<arguments.length;k++)E[k-1]=arguments[k];V.apply(void 0,q([d[we]],P(E),!1))}});z=Te}return z}}function a(v){var y,S,w=[];try{for(var T=x(v.actions),b=T.next();!b.done;b=T.next()){var O=b.value,M=l(v.type,O);M&&(w=w.concat(M))}}catch(D){y={error:D}}finally{try{b&&!b.done&&(S=T.return)&&S.call(T)}finally{if(y)throw y.error}}return h.forEach(function(D){s(D,c,n)}),h.length=0,w}var f=G(i.map(a));return[f,c]}const Di=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:ui,after:$r,assign:jr,cancel:Dr,choose:Ni,done:Fe,doneInvoke:He,error:Ie,escalate:Pi,forwardTo:_i,getActionFunction:ft,initEvent:ge,isActionObject:Ri,log:Ii,pure:xi,raise:_r,resolveActions:qe,resolveLog:Ur,resolveRaise:Pr,resolveSend:Nr,resolveStop:Lr,respond:Ai,send:me,sendParent:jt,sendTo:bi,sendUpdate:ki,start:Cr,stop:Mr,toActionObject:Oe,toActionObjects:de,toActivityDefinition:pt},Symbol.toStringTag,{value:"Module"}));var vt=[],Re=function(t,e){vt.push(t);var r=e(t);return vt.pop(),r},Ci=function(t){return t(vt[vt.length-1])};function Fr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[pe]=function(){return this},e}function Mi(t,e,r,n){var i,s=xr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],u=t.data?ut(t.data,r,n):void 0,c=o?$t(o,t.id,u):Fr(t.id);return c.meta=t,c}function $t(t,e,r){var n=Fr(e);if(n.deferred=!0,le(t)){var i=n.state=Re(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function Li(t){try{return typeof t.send=="function"}catch{return!1}}function ji(t){return Li(t)&&"id"in t}function $i(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[pe]=function(){return this},e),t)}var yt=function(t){return t.type==="atomic"||t.type==="final"};function Hr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Ve(t){return Hr(t).filter(function(e){return e.type!=="history"})}function qr(t){var e=[t];return yt(t)?e:e.concat(G(Ve(t).map(qr)))}function Ke(t,e){var r,n,i,s,o,u,c,d,h=new Set(t),l=Ft(h),a=new Set(e);try{for(var f=x(a),v=f.next();!v.done;v=f.next())for(var y=v.value,S=y.parent;S&&!a.has(S);)a.add(S),S=S.parent}catch(R){r={error:R}}finally{try{v&&!v.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}var w=Ft(a);try{for(var T=x(a),b=T.next();!b.done;b=T.next()){var y=b.value;if(y.type==="compound"&&(!w.get(y)||!w.get(y).length))l.get(y)?l.get(y).forEach(function(B){return a.add(B)}):y.initialStateNodes.forEach(function(B){return a.add(B)});else if(y.type==="parallel")try{for(var O=(o=void 0,x(Ve(y))),M=O.next();!M.done;M=O.next()){var D=M.value;a.has(D)||(a.add(D),l.get(D)?l.get(D).forEach(function(B){return a.add(B)}):D.initialStateNodes.forEach(function(B){return a.add(B)}))}}catch(B){o={error:B}}finally{try{M&&!M.done&&(u=O.return)&&u.call(O)}finally{if(o)throw o.error}}}}catch(R){i={error:R}}finally{try{b&&!b.done&&(s=T.return)&&s.call(T)}finally{if(i)throw i.error}}try{for(var _=x(a),$=_.next();!$.done;$=_.next())for(var y=$.value,S=y.parent;S&&!a.has(S);)a.add(S),S=S.parent}catch(R){c={error:R}}finally{try{$&&!$.done&&(d=_.return)&&d.call(_)}finally{if(c)throw c.error}}return a}function Vr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(yt(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Vr(s,e)}),i}function Ft(t){var e,r,n=new Map;try{for(var i=x(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Fi(t,e){var r=Ke([t],e);return Vr(t,Ft(r))}function Ge(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Hi(t){return q([],P(new Set(G(q([],P(t.map(function(e){return e.ownEvents})),!1)))),!1)}function gt(t,e){return e.type==="compound"?Ve(e).some(function(r){return r.type==="final"&&Ge(t,r)}):e.type==="parallel"?Ve(e).every(function(r){return gt(t,r)}):!1}function qi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Kr(t){return new Set(G(t.map(function(e){return e.tags})))}function Gr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(U(t)||U(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Gr(t[i],e[i])})}function Vi(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Ki(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var ue=function(){function t(e){var r=this,n;this.actions=[],this.activities=wr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||wr,this.meta=qi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Hi(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=ge;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=ge;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),U(e))return[e];var i=Object.keys(e);return i.concat.apply(i,q([],P(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=_t(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Ct(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;K&&J(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),Gi={deferEvents:!1},Br=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},Gi),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),Ht=new Map,Bi=0,Be={bookId:function(){return"x:".concat(Bi++)},register:function(t,e){return Ht.set(t,e),t},get:function(t){return Ht.get(t)},free:function(t){Ht.delete(t)}};function qt(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;K||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function zi(){var t=qt();if(t&&"__xstate__"in t)return t.__xstate__}function Yi(t){if(qt()){var e=zi();e&&e.register(t)}}function Wi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var d=i.shift();r=t.transition(r,d,c),n.forEach(function(h){return h.next(r)})}s=!1}},u=$i({id:e.id,send:function(d){i.push(d),o()},getSnapshot:function(){return r},subscribe:function(d,h,l){var a=dt(d,h,l);return n.add(a),a.next(r),{unsubscribe:function(){n.delete(a)}}}}),c={parent:e.parent,self:u,id:e.id||"anonymous",observers:n};return r=t.start?t.start(c):r,u}var Vt={sync:!1,autoForward:!1},Y;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Y||(Y={}));var Ji=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=Y.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(h,l){if(ke(h))return n.batch(h),n.state;var a=Q(lt(h,l));if(n.status===Y.Stopped)return K||J(!1,'Event "'.concat(a.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
14
|
+
***************************************************************************** */var m=function(){return m=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},m.apply(this,arguments)};function _t(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function x(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function P(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(c){o={error:c}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function q(t,e,r){if(arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))}var j;(function(t){t.Start="xstate.start",t.Stop="xstate.stop",t.Raise="xstate.raise",t.Send="xstate.send",t.Cancel="xstate.cancel",t.NullEvent="",t.Assign="xstate.assign",t.After="xstate.after",t.DoneState="done.state",t.DoneInvoke="done.invoke",t.Log="xstate.log",t.Init="xstate.init",t.Invoke="xstate.invoke",t.ErrorExecution="error.execution",t.ErrorCommunication="error.communication",t.ErrorPlatform="error.platform",t.ErrorCustom="xstate.error",t.Update="xstate.update",t.Pure="xstate.pure",t.Choose="xstate.choose"})(j||(j={}));var fe;(function(t){t.Parent="#_parent",t.Internal="#_internal"})(fe||(fe={}));var et=j.Start,tt=j.Stop,be=j.Raise,Le=j.Send,Pt=j.Cancel,vr=j.NullEvent,rt=j.Assign,oi=j.After,ai=j.DoneState,nt=j.Log,yr=j.Init,it=j.Invoke,ci=j.ErrorExecution,Nt=j.ErrorPlatform,Ut=j.ErrorCustom,st=j.Update,gr=j.Choose,mr=j.Pure;const ui=Object.freeze(Object.defineProperty({__proto__:null,after:oi,assign:rt,cancel:Pt,choose:gr,doneState:ai,error:Ut,errorExecution:ci,errorPlatform:Nt,init:yr,invoke:it,log:nt,nullEvent:vr,pure:mr,raise:be,send:Le,start:et,stop:tt,update:st},Symbol.toStringTag,{value:"Module"}));var Er=".",wr={},Dt="xstate.guard",li="",K=process.env.NODE_ENV==="production",ot;function Ct(t,e,r){r===void 0&&(r=Er);var n=je(t,r),i=je(e,r);return U(i)?U(n)?i===n:!1:U(n)?n in i:Object.keys(n).every(function(s){return s in i?Ct(n[s],i[s]):!1})}function Tr(t){try{return U(t)||typeof t=="number"?"".concat(t):t.type}catch{throw new Error("Events must be strings or objects with a string event.type property.")}}function Mt(t,e){try{return ke(t)?t:t.toString().split(e)}catch{throw new Error("'".concat(t,"' is not a valid state path."))}}function di(t){return typeof t=="object"&&"value"in t&&"context"in t&&"event"in t&&"_event"in t}function je(t,e){if(di(t))return t.value;if(ke(t))return at(t);if(typeof t!="string")return t;var r=Mt(t,e);return at(r)}function at(t){if(t.length===1)return t[0];for(var e={},r=e,n=0;n<t.length-1;n++)n===t.length-2?r[t[n]]=t[n+1]:(r[t[n]]={},r=r[t[n]]);return e}function $e(t,e){for(var r={},n=Object.keys(t),i=0;i<n.length;i++){var s=n[i];r[s]=e(t[s],s,t,i)}return r}function Sr(t,e,r){var n,i,s={};try{for(var o=x(Object.keys(t)),c=o.next();!c.done;c=o.next()){var u=c.value,d=t[u];r(d)&&(s[u]=e(d,u,t))}}catch(h){n={error:h}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}var hi=function(t){return function(e){var r,n,i=e;try{for(var s=x(t),o=s.next();!o.done;o=s.next()){var c=o.value;i=i[c]}}catch(u){r={error:u}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}};function fi(t,e){return function(r){var n,i,s=r;try{for(var o=x(t),c=o.next();!c.done;c=o.next()){var u=c.value;s=s[e][u]}}catch(d){n={error:d}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}}function ct(t){if(!t)return[[]];if(U(t))return[[t]];var e=G(Object.keys(t).map(function(r){var n=t[r];return typeof n!="string"&&(!n||!Object.keys(n).length)?[[r]]:ct(t[r]).map(function(i){return[r].concat(i)})}));return e}function G(t){var e;return(e=[]).concat.apply(e,q([],P(t),!1))}function br(t){return ke(t)?t:[t]}function se(t){return t===void 0?[]:br(t)}function ut(t,e,r){var n,i;if(N(t))return t(e,r.data);var s={};try{for(var o=x(Object.keys(t)),c=o.next();!c.done;c=o.next()){var u=c.value,d=t[u];N(d)?s[u]=d(e,r.data):s[u]=d}}catch(h){n={error:h}}finally{try{c&&!c.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return s}function pi(t){return/^(done|error)\./.test(t)}function kr(t){return!!(t instanceof Promise||t!==null&&(N(t)||typeof t=="object")&&N(t.then))}function vi(t){return t!==null&&typeof t=="object"&&"transition"in t&&typeof t.transition=="function"}function yi(t,e){var r,n,i=P([[],[]],2),s=i[0],o=i[1];try{for(var c=x(t),u=c.next();!u.done;u=c.next()){var d=u.value;e(d)?s.push(d):o.push(d)}}catch(h){r={error:h}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}return[s,o]}function Ar(t,e){return $e(t.states,function(r,n){if(r){var i=(U(e)?void 0:e[n])||(r?r.current:void 0);if(i)return{current:i,states:Ar(r,i)}}})}function gi(t,e){return{current:e,states:Ar(t,e)}}function Or(t,e,r,n){K||J(!!t,"Attempting to update undefined context");var i=t&&r.reduce(function(s,o){var c,u,d=o.assignment,h={state:n,action:o,_event:e},l={};if(N(d))l=d(s,e.data,h);else try{for(var a=x(Object.keys(d)),f=a.next();!f.done;f=a.next()){var v=f.value,y=d[v];l[v]=N(y)?y(s,e.data,h):y}}catch(S){c={error:S}}finally{try{f&&!f.done&&(u=a.return)&&u.call(a)}finally{if(c)throw c.error}}return Object.assign({},s,l)},t);return i}var J=function(){};K||(J=function(t,e){var r=t instanceof Error?t:void 0;if(!(!r&&t)&&console!==void 0){var n=["Warning: ".concat(e)];r&&n.push(r),console.warn.apply(console,n)}});function ke(t){return Array.isArray(t)}function N(t){return typeof t=="function"}function U(t){return typeof t=="string"}function Ir(t,e){if(t)return U(t)?{type:Dt,name:t,predicate:e?e[t]:void 0}:N(t)?{type:Dt,name:t.name,predicate:t}:t}function mi(t){try{return"subscribe"in t&&N(t.subscribe)}catch{return!1}}var pe=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();ot={},ot[pe]=function(){return this},ot[Symbol.observable]=function(){return this};function le(t){return!!t&&"__xstatenode"in t}function Ei(t){return!!t&&typeof t.send=="function"}var wi=function(){var t=0;return function(){return t++,t.toString(16)}}();function lt(t,e){return U(t)||typeof t=="number"?m({type:t},e):t}function Q(t,e){if(!U(t)&&"$$type"in t&&t.$$type==="scxml")return t;var r=lt(t);return m({name:r.type,data:r,$$type:"scxml",type:"external"},e)}function Ae(t,e){var r=br(e).map(function(n){return typeof n=="undefined"||typeof n=="string"||le(n)?{target:n,event:t}:m(m({},n),{event:t})});return r}function Ti(t){if(!(t===void 0||t===li))return se(t)}function Si(t,e,r){if(!K){var n=t.stack?" Stacktrace was '".concat(t.stack,"'"):"";if(t===e)console.error("Missing onError handler for invocation '".concat(r,"', error was '").concat(t,"'.").concat(n));else{var i=e.stack?" Stacktrace was '".concat(e.stack,"'"):"";console.error("Missing onError handler and/or unhandled exception/promise rejection for invocation '".concat(r,"'. ")+"Original error: '".concat(t,"'. ").concat(n," Current error is '").concat(e,"'.").concat(i))}}}function Rr(t,e,r,n,i){var s=t.options.guards,o={state:i,cond:e,_event:n};if(e.type===Dt)return((s==null?void 0:s[e.name])||e.predicate)(r,n.data,o);var c=s==null?void 0:s[e.type];if(!c)throw new Error("Guard '".concat(e.type,"' is not implemented on machine '").concat(t.id,"'."));return c(r,n.data,o)}function xr(t){return typeof t=="string"?{type:t}:t}function dt(t,e,r){var n=function(){},i=typeof t=="object",s=i?t:null;return{next:((i?t.next:t)||n).bind(s),error:((i?t.error:e)||n).bind(s),complete:((i?t.complete:r)||n).bind(s)}}function ht(t,e){return"".concat(t,":invocation[").concat(e,"]")}function Lt(t){return(t.type===be||t.type===Le&&t.to===fe.Internal)&&typeof t.delay!="number"}var ge=Q({type:yr});function ft(t,e){return e&&e[t]||void 0}function Oe(t,e){var r;if(U(t)||typeof t=="number"){var n=ft(t,e);N(n)?r={type:t,exec:n}:n?r=n:r={type:t,exec:void 0}}else if(N(t))r={type:t.name||t.toString(),exec:t};else{var n=ft(t.type,e);if(N(n))r=m(m({},t),{exec:n});else if(n){var i=n.type||t.type;r=m(m(m({},n),t),{type:i})}else r=t}return r}var de=function(t,e){if(!t)return[];var r=ke(t)?t:[t];return r.map(function(n){return Oe(n,e)})};function pt(t){var e=Oe(t);return m(m({id:U(t)?t:e.id},e),{type:e.type})}function _r(t,e){return{type:be,event:typeof t=="function"?t:lt(t),delay:e?e.delay:void 0,id:e==null?void 0:e.id}}function Pr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var c=n&&n[t.delay];o=N(c)?c(e,r.data,i):c}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;return m(m({},t),{type:be,_event:s,delay:o})}function me(t,e){return{to:e?e.to:void 0,type:Le,event:N(t)?t:lt(t),delay:e?e.delay:void 0,id:e&&e.id!==void 0?e.id:N(t)?t.name:Tr(t)}}function Nr(t,e,r,n){var i={_event:r},s=Q(N(t.event)?t.event(e,r.data,i):t.event),o;if(U(t.delay)){var c=n&&n[t.delay];o=N(c)?c(e,r.data,i):c}else o=N(t.delay)?t.delay(e,r.data,i):t.delay;var u=N(t.to)?t.to(e,r.data,i):t.to;return m(m({},t),{to:u,_event:s,event:s.data,delay:o})}function jt(t,e){return me(t,m(m({},e),{to:fe.Parent}))}function bi(t,e,r){return me(e,m(m({},r),{to:t}))}function ki(){return jt(st)}function Ai(t,e){return me(t,m(m({},e),{to:function(r,n,i){var s=i._event;return s.origin}}))}var Oi=function(t,e){return{context:t,event:e}};function Ii(t,e){return t===void 0&&(t=Oi),{type:nt,label:e,expr:t}}var Ur=function(t,e,r){return m(m({},t),{value:U(t.expr)?t.expr:t.expr(e,r.data,{_event:r})})},Dr=function(t){return{type:Pt,sendId:t}};function Cr(t){var e=pt(t);return{type:j.Start,activity:e,exec:void 0}}function Mr(t){var e=N(t)?t:pt(t);return{type:j.Stop,activity:e,exec:void 0}}function Lr(t,e,r){var n=N(t.activity)?t.activity(e,r.data):t.activity,i=typeof n=="string"?{id:n}:n,s={type:j.Stop,activity:i};return s}var jr=function(t){return{type:rt,assignment:t}};function Ri(t){return typeof t=="object"&&"type"in t}function $r(t,e){var r=e?"#".concat(e):"";return"".concat(j.After,"(").concat(t,")").concat(r)}function Fe(t,e){var r="".concat(j.DoneState,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function He(t,e){var r="".concat(j.DoneInvoke,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function Ie(t,e){var r="".concat(j.ErrorPlatform,".").concat(t),n={type:r,data:e};return n.toString=function(){return r},n}function xi(t){return{type:j.Pure,get:t}}function _i(t,e){if(!K&&(!t||typeof t=="function")){var r=t;t=function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];var s=typeof r=="function"?r.apply(void 0,q([],P(n),!1)):r;if(!s)throw new Error("Attempted to forward event to undefined actor. This risks an infinite loop in the sender.");return s}}return me(function(n,i){return i},m(m({},e),{to:t}))}function Pi(t,e){return jt(function(r,n,i){return{type:Ut,data:N(t)?t(r,n,i):t}},m(m({},e),{to:fe.Parent}))}function Ni(t){return{type:j.Choose,conds:t}}var Ui=function(t){var e,r,n=[];try{for(var i=x(t),s=i.next();!s.done;s=i.next())for(var o=s.value,c=0;c<o.actions.length;){if(o.actions[c].type===rt){n.push(o.actions[c]),o.actions.splice(c,1);continue}c++}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n};function qe(t,e,r,n,i,s,o){o===void 0&&(o=!1);var c=o?[]:Ui(i),u=c.length?Or(r,n,c,e):r,d=o?[r]:void 0,h=[];function l(v,y){var S;switch(y.type){case be:{var w=Pr(y,u,n,t.options.delays);return s&&typeof w.delay=="number"&&s(w,u,n),w}case Le:var T=Nr(y,u,n,t.options.delays);if(!K){var b=y.delay;J(!U(b)||typeof T.delay=="number","No delay reference for delay expression '".concat(b,"' was found on machine '").concat(t.id,"'"))}return s&&T.to!==fe.Internal&&(v==="entry"?h.push(T):s(T,u,n)),T;case nt:{var O=Ur(y,u,n);return s==null||s(O,u,n),O}case gr:{var M=y,D=(S=M.conds.find(function(p){var E=Ir(p.cond,t.options.guards);return!E||Rr(t,E,u,n,s?void 0:e)}))===null||S===void 0?void 0:S.actions;if(!D)return[];var _=P(qe(t,e,u,n,[{type:v,actions:de(se(D),t.options.actions)}],s,o),2),$=_[0],R=_[1];return u=R,d==null||d.push(u),$}case mr:{var D=y.get(u,n.data);if(!D)return[];var B=P(qe(t,e,u,n,[{type:v,actions:de(se(D),t.options.actions)}],s,o),2),A=B[0],F=B[1];return u=F,d==null||d.push(u),A}case tt:{var O=Lr(y,u,n);return s==null||s(O,r,n),O}case rt:{u=Or(u,n,[y],s?void 0:e),d==null||d.push(u);break}default:var z=Oe(y,t.options.actions),V=z.exec;if(s)s(z,u,n);else if(V&&d){var we=d.length-1,Te=m(m({},z),{exec:function(p){for(var E=[],k=1;k<arguments.length;k++)E[k-1]=arguments[k];V.apply(void 0,q([d[we]],P(E),!1))}});z=Te}return z}}function a(v){var y,S,w=[];try{for(var T=x(v.actions),b=T.next();!b.done;b=T.next()){var O=b.value,M=l(v.type,O);M&&(w=w.concat(M))}}catch(D){y={error:D}}finally{try{b&&!b.done&&(S=T.return)&&S.call(T)}finally{if(y)throw y.error}}return h.forEach(function(D){s(D,u,n)}),h.length=0,w}var f=G(i.map(a));return[f,u]}const Di=Object.freeze(Object.defineProperty({__proto__:null,actionTypes:ui,after:$r,assign:jr,cancel:Dr,choose:Ni,done:Fe,doneInvoke:He,error:Ie,escalate:Pi,forwardTo:_i,getActionFunction:ft,initEvent:ge,isActionObject:Ri,log:Ii,pure:xi,raise:_r,resolveActions:qe,resolveLog:Ur,resolveRaise:Pr,resolveSend:Nr,resolveStop:Lr,respond:Ai,send:me,sendParent:jt,sendTo:bi,sendUpdate:ki,start:Cr,stop:Mr,toActionObject:Oe,toActionObjects:de,toActivityDefinition:pt},Symbol.toStringTag,{value:"Module"}));var vt=[],Re=function(t,e){vt.push(t);var r=e(t);return vt.pop(),r},Ci=function(t){return t(vt[vt.length-1])};function Fr(t){var e;return e={id:t,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},getSnapshot:function(){},toJSON:function(){return{id:t}}},e[pe]=function(){return this},e}function Mi(t,e,r,n){var i,s=xr(t.src),o=(i=e==null?void 0:e.options.services)===null||i===void 0?void 0:i[s.type],c=t.data?ut(t.data,r,n):void 0,u=o?$t(o,t.id,c):Fr(t.id);return u.meta=t,u}function $t(t,e,r){var n=Fr(e);if(n.deferred=!0,le(t)){var i=n.state=Re(void 0,function(){return(r?t.withContext(r):t).initialState});n.getSnapshot=function(){return i}}return n}function Li(t){try{return typeof t.send=="function"}catch{return!1}}function ji(t){return Li(t)&&"id"in t}function $i(t){var e;return m((e={subscribe:function(){return{unsubscribe:function(){}}},id:"anonymous",getSnapshot:function(){}},e[pe]=function(){return this},e),t)}var yt=function(t){return t.type==="atomic"||t.type==="final"};function Hr(t){return Object.keys(t.states).map(function(e){return t.states[e]})}function Ve(t){return Hr(t).filter(function(e){return e.type!=="history"})}function qr(t){var e=[t];return yt(t)?e:e.concat(G(Ve(t).map(qr)))}function Ke(t,e){var r,n,i,s,o,c,u,d,h=new Set(t),l=Ft(h),a=new Set(e);try{for(var f=x(a),v=f.next();!v.done;v=f.next())for(var y=v.value,S=y.parent;S&&!a.has(S);)a.add(S),S=S.parent}catch(R){r={error:R}}finally{try{v&&!v.done&&(n=f.return)&&n.call(f)}finally{if(r)throw r.error}}var w=Ft(a);try{for(var T=x(a),b=T.next();!b.done;b=T.next()){var y=b.value;if(y.type==="compound"&&(!w.get(y)||!w.get(y).length))l.get(y)?l.get(y).forEach(function(B){return a.add(B)}):y.initialStateNodes.forEach(function(B){return a.add(B)});else if(y.type==="parallel")try{for(var O=(o=void 0,x(Ve(y))),M=O.next();!M.done;M=O.next()){var D=M.value;a.has(D)||(a.add(D),l.get(D)?l.get(D).forEach(function(B){return a.add(B)}):D.initialStateNodes.forEach(function(B){return a.add(B)}))}}catch(B){o={error:B}}finally{try{M&&!M.done&&(c=O.return)&&c.call(O)}finally{if(o)throw o.error}}}}catch(R){i={error:R}}finally{try{b&&!b.done&&(s=T.return)&&s.call(T)}finally{if(i)throw i.error}}try{for(var _=x(a),$=_.next();!$.done;$=_.next())for(var y=$.value,S=y.parent;S&&!a.has(S);)a.add(S),S=S.parent}catch(R){u={error:R}}finally{try{$&&!$.done&&(d=_.return)&&d.call(_)}finally{if(u)throw u.error}}return a}function Vr(t,e){var r=e.get(t);if(!r)return{};if(t.type==="compound"){var n=r[0];if(n){if(yt(n))return n.key}else return{}}var i={};return r.forEach(function(s){i[s.key]=Vr(s,e)}),i}function Ft(t){var e,r,n=new Map;try{for(var i=x(t),s=i.next();!s.done;s=i.next()){var o=s.value;n.has(o)||n.set(o,[]),o.parent&&(n.has(o.parent)||n.set(o.parent,[]),n.get(o.parent).push(o))}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(e)throw e.error}}return n}function Fi(t,e){var r=Ke([t],e);return Vr(t,Ft(r))}function Ge(t,e){return Array.isArray(t)?t.some(function(r){return r===e}):t instanceof Set?t.has(e):!1}function Hi(t){return q([],P(new Set(G(q([],P(t.map(function(e){return e.ownEvents})),!1)))),!1)}function gt(t,e){return e.type==="compound"?Ve(e).some(function(r){return r.type==="final"&&Ge(t,r)}):e.type==="parallel"?Ve(e).every(function(r){return gt(t,r)}):!1}function qi(t){return t===void 0&&(t=[]),t.reduce(function(e,r){return r.meta!==void 0&&(e[r.id]=r.meta),e},{})}function Kr(t){return new Set(G(t.map(function(e){return e.tags})))}function Gr(t,e){if(t===e)return!0;if(t===void 0||e===void 0)return!1;if(U(t)||U(e))return t===e;var r=Object.keys(t),n=Object.keys(e);return r.length===n.length&&r.every(function(i){return Gr(t[i],e[i])})}function Vi(t){return typeof t!="object"||t===null?!1:"value"in t&&"_event"in t}function Ki(t,e){var r=t.exec,n=m(m({},t),{exec:r!==void 0?function(){return r(e.context,e.event,{action:t,state:e,_event:e._event})}:void 0});return n}var ue=function(){function t(e){var r=this,n;this.actions=[],this.activities=wr,this.meta={},this.events=[],this.value=e.value,this.context=e.context,this._event=e._event,this._sessionid=e._sessionid,this.event=this._event.data,this.historyValue=e.historyValue,this.history=e.history,this.actions=e.actions||[],this.activities=e.activities||wr,this.meta=qi(e.configuration),this.events=e.events||[],this.matches=this.matches.bind(this),this.toStrings=this.toStrings.bind(this),this.configuration=e.configuration,this.transitions=e.transitions,this.children=e.children,this.done=!!e.done,this.tags=(n=Array.isArray(e.tags)?new Set(e.tags):e.tags)!==null&&n!==void 0?n:new Set,this.machine=e.machine,Object.defineProperty(this,"nextEvents",{get:function(){return Hi(r.configuration)}})}return t.from=function(e,r){if(e instanceof t)return e.context!==r?new t({value:e.value,context:r,_event:e._event,_sessionid:null,historyValue:e.historyValue,history:e.history,actions:[],activities:e.activities,meta:{},events:[],configuration:[],transitions:[],children:{}}):e;var n=ge;return new t({value:e,context:r,_event:n,_sessionid:null,historyValue:void 0,history:void 0,actions:[],activities:void 0,meta:void 0,events:[],configuration:[],transitions:[],children:{}})},t.create=function(e){return new t(e)},t.inert=function(e,r){if(e instanceof t){if(!e.actions.length)return e;var n=ge;return new t({value:e.value,context:r,_event:n,_sessionid:null,historyValue:e.historyValue,history:e.history,activities:e.activities,configuration:e.configuration,transitions:[],children:{}})}return t.from(e,r)},t.prototype.toStrings=function(e,r){var n=this;if(e===void 0&&(e=this.value),r===void 0&&(r="."),U(e))return[e];var i=Object.keys(e);return i.concat.apply(i,q([],P(i.map(function(s){return n.toStrings(e[s],r).map(function(o){return s+r+o})})),!1))},t.prototype.toJSON=function(){var e=this;e.configuration,e.transitions;var r=e.tags;e.machine;var n=_t(e,["configuration","transitions","tags","machine"]);return m(m({},n),{tags:Array.from(r)})},t.prototype.matches=function(e){return Ct(e,this.value)},t.prototype.hasTag=function(e){return this.tags.has(e)},t.prototype.can=function(e){var r;K&&J(!!this.machine,"state.can(...) used outside of a machine-created State object; this will always return false.");var n=(r=this.machine)===null||r===void 0?void 0:r.getTransitionData(this,e);return!!(n!=null&&n.transitions.length)&&n.transitions.some(function(i){return i.target!==void 0||i.actions.length})},t}(),Gi={deferEvents:!1},Br=function(){function t(e){this.processingEvent=!1,this.queue=[],this.initialized=!1,this.options=m(m({},Gi),e)}return t.prototype.initialize=function(e){if(this.initialized=!0,e){if(!this.options.deferEvents){this.schedule(e);return}this.process(e)}this.flushEvents()},t.prototype.schedule=function(e){if(!this.initialized||this.processingEvent){this.queue.push(e);return}if(this.queue.length!==0)throw new Error("Event queue should be empty when it is not processing events");this.process(e),this.flushEvents()},t.prototype.clear=function(){this.queue=[]},t.prototype.flushEvents=function(){for(var e=this.queue.shift();e;)this.process(e),e=this.queue.shift()},t.prototype.process=function(e){this.processingEvent=!0;try{e()}catch(r){throw this.clear(),r}finally{this.processingEvent=!1}},t}(),Ht=new Map,Bi=0,Be={bookId:function(){return"x:".concat(Bi++)},register:function(t,e){return Ht.set(t,e),t},get:function(t){return Ht.get(t)},free:function(t){Ht.delete(t)}};function qt(){if(typeof globalThis!="undefined")return globalThis;if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof global!="undefined")return global;K||console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function zi(){var t=qt();if(t&&"__xstate__"in t)return t.__xstate__}function Yi(t){if(qt()){var e=zi();e&&e.register(t)}}function Wi(t,e){e===void 0&&(e={});var r=t.initialState,n=new Set,i=[],s=!1,o=function(){if(!s){for(s=!0;i.length>0;){var d=i.shift();r=t.transition(r,d,u),n.forEach(function(h){return h.next(r)})}s=!1}},c=$i({id:e.id,send:function(d){i.push(d),o()},getSnapshot:function(){return r},subscribe:function(d,h,l){var a=dt(d,h,l);return n.add(a),a.next(r),{unsubscribe:function(){n.delete(a)}}}}),u={parent:e.parent,self:c,id:e.id||"anonymous",observers:n};return r=t.start?t.start(u):r,c}var Vt={sync:!1,autoForward:!1},Y;(function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"})(Y||(Y={}));var Ji=function(){function t(e,r){r===void 0&&(r=t.defaultOptions);var n=this;this.machine=e,this.delayedEventsMap={},this.listeners=new Set,this.contextListeners=new Set,this.stopListeners=new Set,this.doneListeners=new Set,this.eventListeners=new Set,this.sendListeners=new Set,this.initialized=!1,this.status=Y.NotStarted,this.children=new Map,this.forwardTo=new Set,this._outgoingQueue=[],this.init=this.start,this.send=function(h,l){if(ke(h))return n.batch(h),n.state;var a=Q(lt(h,l));if(n.status===Y.Stopped)return K||J(!1,'Event "'.concat(a.name,'" was sent to stopped service "').concat(n.machine.id,`". This service has already reached its final state, and will not transition.
|
|
15
15
|
Event: `).concat(JSON.stringify(a.data))),n.state;if(n.status!==Y.Running&&!n.options.deferEvents)throw new Error('Event "'.concat(a.name,'" was sent to uninitialized service "').concat(n.machine.id,`". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.
|
|
16
|
-
Event: `).concat(JSON.stringify(a.data)));return n.scheduler.schedule(function(){n.forward(a);var f=n._nextState(a);n.update(f,a)}),n._state},this.sendTo=function(h,l,a){var f=n.parent&&(l===fe.Parent||n.parent.id===l),v=f?n.parent:U(l)?l===fe.Internal?n:n.children.get(l)||Be.get(l):Ei(l)?l:void 0;if(!v){if(!f)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));K||J(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(h.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var y=m(m({},h),{name:h.name===Ut?"".concat(Ie(n.id)):h.name,origin:n.sessionId});!a&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,y]):v.send(y)}}else!a&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,h.data]):v.send(h.data)},this._exec=function(h,l,a,f){f===void 0&&(f=n.machine.options.actions);var v=h.exec||ft(h.type,f),y=N(v)?v:v?v.exec:h.exec;if(y)try{return y(l,a.data,n.machine.config.predictableActionArguments?{action:h,_event:a}:{action:h,state:n.state,_event:a})}catch(V){throw n.parent&&n.parent.send({type:"xstate.error",data:V}),V}switch(h.type){case be:{var S=h;n.defer(S);break}case Le:var w=h;if(typeof w.delay=="number"){n.defer(w);return}else w.to?n.sendTo(w._event,w.to,a===ge):n.send(w._event);break;case Pt:n.cancel(h.sendId);break;case et:{if(n.status!==Y.Running)return;var T=h.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[T.id||T.type])break;if(T.type===j.Invoke){var b=xr(T.src),O=n.machine.options.services?n.machine.options.services[b.type]:void 0,M=T.id,D=T.data;K||J(!("forward"in T),"`forward` property is deprecated (found in invocation of '".concat(T.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var _="autoForward"in T?T.autoForward:!!T.forward;if(!O){K||J(!1,"No service found for invocation '".concat(T.src,"' in machine '").concat(n.machine.id,"'."));return}var $=D?ut(D,l,a):void 0;if(typeof O=="string")return;var R=N(O)?O(l,a.data,{data:$,src:b,meta:T.meta}):O;if(!R)return;var B=void 0;le(R)&&(R=$?R.withContext($):R,B={autoForward:_}),n.spawn(R,M,B)}else n.spawnActivity(T);break}case tt:{n.stopChild(h.activity.id);break}case nt:var A=h,F=A.label,z=A.value;F?n.logger(F,z):n.logger(z);break;default:K||J(!1,"No implementation found for action type '".concat(h.type,"'"));break}};var i=m(m({},t.defaultOptions),r),s=i.clock,o=i.logger,
|
|
17
|
-
Event: `).concat(JSON.stringify(event)));else if(this.status!==Y.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,u=!1,c=[],d=function(f){var v=Q(f);r.forward(v),o=Re(r,function(){return r.machine.transition(o,v,void 0,n||void 0)}),c.push.apply(c,q([],P(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(y){return Ki(y,o)})),!1)),u=u||!!o.changed};try{for(var h=x(e),l=h.next();!l.done;l=h.next()){var a=l.value;d(a)}}catch(f){i={error:f}}finally{try{l&&!l.done&&(s=h.return)&&s.call(h)}finally{if(i)throw i.error}}o.changed=u,o.actions=c,r.update(o,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(Nt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(Nt)===0}))throw i.data.data;var s=Re(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=x(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,u=this.children.get(o);if(!u)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));u.send(e)}}catch(c){r={error:c}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this,n=this.clock.setTimeout(function(){"to"in e&&e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay);e.id&&(this.delayedEventsMap[e.id]=n)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return $t(e,r);if(kr(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(ji(e))return this.spawnActor(e,r);if(mi(e))return this.spawnObservable(e,r);if(le(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(vi(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),s=m(m({},Vt),r);s.sync&&i.onTransition(function(u){n.send(st,{state:u,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(u){n.removeChild(i.id),n.send(Q(u,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Wi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(c){s||(o=c,i.removeChild(r),i.send(Q(He(r,c),{origin:r})))},function(c){if(!s){i.removeChild(r);var d=Ie(r,c);try{i.send(Q(d,{origin:r}))}catch(h){Si(c,h,r),i.devTools&&i.devTools.send(d,i.state),i.machine.strict&&i.stop()}}});var u=(n={id:r,send:function(){},subscribe:function(c,d,h){var l=dt(c,d,h),a=!1;return e.then(function(f){a||(l.next(f),!a&&l.complete())},function(f){a||l.error(f)}),{unsubscribe:function(){return a=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[pe]=function(){return this},n);return this.children.set(r,u),u},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,u=new Set,c,d=function(a){c=a,u.forEach(function(f){return f(a)}),!s&&i.send(Q(a,{origin:r}))},h;try{h=e(d,function(a){o.add(a)})}catch(a){this.send(Ie(r,a))}if(kr(h))return this.spawnPromise(h,r);var l=(n={id:r,send:function(a){return o.forEach(function(f){return f(a)})},subscribe:function(a){var f=dt(a);return u.add(f.next),{unsubscribe:function(){u.delete(f.next)}}},stop:function(){s=!0,N(h)&&h()},toJSON:function(){return{id:r}},getSnapshot:function(){return c}},n[pe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(c){s=c,i.send(Q(c,{origin:r}))},function(c){i.removeChild(r),i.send(Q(Ie(r,c),{origin:r}))},function(){i.removeChild(r),i.send(Q(He(r),{origin:r}))}),u=(n={id:r,send:function(){},subscribe:function(c,d,h){return e.subscribe(c,d,h)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[pe]=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){K||J(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[pe]=function(){return this},n))},t.prototype.attachDev=function(){var e=qt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Yi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[pe]=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}(),Xi=function(t){return U(t)?m(m({},Vt),{name:t}):m(m(m({},Vt),{name:wi()}),t)};function Qi(t,e){var r=Xi(e);return Ci(function(n){if(!K){var i=le(t)||N(t);J(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(le(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):$t(t,r.name)})}function xe(t,e){var r=new Ji(t,e);return r}function Zi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function mt(t){return m(m({type:it},t),{toJSON:function(){t.onDone,t.onError;var e=_t(t,["onDone","onError"]);return m(m({},e),{type:it,src:Zi(t.src)})}})}var _e="",Kt="#",ze="*",Pe={},Ne=function(t){return t[0]===Kt},es=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},ts=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(U(s.target)||le(s.target))}),i=e===_e?"the transient event":"event '".concat(e,"'");J(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},rs=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(es(),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:Er),this.id=this.config.id||q([this.machine.key],P(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,K||J(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?$e(this.config.states,function(d,h){var l,a=new t(d,{},void 0,{parent:s,key:h});return Object.assign(s.idMap,m((l={},l[a.id]=a,l),a.idMap)),a}):Pe;var u=0;function c(d){var h,l;d.order=u++;try{for(var a=x(Hr(d)),f=a.next();!f.done;f=a.next()){var v=f.value;c(v)}}catch(y){h={error:y}}finally{try{f&&!f.done&&(l=a.return)&&l.call(a)}finally{if(h)throw h.error}}}c(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(d){var h=d.event;return h===_e}):_e in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=se(this.config.entry||this.config.onEntry).map(function(d){return Oe(d)}),this.onExit=se(this.config.exit||this.config.onExit).map(function(d){return Oe(d)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=se(this.config.invoke).map(function(d,h){var l,a;if(le(d)){var f=ht(s.id,h);return s.machine.options.services=m((l={},l[f]=d,l),s.machine.options.services),mt({src:f,id:f})}else if(U(d.src)){var f=d.id||ht(s.id,h);return mt(m(m({},d),{id:f,src:d.src}))}else if(le(d.src)||N(d.src)){var f=d.id||ht(s.id,h);return s.machine.options.services=m((a={},a[f]=d.src,a),s.machine.options.services),mt(m(m({id:f},d),{src:f}))}else{var v=d.src;return mt(m(m({id:ht(s.id,h)},d),{src:v}))}}),this.activities=se(this.config.activities).concat(this.invoke).map(function(d){return pt(d)}),this.transition=this.transition.bind(this),this.tags=se(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||qr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,u=n.services,c=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},s),e.activities),guards:m(m({},o),e.guards),services:m(m({},u),e.services),delays:m(m({},c),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:$e(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===_e,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===ze});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var u=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,c=$r(u,e.id);return e.onEntry.push(me(c,{delay:s})),e.onExit.push(Dr(c)),c},i=ke(r)?r.map(function(s,o){var u=n(s.delay,o);return m(m({},s),{event:u})}):G(Object.keys(r).map(function(s,o){var u=r[s],c=U(u)?{target:u}:u,d=isNaN(+s)?s:+s,h=n(d,o);return se(c).map(function(l){return m(m({},l),{event:h,delay:d})})}));return i.map(function(s){var o=s.delay;return m(m({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof ue?e.value:je(e,this.delimiter);if(U(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),u=[this];return u.push.apply(u,q([],P(G(o.map(function(c){return n.getStateNode(c).getStateNodes(i[c])}))),!1)),u},t.prototype.handles=function(e){var r=Tr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof ue?e:ue.create(e),n=Array.from(Ke([],this.getStateNodes(r.value)));return new ue(m(m({},r),{value:this.resolve(r.value),configuration:n,done:gt(n,this),tags:Kr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var u=x(Object.keys(e)),c=u.next();!c.done;c=u.next()){var d=c.value,h=e[d];if(h){var l=this.getStateNode(d),a=l._transition(h,r,n);a&&(o[d]=a)}}}catch(w){i={error:w}}finally{try{c&&!c.done&&(s=u.return)&&s.call(u)}finally{if(i)throw i.error}}var f=Object.keys(o).map(function(w){return o[w]}),v=G(f.map(function(w){return w.transitions})),y=f.some(function(w){return w.transitions.length>0});if(!y)return this.next(r,n);var S=G(Object.keys(o).map(function(w){return o[w].configuration}));return{transitions:v,exitSet:G(f.map(function(w){return w.exitSet})),configuration:S,source:r,actions:G(Object.keys(o).map(function(w){return o[w].actions}))}},t.prototype._transition=function(e,r,n){return U(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,u=[],c=[],d;try{for(var h=x(this.getCandidates(o)),l=h.next();!l.done;l=h.next()){var a=l.value,f=a.cond,v=a.in,y=e.context,S=v?U(v)&&Ne(v)?e.matches(je(this.getStateNodeById(v).path,this.delimiter)):Ct(je(v,this.delimiter),hi(this.path.slice(0,-2))(e.value)):!0,w=!1;try{w=!f||Rr(this.machine,f,y,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(f.name||f.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
-
`).concat(O.message))}if(w&&S){a.target!==void 0&&(c=a.target),u.push.apply(u,q([],P(a.actions),!1)),d=a;break}}}catch(O){n={error:O}}finally{try{l&&!l.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}if(d){if(!c.length)return{transitions:[d],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var T=G(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),b=!!d.internal;return{transitions:[d],exitSet:b?[]:G(c.map(function(O){return s.getPotentiallyReenteringNodes(O)})),configuration:T,source:e,actions:u}}},t.prototype.getPotentiallyReenteringNodes=function(e){if(this.order<e.order)return[this];for(var r=[],n=this,i=e;n&&n!==i;)r.push(n),n=n.parent;return n!==i?[]:(r.push(i),r)},t.prototype.getActions=function(e,r,n,i,s,o,u){var c,d,h,l,a=this,f=o?Ke([],this.getStateNodes(o.value)):[],v=new Set;try{for(var y=x(Array.from(e).sort(function(A,F){return A.order-F.order})),S=y.next();!S.done;S=y.next()){var w=S.value;(!Ge(f,w)||Ge(n.exitSet,w)||w.parent&&v.has(w.parent))&&v.add(w)}}catch(A){c={error:A}}finally{try{S&&!S.done&&(d=y.return)&&d.call(y)}finally{if(c)throw c.error}}try{for(var T=x(f),b=T.next();!b.done;b=T.next()){var w=b.value;(!Ge(e,w)||Ge(n.exitSet,w.parent))&&n.exitSet.push(w)}}catch(A){h={error:A}}finally{try{b&&!b.done&&(l=T.return)&&l.call(T)}finally{if(h)throw h.error}}n.exitSet.sort(function(A,F){return F.order-A.order});var O=Array.from(v).sort(function(A,F){return A.order-F.order}),M=new Set(n.exitSet),D=G(O.map(function(A){var F=[];if(A.type!=="final")return F;var z=A.parent;if(!z.parent)return F;F.push(Fe(A.id,A.doneData),Fe(z.id,A.doneData?ut(A.doneData,i,s):void 0));var V=z.parent;return V.type==="parallel"&&Ve(V).every(function(we){return gt(n.configuration,we)})&&F.push(Fe(V.id)),F})),_=O.map(function(A){var F=A.onEntry,z=A.activities.map(function(V){return Cr(V)});return{type:"entry",actions:de(u?q(q([],P(F),!1),P(z),!1):q(q([],P(z),!1),P(F),!1),a.machine.options.actions)}}).concat({type:"state_done",actions:D.map(function(A){return _r(A)})}),$=Array.from(M).map(function(A){return{type:"exit",actions:de(q(q([],P(A.onExit),!1),P(A.activities.map(function(F){return Mr(F)})),!1),a.machine.options.actions)}}),R=$.concat({type:"transition",actions:de(n.actions,this.machine.options.actions)}).concat(_);if(r){var B=de(G(q([],P(e),!1).sort(function(A,F){return F.order-A.order}).map(function(A){return A.onExit})),this.machine.options.actions).filter(function(A){return!Lt(A)});return R.concat({type:"stop",actions:B})}return R},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=Q(r),o;if(e instanceof ue)o=n===void 0?e:this.resolveState(ue.from(e,n));else{var u=U(e)?this.resolve(at(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(ue.from(u,c))}if(!K&&s.name===ze)throw new Error("An event cannot have the wildcard type ('".concat(ze,"')"));if(this.strict&&!this.events.includes(s.name)&&!pi(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var d=this._transition(o.value,o,s)||{transitions:[],configuration:[],exitSet:[],source:o,actions:[]},h=Ke([],this.getStateNodes(o.value)),l=d.configuration.length?Ke(h,d.configuration):h;return d.configuration=q([],P(l),!1),this.resolveTransition(d,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,q([],P(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,u,c,d,h=this;s===void 0&&(s=ge);var l=e.configuration,a=!r||e.transitions.length>0,f=a?e.configuration:r?r.configuration:[],v=gt(f,this),y=a?Fi(this.machine,l):void 0,S=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,w=this.getActions(new Set(f),v,e,n,s,r,i),T=r?m({},r.activities):{};try{for(var b=x(w),O=b.next();!O.done;O=b.next()){var M=O.value;try{for(var D=(c=void 0,x(M.actions)),_=D.next();!_.done;_=D.next()){var $=_.value;$.type===et?T[$.activity.id||$.activity.type]=$:$.type===tt&&(T[$.activity.id||$.activity.type]=!1)}}catch(ne){c={error:ne}}finally{try{_&&!_.done&&(d=D.return)&&d.call(D)}finally{if(c)throw c.error}}}}catch(ne){o={error:ne}}finally{try{O&&!O.done&&(u=b.return)&&u.call(b)}finally{if(o)throw o.error}}var R=P(qe(this,r,n,s,w,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),B=R[0],A=R[1],F=P(yi(B,Lt),2),z=F[0],V=F[1],we=B.filter(function(ne){var W;return ne.type===et&&((W=ne.activity)===null||W===void 0?void 0:W.type)===it}),Te=we.reduce(function(ne,W){return ne[W.activity.id]=Mi(W.activity,h.machine,A,s),ne},r?m({},r.children):{}),p=new ue({value:y||r.value,context:A,_event:s,_sessionid:r?r._sessionid:null,historyValue:y?S?gi(S,y):void 0:r?r.historyValue:void 0,history:!y||e.source?r:void 0,actions:y?V:[],activities:y?T:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:Te,done:v,tags:Kr(f),machine:this}),E=n!==A;p.changed=s.name===st||E;var k=p.history;k&&delete k.history;var H=!v&&(this._transient||l.some(function(ne){return ne._transient}));if(!a&&(!H||s.name===_e))return p;var C=p;if(!v)for(H&&(C=this.resolveRaisedTransition(C,{type:vr},s,i));z.length;){var L=z.shift();C=this.resolveRaisedTransition(C,L._event,s,i)}var Ce=C.changed||(k?!!C.actions.length||E||typeof k.value!=typeof C.value||!Gr(C.value,k.value):void 0);return C.changed=Ce,C.history=k,C},t.prototype.getStateNode=function(e){if(Ne(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Ne(e)?e.slice(Kt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Ne(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Mt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Pe;switch(this.type){case"parallel":return $e(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Pe});case"compound":if(U(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?$e(e,function(s,o){return s?n.getStateNode(o).resolve(s):Pe}):this.initialStateValue||{};default:return e||Pe}},t.prototype.getResolvedPath=function(e){if(Ne(e)){var r=this.machine.idMap[e.slice(Kt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Mt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=Sr(this.states,function(n){return n.initialStateValue||Pe},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=yt(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;U(r.target)?e=Ne(r.target)?at(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(yt(this))return[this];if(this.type==="compound"&&!this.initial)return K||J(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=ct(this.initialStateValue);return G(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=P(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:Sr(this.states,function(r,n){if(!e)return r.historyValue();var i=U(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?G(ct(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=fi(n.path,"states")(e).current;return U(s)?[n.getStateNode(s)]:G(ct(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=G(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var u=x(Object.keys(s)),c=u.next();!c.done;c=u.next()){var d=c.value,h=s[d];if(h.states)try{for(var l=(n=void 0,x(h.events)),a=l.next();!a.done;a=l.next()){var f=a.value;o.add("".concat(f))}}catch(v){n={error:v}}finally{try{a&&!a.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!U(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(u){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
-
`).concat(u.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Ti(e.target),i="internal"in e?e.internal:n?n.some(function(c){return U(c)&&c[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),u=m(m({},e),{actions:de(se(e.actions)),cond:Ir(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},u),{target:u.target?u.target.map(function(c){return"#".concat(c.id)}):void 0,source:"#".concat(r.id)})}});return u},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=ze,u=s[o],c=u===void 0?[]:u,d=_t(s,[typeof o=="symbol"?o:o+""]);i=G(Object.keys(d).map(function(T){!K&&T===_e&&J(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var b=Ae(T,d[T]);return K||ts(n,T,b),b}).concat(Ae(ze,c)))}var h=this.config.always?Ae("",this.config.always):[],l=this.config.onDone?Ae(String(Fe(this.id)),this.config.onDone):[];K||J(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var a=G(this.invoke.map(function(T){var b=[];return T.onDone&&b.push.apply(b,q([],P(Ae(String(He(T.id)),T.onDone)),!1)),T.onError&&b.push.apply(b,q([],P(Ae(String(Ie(T.id)),T.onError)),!1)),b})),f=this.after,v=G(q(q(q(q([],P(l),!1),P(a),!1),P(i),!1),P(h),!1).map(function(T){return se(T).map(function(b){return n.formatTransition(b)})}));try{for(var y=x(f),S=y.next();!S.done;S=y.next()){var w=S.value;v.push(w)}}catch(T){e={error:T}}finally{try{S&&!S.done&&(r=y.return)&&r.call(y)}finally{if(e)throw e.error}}return v},t}(),zr=!1;function ve(t,e){return!K&&!("predictableActionArguments"in t)&&!zr&&(zr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new rs(t,e)}var I=jr,X=me;/*! js-cookie v3.0.5 | MIT */function Et(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 ns={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Gt(t,e){function r(i,s,o){if(typeof document!="undefined"){o=Et({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var u="";for(var c in o)o[c]&&(u+="; "+c,o[c]!==!0&&(u+="="+o[c].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+u}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},u=0;u<s.length;u++){var c=s[u].split("="),d=c.slice(1).join("=");try{var h=decodeURIComponent(c[0]);if(o[h]=t.read(d,h),i===h)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",Et({},s,{expires:-1}))},withAttributes:function(i){return Gt(this.converter,Et({},this.attributes,i))},withConverter:function(i){return Gt(Et({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Bt=Gt(ns,{path:"/"}),zt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Yt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function is(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Wt={exports:{}};(function(t,e){(function(r){function n(i){var s=i&&i.Promise||r.Promise,o=i&&i.XMLHttpRequest||r.XMLHttpRequest;return function(){var u=Object.create(r,{fetch:{value:void 0,writable:!0}});return function(c,d){d(e)}(this,function(c){var d=typeof u!="undefined"&&u||typeof self!="undefined"&&self||typeof d!="undefined"&&d,h={searchParams:"URLSearchParams"in d,iterable:"Symbol"in d&&"iterator"in Symbol,blob:"FileReader"in d&&"Blob"in d&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in d,arrayBuffer:"ArrayBuffer"in d};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(h.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(p){return p&&a.indexOf(Object.prototype.toString.call(p))>-1};function v(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function y(p){return typeof p!="string"&&(p=String(p)),p}function S(p){var E={next:function(){var k=p.shift();return{done:k===void 0,value:k}}};return h.iterable&&(E[Symbol.iterator]=function(){return E}),E}function w(p){this.map={},p instanceof w?p.forEach(function(E,k){this.append(k,E)},this):Array.isArray(p)?p.forEach(function(E){this.append(E[0],E[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(E){this.append(E,p[E])},this)}w.prototype.append=function(p,E){p=v(p),E=y(E);var k=this.map[p];this.map[p]=k?k+", "+E:E},w.prototype.delete=function(p){delete this.map[v(p)]},w.prototype.get=function(p){return p=v(p),this.has(p)?this.map[p]:null},w.prototype.has=function(p){return this.map.hasOwnProperty(v(p))},w.prototype.set=function(p,E){this.map[v(p)]=y(E)},w.prototype.forEach=function(p,E){for(var k in this.map)this.map.hasOwnProperty(k)&&p.call(E,this.map[k],k,this)},w.prototype.keys=function(){var p=[];return this.forEach(function(E,k){p.push(k)}),S(p)},w.prototype.values=function(){var p=[];return this.forEach(function(E){p.push(E)}),S(p)},w.prototype.entries=function(){var p=[];return this.forEach(function(E,k){p.push([k,E])}),S(p)},h.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function T(p){if(p.bodyUsed)return s.reject(new TypeError("Already read"));p.bodyUsed=!0}function b(p){return new s(function(E,k){p.onload=function(){E(p.result)},p.onerror=function(){k(p.error)}})}function O(p){var E=new FileReader,k=b(E);return E.readAsArrayBuffer(p),k}function M(p){var E=new FileReader,k=b(E);return E.readAsText(p),k}function D(p){for(var E=new Uint8Array(p),k=new Array(E.length),H=0;H<E.length;H++)k[H]=String.fromCharCode(E[H]);return k.join("")}function _(p){if(p.slice)return p.slice(0);var E=new Uint8Array(p.byteLength);return E.set(new Uint8Array(p)),E.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:h.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:h.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:h.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():h.arrayBuffer&&h.blob&&l(p)?(this._bodyArrayBuffer=_(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||f(p))?this._bodyArrayBuffer=_(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):h.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},h.blob&&(this.blob=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return s.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return s.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=T(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?s.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):s.resolve(this._bodyArrayBuffer))}else return this.blob().then(O)}),this.text=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return M(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return s.resolve(this._bodyText)},h.formData&&(this.formData=function(){return this.text().then(F)}),this.json=function(){return this.text().then(JSON.parse)},this}var R=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function B(p){var E=p.toUpperCase();return R.indexOf(E)>-1?E:p}function A(p,E){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E=E||{};var k=E.body;if(p instanceof A){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,E.headers||(this.headers=new w(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!k&&p._bodyInit!=null&&(k=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=E.credentials||this.credentials||"same-origin",(E.headers||!this.headers)&&(this.headers=new w(E.headers)),this.method=B(E.method||this.method||"GET"),this.mode=E.mode||this.mode||null,this.signal=E.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&k)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(k),(this.method==="GET"||this.method==="HEAD")&&(E.cache==="no-store"||E.cache==="no-cache")){var H=/([?&])_=[^&]*/;if(H.test(this.url))this.url=this.url.replace(H,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}A.prototype.clone=function(){return new A(this,{body:this._bodyInit})};function F(p){var E=new FormData;return p.trim().split("&").forEach(function(k){if(k){var H=k.split("="),C=H.shift().replace(/\+/g," "),L=H.join("=").replace(/\+/g," ");E.append(decodeURIComponent(C),decodeURIComponent(L))}}),E}function z(p){var E=new w,k=p.replace(/\r?\n[\t ]+/g," ");return k.split("\r").map(function(H){return H.indexOf(`
|
|
20
|
-
`)===0?H.substr(1,H.length):H}).forEach(function(H){var C=H.split(":"),L=C.shift().trim();if(L){var Ce=C.join(":").trim();E.append(L,Ce)}}),E}$.call(A.prototype);function V(p,E){if(!(this instanceof V))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E||(E={}),this.type="default",this.status=E.status===void 0?200:E.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in E?E.statusText:"",this.headers=new w(E.headers),this.url=E.url||"",this._initBody(p)}$.call(V.prototype),V.prototype.clone=function(){return new V(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},V.error=function(){var p=new V(null,{status:0,statusText:""});return p.type="error",p};var we=[301,302,303,307,308];V.redirect=function(p,E){if(we.indexOf(E)===-1)throw new RangeError("Invalid status code");return new V(null,{status:E,headers:{location:p}})},c.DOMException=d.DOMException;try{new c.DOMException}catch{c.DOMException=function(E,k){this.message=E,this.name=k;var H=Error(E);this.stack=H.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function Te(p,E){return new s(function(k,H){var C=new A(p,E);if(C.signal&&C.signal.aborted)return H(new c.DOMException("Aborted","AbortError"));var L=new o;function Ce(){L.abort()}L.onload=function(){var W={status:L.status,statusText:L.statusText,headers:z(L.getAllResponseHeaders()||"")};W.url="responseURL"in L?L.responseURL:W.headers.get("X-Request-URL");var xt="response"in L?L.response:L.responseText;setTimeout(function(){k(new V(xt,W))},0)},L.onerror=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},L.ontimeout=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},L.onabort=function(){setTimeout(function(){H(new c.DOMException("Aborted","AbortError"))},0)};function ne(W){try{return W===""&&d.location.href?d.location.href:W}catch{return W}}L.open(C.method,ne(C.url),!0),C.credentials==="include"?L.withCredentials=!0:C.credentials==="omit"&&(L.withCredentials=!1),"responseType"in L&&(h.blob?L.responseType="blob":h.arrayBuffer&&C.headers.get("Content-Type")&&C.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(L.responseType="arraybuffer")),E&&typeof E.headers=="object"&&!(E.headers instanceof w)?Object.getOwnPropertyNames(E.headers).forEach(function(W){L.setRequestHeader(W,y(E.headers[W]))}):C.headers.forEach(function(W,xt){L.setRequestHeader(xt,W)}),C.signal&&(C.signal.addEventListener("abort",Ce),L.onreadystatechange=function(){L.readyState===4&&C.signal.removeEventListener("abort",Ce)}),L.send(typeof C._bodyInit=="undefined"?null:C._bodyInit)})}Te.polyfill=!0,d.fetch||(d.fetch=Te,d.Headers=w,d.Request=A,d.Response=V),c.Headers=w,c.Request=A,c.Response=V,c.fetch=Te,Object.defineProperty(c,"__esModule",{value:!0})}),{fetch:u.fetch,Headers:u.Headers,Request:u.Request,Response:u.Response,DOMException:u.DOMException}}()}t.exports=n})(typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:zt)})(Wt,Wt.exports);var ss=Wt.exports;const Jt=Yt(ss),Ue="nhostRefreshToken",Ye="nhostRefreshTokenId",Ee="nhostRefreshTokenExpiresAt",Yr=3,Wr=60,Xt=5,Qt=0,Zt=1,oe=10,De=20;let ye=class extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Zt,message:e.message}):(this.name=e.error,this.error=e)}};const ae={status:oe,error:"invalid-email",message:"Email is incorrectly formatted"},Jr={status:oe,error:"invalid-mfa-type",message:"MFA type is invalid"},Xr={status:oe,error:"invalid-mfa-code",message:"MFA code is invalid"},wt={status:oe,error:"invalid-password",message:"Password is incorrectly formatted"},er={status:oe,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:oe,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Zr={status:oe,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},en={status:oe,error:"no-refresh-token",message:"No refresh token has been provided"},tn={status:De,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},ee={status:De,error:"already-signed-in",message:"User is already signed in"},rn={status:De,error:"unauthenticated-user",message:"User is not authenticated"},os={status:De,error:"user-not-anonymous",message:"User is not anonymous"},nn={status:De,error:"unverified-user",message:"Email needs verification"},sn={status:oe,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},on={status:Zt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Tt={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function as(t){return new TextEncoder().encode(t)}function he(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function tr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let u=0;u<i.length;u++)o[u]=i.charCodeAt(u);return s}function an(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function cn(t){const{id:e}=t;return{...t,id:tr(e),transports:t.transports}}function un(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class Z extends Error{constructor({message:e,code:r,cause:n,name:i}){super(e,{cause:n}),this.name=i!=null?i:n.name,this.code=r}}function cs({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 instanceof AbortSignal)return new Z({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)==null?void 0:r.requireResidentKey)===!0)return new Z({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(((n=i.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new Z({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new Z({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Z({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(s=>s.type==="public-key").length===0?new Z({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Z({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(un(s)){if(i.rp.id!==s)return new Z({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Z({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Z({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new Z({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}class us{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ln=new us,ls=["cross-platform","platform"];function dn(t){if(t&&!(ls.indexOf(t)<0))return t}async function hn(t){var e;if(!an())throw new Error("WebAuthn is not supported in this browser");const r={publicKey:{...t,challenge:tr(t.challenge),user:{...t.user,id:as(t.user.id)},excludeCredentials:(e=t.excludeCredentials)==null?void 0:e.map(cn)}};r.signal=ln.createNewAbortSignal();let n;try{n=await navigator.credentials.create(r)}catch(a){throw cs({error:a,options:r})}if(!n)throw new Error("Registration was not completed");const{id:i,rawId:s,response:o,type:u}=n;let c;typeof o.getTransports=="function"&&(c=o.getTransports());let d;if(typeof o.getPublicKeyAlgorithm=="function")try{d=o.getPublicKeyAlgorithm()}catch(a){rr("getPublicKeyAlgorithm()",a)}let h;if(typeof o.getPublicKey=="function")try{const a=o.getPublicKey();a!==null&&(h=he(a))}catch(a){rr("getPublicKey()",a)}let l;if(typeof o.getAuthenticatorData=="function")try{l=he(o.getAuthenticatorData())}catch(a){rr("getAuthenticatorData()",a)}return{id:i,rawId:he(s),response:{attestationObject:he(o.attestationObject),clientDataJSON:he(o.clientDataJSON),transports:c,publicKeyAlgorithm:d,publicKey:h,authenticatorData:l},type:u,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:dn(n.authenticatorAttachment)}}function rr(t,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${t}. You should report this error to them.
|
|
21
|
-
`,e)}function ds(t){return new TextDecoder("utf-8").decode(t)}function hs(){const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable===void 0?new Promise(e=>e(!1)):t.isConditionalMediationAvailable()}function fs({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Z({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Z({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(un(n)){if(r.rpId!==n)return new Z({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Z({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Z({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}async function nr(t,e=!1){var r,n;if(!an())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)==null?void 0:r.length)!==0&&(i=(n=t.allowCredentials)==null?void 0:n.map(cn));const s={...t,challenge:tr(t.challenge),allowCredentials:i},o={};if(e){if(!await hs())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=ln.createNewAbortSignal();let u;try{u=await navigator.credentials.get(o)}catch(f){throw fs({error:f,options:o})}if(!u)throw new Error("Authentication was not completed");const{id:c,rawId:d,response:h,type:l}=u;let a;return h.userHandle&&(a=ds(h.userHandle)),{id:c,rawId:he(d),response:{authenticatorData:he(h.authenticatorData),clientDataJSON:he(h.clientDataJSON),signature:he(h.signature),userHandle:a},type:l,clientExtensionResults:u.getClientExtensionResults(),authenticatorAttachment:dn(u.authenticatorAttachment)}}const St=typeof window!="undefined",bt=new Map,ps=t=>{var e;return St&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=bt.get(t))!=null?e:null},vs=(t,e)=>{St&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?bt.set(t,e):bt.has(t)&&bt.delete(t)},fn=(t,e)=>{if(t==="localStorage"||t==="web")return ps;if(t==="cookie")return r=>{var n;return St&&(n=Bt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},pn=(t,e)=>{if(t==="localStorage"||t==="web")return vs;if(t==="cookie")return(r,n)=>{St&&(n?Bt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Bt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},We=t=>!t||!t.accessToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ie=({accessToken:t,refreshToken:e,isError:r,user:n,error:i})=>r?{session:null,error:i}:n&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:e,user:n},error:null}:{session:null,error:null},Je=()=>typeof window!="undefined"&&typeof window.location!="undefined";let vn=globalThis.fetch;typeof EdgeRuntime!="string"&&(vn=Jt().fetch);const yn=async(t,e,{token:r,body:n,extraHeaders:i}={})=>{const s={"Content-Type":"application/json",Accept:"*/*"};r&&(s.Authorization=`Bearer ${r}`);const o={...s,...i},u={method:e,headers:o};n&&(u.body=JSON.stringify(n));try{const c=await vn(t,u);if(!c.ok){const d=await c.json();return Promise.reject({error:d})}try{return{data:await c.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 c={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:c})}},te=async(t,e,r,n)=>yn(t,"POST",{token:r,body:e,extraHeaders:n}),gn=(t,e)=>yn(t,"GET",{token:e}),kt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},re=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),u=new URLSearchParams(o.search);let c=Object.fromEntries(u);r.startsWith("/")&&(c={...s,...c});let d=i.pathname;return o.pathname.length>1&&(d+=o.pathname.slice(1)),{...n,redirectTo:kt(o.origin+d,c)}};function Xe(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function ir(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const ce=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),At=t=>!!t&&typeof t=="string"&&t.length>=Yr,sr=t=>!!t&&typeof t=="string",mn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),En=({backendUrl:t,clientUrl:e,broadcastKey:r,clientStorageType:n="web",clientStorage:i,refreshIntervalTime:s,autoRefreshToken:o=!0,autoSignIn:u=!0})=>{const c=fn(n,i),d=pn(n,i),h=async(l,a,f,v)=>(await te(`${t}${l}`,a,f,v)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:Tt,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:["clearContextExceptTokens"],exit:["destroyAccessToken","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_SECURITY_KEY:"authenticating.securityKey",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat",SIGNIN_ID_TOKEN:"authenticating.idToken"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},idToken:{invoke:{src:"signInIdToken",id:"authenticateWithIdToken",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},securityKey:{invoke:{src:"signInSecurityKey",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{cond:"isUnauthorizedError",target:"#nhost.authentication.signedOut"},{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",SIGNIN_EMAIL_OTP:"signInEmailOTP",VERIFY_EMAIL_OTP:"verifyEmailOTP"},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"}}},signInEmailOTP:{entry:["resetErrors"],invoke:{src:"signInEmailOTP",id:"signInEmailOTP",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},verifyEmailOTP:{entry:["resetErrors"],invoke:{src:"verifyEmailOTP",id:"verifyEmailOTP",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:I({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:I(()=>(d(Ee,null),d(Ue,null),d(Ye,null),{...Tt})),clearContextExceptTokens:I(({accessToken:l,refreshToken:a})=>({...Tt,accessToken:l,refreshToken:a})),saveSession:I({user:(l,{data:a})=>{var f;return((f=a==null?void 0:a.session)==null?void 0:f.user)||null},accessToken:(l,{data:a})=>{if(a.session){const{accessTokenExpiresIn:f,accessToken:v}=a.session,y=new Date(Date.now()+f*1e3);return d(Ee,y.toISOString()),{value:v,expiresAt:y,expiresInSeconds:f}}return d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(l,{data:a})=>{var f,v;const y=((f=a.session)==null?void 0:f.refreshToken)||null,S=((v=a.session)==null?void 0:v.refreshTokenId)||null;return y&&d(Ue,y),S&&d(Ye,S),{value:y}}}),savePATSession:I({user:(l,{data:a})=>{var f;return((f=a==null?void 0:a.session)==null?void 0:f.user)||null},accessToken:(l,{data:a})=>{if(a.session){const{accessTokenExpiresIn:f,accessToken:v}=a.session,y=new Date(Date.now()+f*1e3);return d(Ee,y.toISOString()),{value:v,expiresAt:y,expiresInSeconds:f}}return d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(l,{data:a})=>{var f,v;const y=((f=a.session)==null?void 0:f.refreshToken)||null,S=((v=a.session)==null?void 0:v.refreshTokenId)||null;return y&&d(Ue,y),S&&d(Ye,S),{value:y,isPAT:!0}}}),saveMfaTicket:I({mfa:(l,a)=>{var f;return(f=a.data)==null?void 0:f.mfa}}),resetTimer:I({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:I({refreshTimer:(l,a)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:I({errors:({errors:l},{data:{error:a}})=>({...l,authentication:a})}),resetErrors:I({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:I({errors:({errors:l},{data:{error:a}})=>({...l,registration:a})}),destroyRefreshToken:I({refreshToken:l=>(d(Ue,null),d(Ye,null),{value:null})}),destroyAccessToken:I({accessToken:l=>(d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null})}),cleanUrl:()=>{u&&Xe("refreshToken")&&(ir("refreshToken"),ir("type"))},broadcastToken:l=>{if(u&&r)try{new BroadcastChannel(r).postMessage({type:"broadcast_token",payload:{token:l.refreshToken.value}})}catch{}}},guards:{isAnonymous:(l,a)=>{var f;return!!((f=l.user)!=null&&f.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,isRefreshTokenPAT:l=>{var a;return!!((a=l.refreshToken)!=null&&a.isPAT)},hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{const{expiresAt:a}=l.accessToken;if(!a)return!1;if(l.refreshTimer.lastAttempt)return l.refreshTimer.attempts>Xt?!1:Date.now()-l.refreshTimer.lastAttempt.getTime()>Math.pow(2,l.refreshTimer.attempts-1)*5e3;if(a.getTime()<Date.now()||s&&Date.now()-l.refreshTimer.startedAt.getTime()>s*1e3)return!0;const f=l.accessToken.expiresInSeconds;return f?a.getTime()-Date.now()-1e3*Math.min(Wr,f*.5)<=0:!1},shouldRetryImportToken:(l,a)=>l.importTokenAttempts<Xt&&(a.data.error.status===Qt||a.data.error.status>=500),unverified:(l,{data:{error:a}})=>a.status===401&&(a.message==="Email is not verified"||a.error==="unverified-user"),hasSession:(l,a)=>{var f;return!!((f=a.data)!=null&&f.session)},hasMfaTicket:(l,a)=>{var f;return!!((f=a.data)!=null&&f.mfa)},isUnauthorizedError:(l,{data:{error:a}})=>a.status===401},services:{signInPassword:(l,{email:a,password:f})=>ce(a)?At(f)?h("/signin/email-password",{email:a,password:f}):Promise.reject({error:wt}):Promise.reject({error:ae}),signInPAT:(l,{pat:a})=>h("/signin/pat",{personalAccessToken:a}),signInIdToken:(l,{provider:a,idToken:f,nonce:v})=>h("/signin/idtoken",{provider:a,idToken:f,...v&&{nonce:v}}),passwordlessSms:(l,{phoneNumber:a,options:f})=>{var v;return sr(a)?(v=l.user)!=null&&v.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:a,options:re(e,f)},l.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:a,options:re(e,f)}):Promise.reject({error:er})},passwordlessSmsOtp:(l,{phoneNumber:a,otp:f})=>sr(a)?h("/signin/passwordless/sms/otp",{phoneNumber:a,otp:f}):Promise.reject({error:er}),signInEmailOTP:(l,{email:a,options:f})=>ce(a)?h("/signin/otp/email",{email:a,options:re(e,f)}):Promise.reject({error:ae}),verifyEmailOTP:(l,{email:a,otp:f})=>ce(a)?h("/signin/otp/email/verify",{email:a,otp:f}):Promise.reject({error:ae}),passwordlessEmail:(l,{email:a,options:f})=>{var v;return ce(a)?(v=l.user)!=null&&v.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:a,options:re(e,f)},l.accessToken.value):h("/signin/passwordless/email",{email:a,options:re(e,f)}):Promise.reject({error:ae})},signInAnonymous:l=>h("/signin/anonymous"),signInMfaTotp:(l,a)=>{var f;const v=a.ticket||((f=l.mfa)==null?void 0:f.ticket);return v?mn(v)?h("/signin/mfa/totp",{ticket:v,otp:a.otp}):Promise.reject({error:Qr}):Promise.reject({error:Zr})},signInSecurityKeyEmail:async(l,{email:a})=>{if(!ce(a))throw new ye(ae);const f=await h("/signin/webauthn",{email:a});let v;try{v=await nr(f)}catch(y){throw new ye(y)}return h("/signin/webauthn/verify",{email:a,credential:v})},refreshToken:async(l,a)=>{const f=a.type==="TRY_TOKEN"?a.token:l.refreshToken.value;return{session:await h("/token",{refreshToken:f}),error:null}},signInSecurityKey:async()=>{try{const l=await h("/signin/webauthn",{});let a;try{a=await nr(l)}catch(f){throw new ye(f)}return h("/signin/webauthn/verify",{credential:a})}catch(l){throw new ye(l)}},signout:async(l,a)=>{const f=await h("/signout",{refreshToken:l.refreshToken.value,all:!!a.all},a.all?l.accessToken.value:void 0);if(r)try{new BroadcastChannel(r).postMessage({type:"signout"})}catch{}return f},signUpEmailPassword:async(l,{email:a,password:f,options:v,requestOptions:y})=>{var S;return ce(a)?At(f)?(S=l.user)!=null&&S.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:a,password:f,options:re(e,v)},l.accessToken.value,y==null?void 0:y.headers):h("/signup/email-password",{email:a,password:f,options:re(e,v)},null,y==null?void 0:y.headers):Promise.reject({error:wt}):Promise.reject({error:ae})},signUpSecurityKey:async(l,{email:a,options:f})=>{if(!ce(a))return Promise.reject({error:ae});const v=f==null?void 0:f.nickname;v&&delete f.nickname;const y=await h("/signup/webauthn",{email:a,options:f});let S;try{S=await hn(y)}catch(w){throw new ye(w)}return h("/signup/webauthn/verify",{credential:S,options:{redirectTo:f==null?void 0:f.redirectTo,nickname:v}})},importRefreshToken:async l=>{if(l.user&&l.refreshToken.value&&l.accessToken.value&&l.accessToken.expiresAt)return{session:{accessToken:l.accessToken.value,accessTokenExpiresIn:l.accessToken.expiresAt.getTime()-Date.now(),refreshToken:l.refreshToken.value,user:l.user},error:null};let a=null;if(u){const v=Xe("refreshToken")||null;if(v)try{return{session:await h("/token",{refreshToken:v}),error:null}}catch(y){a=y.error}else{const y=Xe("error"),S=Xe("errorDescription");if(y&&S!=="social user already exists")return Promise.reject({session:null,error:{status:oe,error:y,message:S||y}})}}const f=await c(Ue);if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(v){a=v.error}return a?Promise.reject({error:a,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>Math.pow(2,l-1)*5e3}})},wn=({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:I({error:n=>ae}),saveRequestError:I({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ce(i)},services:{requestChange:async(n,{email:i,options:s})=>(await te(`${t}/user/email/change`,{newEmail:i,options:re(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),Tn=({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:I({error:r=>wt}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!At(n)},services:{requestChange:(r,{password:n,ticket:i})=>te(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ys=({backendUrl:t,interpreter:e})=>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:I({error:r=>Jr}),saveInvalidMfaCodeError:I({error:r=>Xr}),saveError:I({error:(r,{data:{error:n}})=>n}),saveGeneration:I({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:X((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS"),reportGeneratedSuccess:X("GENERATED"),reportGeneratedError:X(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await gn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>te(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Sn=({backendUrl:t,clientUrl:e})=>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:I({error:r=>ae}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ce(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:re(e,i)})}}),bn=({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:I({error:r=>ae}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ce(n)},services:{request:async(r,{email:n,options:i})=>(await te(`${t}/user/email/send-verification-email`,{email:n,options:re(e,i)})).data}});class or{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,broadcastKey:u,devTools:c,...d}){var h;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=En({...d,backendUrl:s,clientUrl:o,broadcastKey:u,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:c}),typeof window!="undefined"&&u)try{this._channel=new BroadcastChannel(u),r&&((h=this._channel)==null||h.addEventListener("message",l=>{var a;const{type:f,payload:v}=l.data;if(f==="broadcast_token"){const y=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&v.token&&v.token!==y&&this.interpreter.send("TRY_TOKEN",{token:v.token})}})),this._channel.addEventListener("message",l=>{const{type:a}=l.data;a==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context,accessToken:{...this.machine.context.accessToken},refreshToken:{...this.machine.context.refreshToken}};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||xe(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class kn extends or{constructor({...e}){super({...e,autoSignIn:Je()&&e.autoSignIn,autoRefreshToken:Je()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const gs=kn,An=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await te(`${t}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await hn(n)}catch(o){throw new ye(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},On=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),In=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),ms=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),Es=(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})})}),Rn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),xn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),_n=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value,refreshToken:n.context.refreshToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),Pn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),Nn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),Un=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:u}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let c;try{c=await nr(u)}catch(d){throw new ye(d)}try{const{data:{session:d},error:h}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:c},o);d&&!h&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:d}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(d){const{error:h}=d;r({error:h,isError:!0,isSuccess:!1,elevated:!1})}}),Dn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ee,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Cn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),cr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Mn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Ln=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:rn});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),ur=(t,e,r,n,i)=>new Promise(s=>{const{changed:o,context:u}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n,requestOptions:i});if(!o)return s({error:ee,accessToken:u.accessToken.value,refreshToken:u.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:u.user});t.onTransition(c=>{c.matches("registration.incomplete.failed")?s({accessToken:null,refreshToken:null,error:c.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?s({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):c.matches({authentication:"signedIn",registration:"complete"})&&s({accessToken:c.context.accessToken.value,refreshToken:c.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:c.context.user})})}),jn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r});if(!i)return n({error:ee,accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),$n=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("SIGNIN_EMAIL_OTP",{email:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!0,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Fn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"VERIFY_EMAIL_OTP",email:e,otp:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Hn=(t,{provider:e,idToken:r,nonce:n})=>new Promise(i=>{const{changed:s}=t.send("SIGNIN_ID_TOKEN",{provider:e,idToken:r,...n&&{nonce:n}});s||i({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(o=>{if(o.matches({authentication:{signedOut:"failed"}}))return i({accessToken:null,refreshToken:null,user:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1});if(o.matches({authentication:"signedIn"}))return i({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,user:o.context.user,error:null,isError:!1,isSuccess:!0})})}),qn=async({backendUrl:t,interpreter:e},{provider:r,idToken:n,nonce:i})=>{try{return await te(`${t}/link/idtoken`,{provider:r,idToken:n,...i&&{nonce:i}},e==null?void 0:e.getSnapshot().context.accessToken.value),{isError:!1,error:null,isSuccess:!0}}catch(s){const{error:o}=s;return{isError:!0,error:o,isSuccess:!1}}},Vn=t=>new Promise(e=>{const{changed:r,context:n}=t.send({type:"SIGNIN_SECURITY_KEY"});if(!r)return e({accessToken:n.accessToken.value,refreshToken:n.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:n.user});t.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?e({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?e({accessToken:null,refreshToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&e({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),ws=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.toISOString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1,data:null}}};class Kn{constructor({url:e,broadcastKey:r,autoRefreshToken:n=!0,autoSignIn:i=!0,clientStorage:s,clientStorageType:o,refreshIntervalTime:u,start:c=!0}){var d;this.url=e,this._client=new or({backendUrl:e,clientUrl:typeof window!="undefined"&&((d=window.location)==null?void 0:d.origin)||"",broadcastKey:r,autoRefreshToken:n,autoSignIn:i,start:c,clientStorage:s,clientStorageType:o,refreshIntervalTime:u})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?ie(await jn(r,n,i)):ie(await ur(r,n,e.password,i))}async connectProvider(e){const r=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:n,options:i}=e,s=kt(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,{...i,connect:r}));return Je()&&(window.location.href=s),{providerUrl:s}}async signInIdToken(e){const r=await this.waitUntilReady(),n=await Hn(r,e);return{...ie(n),mfa:null}}async linkIdToken(e){return qn(this._client,e)}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await _n(r);return{...ie(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=kt(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,i));return Je()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Pn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:nn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ie(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Nn(r,e.email);return{...ie(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await ar(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Mn(r,e.phoneNumber,e.otp);return{...ie(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await cr(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Dn(r,e.otp,e.ticket);return{...ie(n),mfa:null}}return{error:on,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Cn(r,e);return ie(n)}async signInEmailOTP(e,r){const n=await this.waitUntilReady(),{error:i}=await $n(n,e,r);return{error:i,session:null,mfa:null}}async verifyEmailOTP(e,r){const n=await this.waitUntilReady(),i=await Fn(n,e,r);return{...ie(i),mfa:null}}async signInSecurityKey(){const e=await this.waitUntilReady(),r=await Vn(e);return{...ie(r),mfa:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await Ln(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(Sn(this._client)).start(),{error:i}=await Rn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(Tn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(bn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(wn(this._client)).start(),{error:i}=await On(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await ar(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await cr(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await ur(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await An(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Un(this._client,e),mfa:null}}async createPAT(e,r){return ws(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(We(s))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,We(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?pr(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:en});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:tn});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:sn}):o.event.type==="TOKEN_CHANGED"&&n({session:We(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return We((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}async initWithSession({session:e}){this.client.start({initialSession:e}),await this.waitUntilReady()}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Ts=typeof self=="object"?self.FormData:window.FormData;const lr=Yt(Ts);let Gn=globalThis.fetch;const dr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u,headers:c={}}={})=>{var d;const h={...c};s&&e.append("bucket-id",s),o&&(h["x-hasura-admin-secret"]=o),r&&(h.Authorization=`Bearer ${r}`);const l=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof lr&&(Gn=Jt().fetch);const a=await Gn(l,{method:"POST",headers:h,body:e}),f=await a.json();return a.ok?{fileMetadata:f,error:null}:{error:{status:a.status,message:((d=f==null?void 0:f.error)==null?void 0:d.message)||a.statusText,error:a.statusText},fileMetadata:null}}catch(a){return{error:{status:0,message:a.message,error:a.message},fileMetadata:null}}return new Promise(a=>{let f=new XMLHttpRequest;f.responseType="json",f.onload=()=>{var v,y,S,w,T,b,O,M;if(f.status<200||f.status>=300){const D={error:(T=(w=(y=(v=f.response)==null?void 0:v.error)==null?void 0:y.message)!=null?w:(S=f.response)==null?void 0:S.error)!=null?T:f.response,message:(M=(O=(b=f.response)==null?void 0:b.error)==null?void 0:O.message)!=null?M:f.response,status:f.status};return a({fileMetadata:null,error:D})}return a({fileMetadata:f.response,error:null})},f.onerror=()=>{const v={error:f.statusText,message:f.statusText,status:f.status};return a({fileMetadata:null,error:v})},u&&f.upload.addEventListener("progress",u,!1),f.open("POST",l,!0),Object.entries(h).forEach(([v,y])=>{f.setRequestHeader(v,y)}),f.send(e)})};function Ot(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}let Qe;typeof Qe=="undefined"&&(Qe=Jt().fetch);class Bn{constructor({url:e}){this.headers={},this.url=e}async uploadFormData({formData:e,bucketId:r,headers:n}){const{error:i,fileMetadata:s}=await dr(this.url,e,{bucketId:r,headers:{...this.headers,...n},accessToken:this.accessToken,adminSecret:this.adminSecret});return i?{fileMetadata:null,error:i}:s&&!("processedFiles"in s)?{fileMetadata:{processedFiles:[s]},error:null}:{fileMetadata:s,error:null}}async uploadFile({file:e,bucketId:r,id:n,name:i,headers:s}){const o=typeof window=="undefined"?new lr:new FormData;o.append("file[]",e),o.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:u,fileMetadata:c}=await dr(this.url,o,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:r,fileId:n,name:i,headers:{...this.headers,...s}});return u?{fileMetadata:null,error:u}:c&&"processedFiles"in c?{fileMetadata:c.processedFiles[0],error:null}:{fileMetadata:c,error:null}}async downloadFile(e){try{const{fileId:r,headers:n,...i}=e,s=Ot(`${this.url}/files/${r}`,i),o=await Qe(s,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!o.ok)throw new Error(await o.text());return{file:await o.blob(),error:null}}catch(r){return{file:null,error:r}}}async getPresignedUrl(e){try{const{fileId:r,headers:n}=e,i=await Qe(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!i.ok)throw new Error(await i.text());return{presignedUrl:await i.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r,headers:n}=e,i=await Qe(`${this.url}/files/${r}`,{method:"DELETE",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!i.ok)throw new Error(await i.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}getHeaders(){return this.headers}setHeaders(e){return e?(this.headers={...this.headers,...e},this):this}unsetHeaders(){const e=this.headers["x-hasura-role"];return this.headers=e?{"x-hasura-role":e}:{},this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class zn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Bn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return Ot(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,headers:n,...i}=e,{presignedUrl:s,error:o}=await this.api.getPresignedUrl(e);if(o)return{presignedUrl:null,error:o};if(!s)return{presignedUrl:null,error:new Error("Invalid file id")};const u=Ot(s.url,i);return{presignedUrl:{...s,url:u},error:null}}async download(e){const{file:r,error:n}=await this.api.downloadFile(e);return n?{file:null,error:n}:r?{file:r,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}getHeaders(){return this.api.getHeaders()}setHeaders(e){return this.api.setHeaders(e),this}unsetHeaders(){return this.api.unsetHeaders(),this}}let hr;typeof hr=="undefined"&&(hr=lr);const It={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Yn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...It},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:I({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:I({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:I({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:I({progress:t=>null,loaded:t=>0}),resetContext:I(t=>It),addFile:I({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new hr;i.append("file[]",n);let s=0;return dr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o&&!("processedFiles"in o)){const{id:c,bucketId:d}=o;r({type:"UPLOAD_DONE",id:c,bucketId:d})}if(o&&"processedFiles"in o){const{id:c,bucketId:d}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:c,bucketId:d})}}),()=>{}}}}),{pure:fr,sendParent:Rt}=Di,Ss=()=>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:I((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:I({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:I({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:I({loaded:t=>0}),startProgress:I({progress:t=>0}),resetProgress:I({progress:t=>null}),addItem:I((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,u)=>o+u.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Qi(Yn().withConfig({actions:{sendProgress:Rt((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:Rt("UPLOAD_DONE"),sendError:Rt("UPLOAD_ERROR"),sendDestroy:Rt("REMOVE")}}).withContext({...It,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:I({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:fr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:fr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:fr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),bs=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),ks=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),As=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Ze(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(As);if(i!=null&&i.groups){const{protocol:s,host:o,port:u}=i.groups,c=Rs(e);return c||(o==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${s||"http"}://localhost:${u||1337}/v1/${e}`):u?`${s||"https"}://local.${e}.nhost.run:${u}/v1`:`${s||"https"}://local.${e}.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${e}.${n}.nhost.run/v1`}function Os(){return typeof window!="undefined"}function Is(){return typeof process!="undefined"&&process.env}function Rs(t){return Os()||!Is()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function xs(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Wn(t){const e="subdomain"in t?Ze(t,"auth"):t.authUrl,{subdomain:r,region:n}=t;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Kn({url:e,broadcastKey:`${r}${n!=null?n:"local"}`,...t})}function _s(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],u={},c=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:c,headers:{keys:function(){return s},entries:function(){return o},get:function(h){return u[h.toLowerCase()]},has:function(h){return h.toLowerCase()in u}}}};for(var d in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(h,l,a){s.push(l=l.toLowerCase()),o.push([l,a]),u[l]=u[l]?u[l]+","+a:a}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(d,e.headers[d]);i.send(e.body||null)})}const Jn=is(Object.freeze(Object.defineProperty({__proto__:null,default:_s},Symbol.toStringTag,{value:"Module"})));var Ps=self.fetch||(self.fetch=Jn.default||Jn);const Xn=Yt(Ps);function Qn(t){const e="subdomain"in t?Ze(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Zn({url:e,...t})}class Zn{constructor(e){this.headers={};const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,u;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers,...this.headers},s=xs(this.url,e);try{const c=await Xn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let h;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?h=await c.json():h=await c.text(),{res:null,error:{message:h,error:c.statusText,status:c.status}}}let d;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?d=await c.json():d=await c.text(),{res:{data:d,status:c.status,statusText:c.statusText},error:null}}catch(c){const d=c;return{res:null,error:{message:d.message,status:d.name==="AbortError"?0:500,error:d.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Ns(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function ei(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 Us(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=ei(n)}catch{}return{query:t,operationName:r}}const e=ei(t);return{query:Se.print(t),operationName:e}}class Ds{constructor(e){this.headers={},this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const i=pr(this.accessToken);return i.exp!=null&&i.exp*1e3>Date.now()}catch(i){return console.error("Error decoding token:",i),!1}},this.awaitForValidAccessTokenOrNull=async()=>{if(this.isAccessTokenValidOrNull())return!0;const i=()=>this.isAccessTokenValidOrNull()?Promise.resolve(!0):new Promise(s=>{setTimeout(()=>i().then(s),100)});return i()};const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=Ns(e,n,i),{headers:o,...u}=i||{},{query:c,operationName:d}=Us(s.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const h=await Xn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:d,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...o},...u});if(!h.ok)return{data:null,error:{error:h.statusText,message:h.statusText,status:h.status}};const{data:l,errors:a}=await h.json();return a?{data:null,error:a}: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(h){const l=h;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}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ti(t){const e="subdomain"in t?Ze(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Ds({url:e,...t})}function ri(t){const e="subdomain"in t?Ze(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new zn({url:e,...t})}const Cs=t=>new ni(t);class ni{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...d}){this.auth=Wn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...d}),this.storage=ri({adminSecret:o,...d}),this.functions=Qn({adminSecret:o,...d}),this.graphql=ti({adminSecret:o,...d}),this.auth.onAuthStateChanged((h,l)=>{if(h==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const a=l==null?void 0:l.accessToken;this.storage.setAccessToken(a),this.functions.setAccessToken(a),this.graphql.setAccessToken(a)}),this.auth.onTokenChanged(h=>{const l=h==null?void 0:h.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}setRole(e){this.graphql.setHeaders({"x-hasura-role":e}),this.storage.setHeaders({"x-hasura-role":e}),this.functions.setHeaders({"x-hasura-role":e})}unsetRole(){this.graphql.setHeaders((({"x-hasura-role":e,...r})=>r)(this.graphql.getHeaders())),this.storage.setHeaders((({"x-hasura-role":e,...r})=>r)(this.storage.getHeaders())),this.functions.setHeaders((({"x-hasura-role":e,...r})=>r)(this.functions.getHeaders()))}}g.AuthClient=or,g.AuthClientSSR=gs,g.AuthCookieClient=kn,g.CodifiedError=ye,g.EMAIL_NEEDS_VERIFICATION=nn,g.HasuraAuthClient=Kn,g.HasuraStorageApi=Bn,g.HasuraStorageClient=zn,g.INITIAL_FILE_CONTEXT=It,g.INITIAL_MACHINE_CONTEXT=Tt,g.INVALID_EMAIL_ERROR=ae,g.INVALID_MFA_CODE_ERROR=Xr,g.INVALID_MFA_TICKET_ERROR=Qr,g.INVALID_MFA_TYPE_ERROR=Jr,g.INVALID_PASSWORD_ERROR=wt,g.INVALID_PHONE_NUMBER_ERROR=er,g.INVALID_REFRESH_TOKEN=sn,g.INVALID_SIGN_IN_METHOD=on,g.MIN_PASSWORD_LENGTH=Yr,g.NETWORK_ERROR_CODE=Qt,g.NHOST_JWT_EXPIRES_AT_KEY=Ee,g.NHOST_REFRESH_TOKEN_ID_KEY=Ye,g.NHOST_REFRESH_TOKEN_KEY=Ue,g.NO_MFA_TICKET_ERROR=Zr,g.NO_REFRESH_TOKEN=en,g.NhostClient=ni,g.NhostFunctionsClient=Zn,g.OTHER_ERROR_CODE=Zt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Xt,g.STATE_ERROR_CODE=De,g.TOKEN_REFRESHER_RUNNING_ERROR=tn,g.TOKEN_REFRESH_MARGIN_SECONDS=Wr,g.USER_ALREADY_SIGNED_IN=ee,g.USER_NOT_ANONYMOUS=os,g.USER_UNAUTHENTICATED=rn,g.VALIDATION_ERROR_CODE=oe,g.activateMfaPromise=Es,g.addSecurityKeyPromise=An,g.appendImageTransformationParameters=Ot,g.changeEmailPromise=On,g.changePasswordPromise=In,g.createAuthClient=Wn,g.createAuthMachine=En,g.createChangeEmailMachine=wn,g.createChangePasswordMachine=Tn,g.createEnableMfaMachine=ys,g.createFileUploadMachine=Yn,g.createFunctionsClient=Qn,g.createGraphqlClient=ti,g.createMultipleFilesUploadMachine=Ss,g.createNhostClient=Cs,g.createResetPasswordMachine=Sn,g.createSendVerificationEmailMachine=bn,g.createStorageClient=ri,g.elevateEmailSecurityKeyPromise=Un,g.encodeQueryParameters=kt,g.generateQrCodePromise=ms,g.getAuthenticationResult=ie,g.getFetch=gn,g.getParameterByName=Xe,g.getSession=We,g.isBrowser=Je,g.isValidEmail=ce,g.isValidPassword=At,g.isValidPhoneNumber=sr,g.isValidTicket=mn,g.linkIdTokenPromise=qn,g.localStorageGetter=fn,g.localStorageSetter=pn,g.postFetch=te,g.removeParameterFromWindow=ir,g.resetPasswordPromise=Rn,g.rewriteRedirectTo=re,g.sendVerificationEmailPromise=xn,g.signInAnonymousPromise=_n,g.signInEmailOTPPromise=$n,g.signInEmailPasswordPromise=Pn,g.signInEmailPasswordlessPromise=ar,g.signInEmailSecurityKeyPromise=Nn,g.signInIdTokenPromise=Hn,g.signInMfaTotpPromise=Dn,g.signInPATPromise=Cn,g.signInSecurityKeyPromise=Vn,g.signInSmsPasswordlessOtpPromise=Mn,g.signInSmsPasswordlessPromise=cr,g.signOutPromise=Ln,g.signUpEmailPasswordPromise=ur,g.signUpEmailSecurityKeyPromise=jn,g.uploadFilePromise=bs,g.uploadMultipleFilesPromise=ks,g.urlFromSubdomain=Ze,g.verifyEmailOTPPromise=Fn,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
16
|
+
Event: `).concat(JSON.stringify(a.data)));return n.scheduler.schedule(function(){n.forward(a);var f=n._nextState(a);n.update(f,a)}),n._state},this.sendTo=function(h,l,a){var f=n.parent&&(l===fe.Parent||n.parent.id===l),v=f?n.parent:U(l)?l===fe.Internal?n:n.children.get(l)||Be.get(l):Ei(l)?l:void 0;if(!v){if(!f)throw new Error("Unable to send event to child '".concat(l,"' from service '").concat(n.id,"'."));K||J(!1,"Service '".concat(n.id,"' has no parent: unable to send event ").concat(h.type));return}if("machine"in v){if(n.status!==Y.Stopped||n.parent!==v||n.state.done){var y=m(m({},h),{name:h.name===Ut?"".concat(Ie(n.id)):h.name,origin:n.sessionId});!a&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,y]):v.send(y)}}else!a&&n.machine.config.predictableActionArguments?n._outgoingQueue.push([v,h.data]):v.send(h.data)},this._exec=function(h,l,a,f){f===void 0&&(f=n.machine.options.actions);var v=h.exec||ft(h.type,f),y=N(v)?v:v?v.exec:h.exec;if(y)try{return y(l,a.data,n.machine.config.predictableActionArguments?{action:h,_event:a}:{action:h,state:n.state,_event:a})}catch(V){throw n.parent&&n.parent.send({type:"xstate.error",data:V}),V}switch(h.type){case be:{var S=h;n.defer(S);break}case Le:var w=h;if(typeof w.delay=="number"){n.defer(w);return}else w.to?n.sendTo(w._event,w.to,a===ge):n.send(w._event);break;case Pt:n.cancel(h.sendId);break;case et:{if(n.status!==Y.Running)return;var T=h.activity;if(!n.machine.config.predictableActionArguments&&!n.state.activities[T.id||T.type])break;if(T.type===j.Invoke){var b=xr(T.src),O=n.machine.options.services?n.machine.options.services[b.type]:void 0,M=T.id,D=T.data;K||J(!("forward"in T),"`forward` property is deprecated (found in invocation of '".concat(T.src,"' in in machine '").concat(n.machine.id,"'). ")+"Please use `autoForward` instead.");var _="autoForward"in T?T.autoForward:!!T.forward;if(!O){K||J(!1,"No service found for invocation '".concat(T.src,"' in machine '").concat(n.machine.id,"'."));return}var $=D?ut(D,l,a):void 0;if(typeof O=="string")return;var R=N(O)?O(l,a.data,{data:$,src:b,meta:T.meta}):O;if(!R)return;var B=void 0;le(R)&&(R=$?R.withContext($):R,B={autoForward:_}),n.spawn(R,M,B)}else n.spawnActivity(T);break}case tt:{n.stopChild(h.activity.id);break}case nt:var A=h,F=A.label,z=A.value;F?n.logger(F,z):n.logger(z);break;default:K||J(!1,"No implementation found for action type '".concat(h.type,"'"));break}};var i=m(m({},t.defaultOptions),r),s=i.clock,o=i.logger,c=i.parent,u=i.id,d=u!==void 0?u:e.id;this.id=d,this.logger=o,this.clock=s,this.parent=c,this.options=i,this.scheduler=new Br({deferEvents:this.options.deferEvents}),this.sessionId=Be.bookId()}return Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this;return this._initialState?this._initialState:Re(this,function(){return e._initialState=e.machine.initialState,e._initialState})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return K||J(this.status!==Y.NotStarted,"Attempted to read state from uninitialized service '".concat(this.id,"'. Make sure the service is started first.")),this._state},enumerable:!1,configurable:!0}),t.prototype.execute=function(e,r){var n,i;try{for(var s=x(e.actions),o=s.next();!o.done;o=s.next()){var c=o.value;this.exec(c,e,r)}}catch(u){n={error:u}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}},t.prototype.update=function(e,r){var n,i,s,o,c,u,d,h,l=this;if(e._sessionid=this.sessionId,this._state=e,(!this.machine.config.predictableActionArguments||r===ge)&&this.options.execute)this.execute(this.state);else for(var a=void 0;a=this._outgoingQueue.shift();)a[0].send(a[1]);if(this.children.forEach(function(R){l.state.children[R.id]=R}),this.devTools&&this.devTools.send(r.data,e),e.event)try{for(var f=x(this.eventListeners),v=f.next();!v.done;v=f.next()){var y=v.value;y(e.event)}}catch(R){n={error:R}}finally{try{v&&!v.done&&(i=f.return)&&i.call(f)}finally{if(n)throw n.error}}try{for(var S=x(this.listeners),w=S.next();!w.done;w=S.next()){var y=w.value;y(e,e.event)}}catch(R){s={error:R}}finally{try{w&&!w.done&&(o=S.return)&&o.call(S)}finally{if(s)throw s.error}}try{for(var T=x(this.contextListeners),b=T.next();!b.done;b=T.next()){var O=b.value;O(this.state.context,this.state.history?this.state.history.context:void 0)}}catch(R){c={error:R}}finally{try{b&&!b.done&&(u=T.return)&&u.call(T)}finally{if(c)throw c.error}}if(this.state.done){var M=e.configuration.find(function(R){return R.type==="final"&&R.parent===l.machine}),D=M&&M.doneData?ut(M.doneData,e.context,r):void 0;this._doneEvent=He(this.id,D);try{for(var _=x(this.doneListeners),$=_.next();!$.done;$=_.next()){var y=$.value;y(this._doneEvent)}}catch(R){d={error:R}}finally{try{$&&!$.done&&(h=_.return)&&h.call(_)}finally{if(d)throw d.error}}this._stop(),this._stopChildren(),Be.free(this.sessionId)}},t.prototype.onTransition=function(e){return this.listeners.add(e),this.status===Y.Running&&e(this.state,this.state.event),this},t.prototype.subscribe=function(e,r,n){var i=this,s=dt(e,r,n);this.listeners.add(s.next),this.status!==Y.NotStarted&&s.next(this.state);var o=function(){i.doneListeners.delete(o),i.stopListeners.delete(o),s.complete()};return this.status===Y.Stopped?s.complete():(this.onDone(o),this.onStop(o)),{unsubscribe:function(){i.listeners.delete(s.next),i.doneListeners.delete(o),i.stopListeners.delete(o)}}},t.prototype.onEvent=function(e){return this.eventListeners.add(e),this},t.prototype.onSend=function(e){return this.sendListeners.add(e),this},t.prototype.onChange=function(e){return this.contextListeners.add(e),this},t.prototype.onStop=function(e){return this.stopListeners.add(e),this},t.prototype.onDone=function(e){return this.status===Y.Stopped&&this._doneEvent?e(this._doneEvent):this.doneListeners.add(e),this},t.prototype.off=function(e){return this.listeners.delete(e),this.eventListeners.delete(e),this.sendListeners.delete(e),this.stopListeners.delete(e),this.doneListeners.delete(e),this.contextListeners.delete(e),this},t.prototype.start=function(e){var r=this;if(this.status===Y.Running)return this;this.machine._init(),Be.register(this.sessionId,this),this.initialized=!0,this.status=Y.Running;var n=e===void 0?this.initialState:Re(this,function(){return Vi(e)?r.machine.resolveState(e):r.machine.resolveState(ue.from(e,r.machine.context))});return this.options.devTools&&this.attachDev(),this.scheduler.initialize(function(){r.update(n,ge)}),this},t.prototype._stopChildren=function(){this.children.forEach(function(e){N(e.stop)&&e.stop()}),this.children.clear()},t.prototype._stop=function(){var e,r,n,i,s,o,c,u,d,h;try{for(var l=x(this.listeners),a=l.next();!a.done;a=l.next()){var f=a.value;this.listeners.delete(f)}}catch(_){e={error:_}}finally{try{a&&!a.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}try{for(var v=x(this.stopListeners),y=v.next();!y.done;y=v.next()){var f=y.value;f(),this.stopListeners.delete(f)}}catch(_){n={error:_}}finally{try{y&&!y.done&&(i=v.return)&&i.call(v)}finally{if(n)throw n.error}}try{for(var S=x(this.contextListeners),w=S.next();!w.done;w=S.next()){var f=w.value;this.contextListeners.delete(f)}}catch(_){s={error:_}}finally{try{w&&!w.done&&(o=S.return)&&o.call(S)}finally{if(s)throw s.error}}try{for(var T=x(this.doneListeners),b=T.next();!b.done;b=T.next()){var f=b.value;this.doneListeners.delete(f)}}catch(_){c={error:_}}finally{try{b&&!b.done&&(u=T.return)&&u.call(T)}finally{if(c)throw c.error}}if(!this.initialized)return this;this.initialized=!1,this.status=Y.Stopped,this._initialState=void 0;try{for(var O=x(Object.keys(this.delayedEventsMap)),M=O.next();!M.done;M=O.next()){var D=M.value;this.clock.clearTimeout(this.delayedEventsMap[D])}}catch(_){d={error:_}}finally{try{M&&!M.done&&(h=O.return)&&h.call(O)}finally{if(d)throw d.error}}this.scheduler.clear(),this.scheduler=new Br({deferEvents:this.options.deferEvents})},t.prototype.stop=function(){var e=this,r=this.scheduler;return this._stop(),r.schedule(function(){var n;if(!(!((n=e._state)===null||n===void 0)&&n.done)){var i=Q({type:"xstate.stop"}),s=Re(e,function(){var o=G(q([],P(e.state.configuration),!1).sort(function(l,a){return a.order-l.order}).map(function(l){return de(l.onExit,e.machine.options.actions)})),c=P(qe(e.machine,e.state,e.state.context,i,[{type:"exit",actions:o}],e.machine.config.predictableActionArguments?e._exec:void 0,e.machine.config.predictableActionArguments||e.machine.config.preserveActionOrder),2),u=c[0],d=c[1],h=new ue({value:e.state.value,context:d,_event:i,_sessionid:e.sessionId,historyValue:void 0,history:e.state,actions:u.filter(function(l){return!Lt(l)}),activities:{},events:[],configuration:[],transitions:[],children:{},done:e.state.done,tags:e.state.tags,machine:e.machine});return h.changed=!0,h});e.update(s,i),e._stopChildren(),Be.free(e.sessionId)}}),this},t.prototype.batch=function(e){var r=this;if(this.status===Y.NotStarted&&this.options.deferEvents)K||J(!1,"".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,`" and are deferred. Make sure .start() is called for this service.
|
|
17
|
+
Event: `).concat(JSON.stringify(event)));else if(this.status!==Y.Running)throw new Error("".concat(e.length,' event(s) were sent to uninitialized service "').concat(this.machine.id,'". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.'));if(e.length){var n=!!this.machine.config.predictableActionArguments&&this._exec;this.scheduler.schedule(function(){var i,s,o=r.state,c=!1,u=[],d=function(f){var v=Q(f);r.forward(v),o=Re(r,function(){return r.machine.transition(o,v,void 0,n||void 0)}),u.push.apply(u,q([],P(r.machine.config.predictableActionArguments?o.actions:o.actions.map(function(y){return Ki(y,o)})),!1)),c=c||!!o.changed};try{for(var h=x(e),l=h.next();!l.done;l=h.next()){var a=l.value;d(a)}}catch(f){i={error:f}}finally{try{l&&!l.done&&(s=h.return)&&s.call(h)}finally{if(i)throw i.error}}o.changed=c,o.actions=u,r.update(o,Q(e[e.length-1]))})}},t.prototype.sender=function(e){return this.send.bind(this,e)},t.prototype._nextState=function(e,r){var n=this;r===void 0&&(r=!!this.machine.config.predictableActionArguments&&this._exec);var i=Q(e);if(i.name.indexOf(Nt)===0&&!this.state.nextEvents.some(function(o){return o.indexOf(Nt)===0}))throw i.data.data;var s=Re(this,function(){return n.machine.transition(n.state,i,void 0,r||void 0)});return s},t.prototype.nextState=function(e){return this._nextState(e,!1)},t.prototype.forward=function(e){var r,n;try{for(var i=x(this.forwardTo),s=i.next();!s.done;s=i.next()){var o=s.value,c=this.children.get(o);if(!c)throw new Error("Unable to forward event '".concat(e,"' from interpreter '").concat(this.id,"' to nonexistant child '").concat(o,"'."));c.send(e)}}catch(u){r={error:u}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}},t.prototype.defer=function(e){var r=this,n=this.clock.setTimeout(function(){"to"in e&&e.to?r.sendTo(e._event,e.to,!0):r.send(e._event)},e.delay);e.id&&(this.delayedEventsMap[e.id]=n)},t.prototype.cancel=function(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]},t.prototype.exec=function(e,r,n){n===void 0&&(n=this.machine.options.actions),this._exec(e,r.context,r._event,n)},t.prototype.removeChild=function(e){var r;this.children.delete(e),this.forwardTo.delete(e),(r=this.state)===null||r===void 0||delete r.children[e]},t.prototype.stopChild=function(e){var r=this.children.get(e);r&&(this.removeChild(e),N(r.stop)&&r.stop())},t.prototype.spawn=function(e,r,n){if(this.status!==Y.Running)return $t(e,r);if(kr(e))return this.spawnPromise(Promise.resolve(e),r);if(N(e))return this.spawnCallback(e,r);if(ji(e))return this.spawnActor(e,r);if(mi(e))return this.spawnObservable(e,r);if(le(e))return this.spawnMachine(e,m(m({},n),{id:r}));if(vi(e))return this.spawnBehavior(e,r);throw new Error('Unable to spawn entity "'.concat(r,'" of type "').concat(typeof e,'".'))},t.prototype.spawnMachine=function(e,r){var n=this;r===void 0&&(r={});var i=new t(e,m(m({},this.options),{parent:this,id:r.id||e.id})),s=m(m({},Vt),r);s.sync&&i.onTransition(function(c){n.send(st,{state:c,id:i.id})});var o=i;return this.children.set(i.id,o),s.autoForward&&this.forwardTo.add(i.id),i.onDone(function(c){n.removeChild(i.id),n.send(Q(c,{origin:i.id}))}).start(),o},t.prototype.spawnBehavior=function(e,r){var n=Wi(e,{id:r,parent:this});return this.children.set(r,n),n},t.prototype.spawnPromise=function(e,r){var n,i=this,s=!1,o;e.then(function(u){s||(o=u,i.removeChild(r),i.send(Q(He(r,u),{origin:r})))},function(u){if(!s){i.removeChild(r);var d=Ie(r,u);try{i.send(Q(d,{origin:r}))}catch(h){Si(u,h,r),i.devTools&&i.devTools.send(d,i.state),i.machine.strict&&i.stop()}}});var c=(n={id:r,send:function(){},subscribe:function(u,d,h){var l=dt(u,d,h),a=!1;return e.then(function(f){a||(l.next(f),!a&&l.complete())},function(f){a||l.error(f)}),{unsubscribe:function(){return a=!0}}},stop:function(){s=!0},toJSON:function(){return{id:r}},getSnapshot:function(){return o}},n[pe]=function(){return this},n);return this.children.set(r,c),c},t.prototype.spawnCallback=function(e,r){var n,i=this,s=!1,o=new Set,c=new Set,u,d=function(a){u=a,c.forEach(function(f){return f(a)}),!s&&i.send(Q(a,{origin:r}))},h;try{h=e(d,function(a){o.add(a)})}catch(a){this.send(Ie(r,a))}if(kr(h))return this.spawnPromise(h,r);var l=(n={id:r,send:function(a){return o.forEach(function(f){return f(a)})},subscribe:function(a){var f=dt(a);return c.add(f.next),{unsubscribe:function(){c.delete(f.next)}}},stop:function(){s=!0,N(h)&&h()},toJSON:function(){return{id:r}},getSnapshot:function(){return u}},n[pe]=function(){return this},n);return this.children.set(r,l),l},t.prototype.spawnObservable=function(e,r){var n,i=this,s,o=e.subscribe(function(u){s=u,i.send(Q(u,{origin:r}))},function(u){i.removeChild(r),i.send(Q(Ie(r,u),{origin:r}))},function(){i.removeChild(r),i.send(Q(He(r),{origin:r}))}),c=(n={id:r,send:function(){},subscribe:function(u,d,h){return e.subscribe(u,d,h)},stop:function(){return o.unsubscribe()},getSnapshot:function(){return s},toJSON:function(){return{id:r}}},n[pe]=function(){return this},n);return this.children.set(r,c),c},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){K||J(!1,"No implementation found for activity '".concat(e.type,"'"));return}var n=r(this.state.context,e);this.spawnEffect(e.id,n)},t.prototype.spawnEffect=function(e,r){var n;this.children.set(e,(n={id:e,send:function(){},subscribe:function(){return{unsubscribe:function(){}}},stop:r||void 0,getSnapshot:function(){},toJSON:function(){return{id:e}}},n[pe]=function(){return this},n))},t.prototype.attachDev=function(){var e=qt();if(this.options.devTools&&e){if(e.__REDUX_DEVTOOLS_EXTENSION__){var r=typeof this.options.devTools=="object"?this.options.devTools:void 0;this.devTools=e.__REDUX_DEVTOOLS_EXTENSION__.connect(m(m({name:this.id,autoPause:!0,stateSanitizer:function(n){return{value:n.value,context:n.context,actions:n.actions}}},r),{features:m({jump:!1,skip:!1},r?r.features:void 0)}),this.machine),this.devTools.init(this.state)}Yi(this)}},t.prototype.toJSON=function(){return{id:this.id}},t.prototype[pe]=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}(),Xi=function(t){return U(t)?m(m({},Vt),{name:t}):m(m(m({},Vt),{name:wi()}),t)};function Qi(t,e){var r=Xi(e);return Ci(function(n){if(!K){var i=le(t)||N(t);J(!!n||i,'Attempted to spawn an Actor (ID: "'.concat(le(t)?t.id:"undefined",'") outside of a service. This will have no effect.'))}return n?n.spawn(t,r.name,r):$t(t,r.name)})}function xe(t,e){var r=new Ji(t,e);return r}function Zi(t){if(typeof t=="string"){var e={type:t};return e.toString=function(){return t},e}return t}function mt(t){return m(m({type:it},t),{toJSON:function(){t.onDone,t.onError;var e=_t(t,["onDone","onError"]);return m(m({},e),{type:it,src:Zi(t.src)})}})}var _e="",Kt="#",ze="*",Pe={},Ne=function(t){return t[0]===Kt},es=function(){return{actions:{},guards:{},services:{},activities:{},delays:{}}},ts=function(t,e,r){var n=r.slice(0,-1).some(function(s){return!("cond"in s)&&!("in"in s)&&(U(s.target)||le(s.target))}),i=e===_e?"the transient event":"event '".concat(e,"'");J(!n,"One or more transitions for ".concat(i," on state '").concat(t.id,"' are unreachable. ")+"Make sure that the default transition is the last one defined.")},rs=function(){function t(e,r,n,i){n===void 0&&(n="context"in e?e.context:void 0);var s=this,o;this.config=e,this._context=n,this.order=-1,this.__xstatenode=!0,this.__cache={events:void 0,relativeValue:new Map,initialStateValue:void 0,initialState:void 0,on:void 0,transitions:void 0,candidates:{},delayedTransitions:void 0},this.idMap={},this.tags=[],this.options=Object.assign(es(),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:Er),this.id=this.config.id||q([this.machine.key],P(this.path),!1).join(this.delimiter),this.version=this.parent?this.parent.version:this.config.version,this.type=this.config.type||(this.config.parallel?"parallel":this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.schema=this.parent?this.machine.schema:(o=this.config.schema)!==null&&o!==void 0?o:{},this.description=this.config.description,K||J(!("parallel"in this.config),'The "parallel" property is deprecated and will be removed in version 4.1. '.concat(this.config.parallel?"Replace with `type: 'parallel'`":"Use `type: '".concat(this.type,"'`")," in the config for state node '").concat(this.id,"' instead.")),this.initial=this.config.initial,this.states=this.config.states?$e(this.config.states,function(d,h){var l,a=new t(d,{},void 0,{parent:s,key:h});return Object.assign(s.idMap,m((l={},l[a.id]=a,l),a.idMap)),a}):Pe;var c=0;function u(d){var h,l;d.order=c++;try{for(var a=x(Hr(d)),f=a.next();!f.done;f=a.next()){var v=f.value;u(v)}}catch(y){h={error:y}}finally{try{f&&!f.done&&(l=a.return)&&l.call(a)}finally{if(h)throw h.error}}}u(this),this.history=this.config.history===!0?"shallow":this.config.history||!1,this._transient=!!this.config.always||(this.config.on?Array.isArray(this.config.on)?this.config.on.some(function(d){var h=d.event;return h===_e}):_e in this.config.on:!1),this.strict=!!this.config.strict,this.onEntry=se(this.config.entry||this.config.onEntry).map(function(d){return Oe(d)}),this.onExit=se(this.config.exit||this.config.onExit).map(function(d){return Oe(d)}),this.meta=this.config.meta,this.doneData=this.type==="final"?this.config.data:void 0,this.invoke=se(this.config.invoke).map(function(d,h){var l,a;if(le(d)){var f=ht(s.id,h);return s.machine.options.services=m((l={},l[f]=d,l),s.machine.options.services),mt({src:f,id:f})}else if(U(d.src)){var f=d.id||ht(s.id,h);return mt(m(m({},d),{id:f,src:d.src}))}else if(le(d.src)||N(d.src)){var f=d.id||ht(s.id,h);return s.machine.options.services=m((a={},a[f]=d.src,a),s.machine.options.services),mt(m(m({id:f},d),{src:f}))}else{var v=d.src;return mt(m(m({id:ht(s.id,h)},d),{src:v}))}}),this.activities=se(this.config.activities).concat(this.invoke).map(function(d){return pt(d)}),this.transition=this.transition.bind(this),this.tags=se(this.config.tags)}return t.prototype._init=function(){this.__cache.transitions||qr(this).forEach(function(e){return e.on})},t.prototype.withConfig=function(e,r){var n=this.options,i=n.actions,s=n.activities,o=n.guards,c=n.services,u=n.delays;return new t(this.config,{actions:m(m({},i),e.actions),activities:m(m({},s),e.activities),guards:m(m({},o),e.guards),services:m(m({},c),e.services),delays:m(m({},u),e.delays)},r!=null?r:this.context)},t.prototype.withContext=function(e){return new t(this.config,this.options,e)},Object.defineProperty(t.prototype,"context",{get:function(){return N(this._context)?this._context():this._context},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"definition",{get:function(){return{id:this.id,key:this.key,version:this.version,context:this.context,type:this.type,initial:this.initial,history:this.history,states:$e(this.states,function(e){return e.definition}),on:this.on,transitions:this.transitions,entry:this.onEntry,exit:this.onExit,activities:this.activities||[],meta:this.meta,order:this.order||-1,data:this.doneData,invoke:this.invoke,description:this.description,tags:this.tags}},enumerable:!1,configurable:!0}),t.prototype.toJSON=function(){return this.definition},Object.defineProperty(t.prototype,"on",{get:function(){if(this.__cache.on)return this.__cache.on;var e=this.transitions;return this.__cache.on=e.reduce(function(r,n){return r[n.eventType]=r[n.eventType]||[],r[n.eventType].push(n),r},{})},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"after",{get:function(){return this.__cache.delayedTransitions||(this.__cache.delayedTransitions=this.getDelayedTransitions(),this.__cache.delayedTransitions)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transitions",{get:function(){return this.__cache.transitions||(this.__cache.transitions=this.formatTransitions(),this.__cache.transitions)},enumerable:!1,configurable:!0}),t.prototype.getCandidates=function(e){if(this.__cache.candidates[e])return this.__cache.candidates[e];var r=e===_e,n=this.transitions.filter(function(i){var s=i.eventType===e;return r?s:s||i.eventType===ze});return this.__cache.candidates[e]=n,n},t.prototype.getDelayedTransitions=function(){var e=this,r=this.config.after;if(!r)return[];var n=function(s,o){var c=N(s)?"".concat(e.id,":delay[").concat(o,"]"):s,u=$r(c,e.id);return e.onEntry.push(me(u,{delay:s})),e.onExit.push(Dr(u)),u},i=ke(r)?r.map(function(s,o){var c=n(s.delay,o);return m(m({},s),{event:c})}):G(Object.keys(r).map(function(s,o){var c=r[s],u=U(c)?{target:c}:c,d=isNaN(+s)?s:+s,h=n(d,o);return se(u).map(function(l){return m(m({},l),{event:h,delay:d})})}));return i.map(function(s){var o=s.delay;return m(m({},e.formatTransition(s)),{delay:o})})},t.prototype.getStateNodes=function(e){var r,n=this;if(!e)return[];var i=e instanceof ue?e.value:je(e,this.delimiter);if(U(i)){var s=this.getStateNode(i).initial;return s!==void 0?this.getStateNodes((r={},r[i]=s,r)):[this,this.states[i]]}var o=Object.keys(i),c=[this];return c.push.apply(c,q([],P(G(o.map(function(u){return n.getStateNode(u).getStateNodes(i[u])}))),!1)),c},t.prototype.handles=function(e){var r=Tr(e);return this.events.includes(r)},t.prototype.resolveState=function(e){var r=e instanceof ue?e:ue.create(e),n=Array.from(Ke([],this.getStateNodes(r.value)));return new ue(m(m({},r),{value:this.resolve(r.value),configuration:n,done:gt(n,this),tags:Kr(n),machine:this.machine}))},t.prototype.transitionLeafNode=function(e,r,n){var i=this.getStateNode(e),s=i.next(r,n);return!s||!s.transitions.length?this.next(r,n):s},t.prototype.transitionCompoundNode=function(e,r,n){var i=Object.keys(e),s=this.getStateNode(i[0]),o=s._transition(e[i[0]],r,n);return!o||!o.transitions.length?this.next(r,n):o},t.prototype.transitionParallelNode=function(e,r,n){var i,s,o={};try{for(var c=x(Object.keys(e)),u=c.next();!u.done;u=c.next()){var d=u.value,h=e[d];if(h){var l=this.getStateNode(d),a=l._transition(h,r,n);a&&(o[d]=a)}}}catch(w){i={error:w}}finally{try{u&&!u.done&&(s=c.return)&&s.call(c)}finally{if(i)throw i.error}}var f=Object.keys(o).map(function(w){return o[w]}),v=G(f.map(function(w){return w.transitions})),y=f.some(function(w){return w.transitions.length>0});if(!y)return this.next(r,n);var S=G(Object.keys(o).map(function(w){return o[w].configuration}));return{transitions:v,exitSet:G(f.map(function(w){return w.exitSet})),configuration:S,source:r,actions:G(Object.keys(o).map(function(w){return o[w].actions}))}},t.prototype._transition=function(e,r,n){return U(e)?this.transitionLeafNode(e,r,n):Object.keys(e).length===1?this.transitionCompoundNode(e,r,n):this.transitionParallelNode(e,r,n)},t.prototype.getTransitionData=function(e,r){return this._transition(e.value,e,Q(r))},t.prototype.next=function(e,r){var n,i,s=this,o=r.name,c=[],u=[],d;try{for(var h=x(this.getCandidates(o)),l=h.next();!l.done;l=h.next()){var a=l.value,f=a.cond,v=a.in,y=e.context,S=v?U(v)&&Ne(v)?e.matches(je(this.getStateNodeById(v).path,this.delimiter)):Ct(je(v,this.delimiter),hi(this.path.slice(0,-2))(e.value)):!0,w=!1;try{w=!f||Rr(this.machine,f,y,r,e)}catch(O){throw new Error("Unable to evaluate guard '".concat(f.name||f.type,"' in transition for event '").concat(o,"' in state node '").concat(this.id,`':
|
|
18
|
+
`).concat(O.message))}if(w&&S){a.target!==void 0&&(u=a.target),c.push.apply(c,q([],P(a.actions),!1)),d=a;break}}}catch(O){n={error:O}}finally{try{l&&!l.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}if(d){if(!u.length)return{transitions:[d],exitSet:[],configuration:e.value?[this]:[],source:e,actions:c};var T=G(u.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),b=!!d.internal;return{transitions:[d],exitSet:b?[]:G(u.map(function(O){return s.getPotentiallyReenteringNodes(O)})),configuration:T,source:e,actions:c}}},t.prototype.getPotentiallyReenteringNodes=function(e){if(this.order<e.order)return[this];for(var r=[],n=this,i=e;n&&n!==i;)r.push(n),n=n.parent;return n!==i?[]:(r.push(i),r)},t.prototype.getActions=function(e,r,n,i,s,o,c){var u,d,h,l,a=this,f=o?Ke([],this.getStateNodes(o.value)):[],v=new Set;try{for(var y=x(Array.from(e).sort(function(A,F){return A.order-F.order})),S=y.next();!S.done;S=y.next()){var w=S.value;(!Ge(f,w)||Ge(n.exitSet,w)||w.parent&&v.has(w.parent))&&v.add(w)}}catch(A){u={error:A}}finally{try{S&&!S.done&&(d=y.return)&&d.call(y)}finally{if(u)throw u.error}}try{for(var T=x(f),b=T.next();!b.done;b=T.next()){var w=b.value;(!Ge(e,w)||Ge(n.exitSet,w.parent))&&n.exitSet.push(w)}}catch(A){h={error:A}}finally{try{b&&!b.done&&(l=T.return)&&l.call(T)}finally{if(h)throw h.error}}n.exitSet.sort(function(A,F){return F.order-A.order});var O=Array.from(v).sort(function(A,F){return A.order-F.order}),M=new Set(n.exitSet),D=G(O.map(function(A){var F=[];if(A.type!=="final")return F;var z=A.parent;if(!z.parent)return F;F.push(Fe(A.id,A.doneData),Fe(z.id,A.doneData?ut(A.doneData,i,s):void 0));var V=z.parent;return V.type==="parallel"&&Ve(V).every(function(we){return gt(n.configuration,we)})&&F.push(Fe(V.id)),F})),_=O.map(function(A){var F=A.onEntry,z=A.activities.map(function(V){return Cr(V)});return{type:"entry",actions:de(c?q(q([],P(F),!1),P(z),!1):q(q([],P(z),!1),P(F),!1),a.machine.options.actions)}}).concat({type:"state_done",actions:D.map(function(A){return _r(A)})}),$=Array.from(M).map(function(A){return{type:"exit",actions:de(q(q([],P(A.onExit),!1),P(A.activities.map(function(F){return Mr(F)})),!1),a.machine.options.actions)}}),R=$.concat({type:"transition",actions:de(n.actions,this.machine.options.actions)}).concat(_);if(r){var B=de(G(q([],P(e),!1).sort(function(A,F){return F.order-A.order}).map(function(A){return A.onExit})),this.machine.options.actions).filter(function(A){return!Lt(A)});return R.concat({type:"stop",actions:B})}return R},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=Q(r),o;if(e instanceof ue)o=n===void 0?e:this.resolveState(ue.from(e,n));else{var c=U(e)?this.resolve(at(this.getResolvedPath(e))):this.resolve(e),u=n!=null?n:this.machine.context;o=this.resolveState(ue.from(c,u))}if(!K&&s.name===ze)throw new Error("An event cannot have the wildcard type ('".concat(ze,"')"));if(this.strict&&!this.events.includes(s.name)&&!pi(s.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(s.name,"'"));var d=this._transition(o.value,o,s)||{transitions:[],configuration:[],exitSet:[],source:o,actions:[]},h=Ke([],this.getStateNodes(o.value)),l=d.configuration.length?Ke(h,d.configuration):h;return d.configuration=q([],P(l),!1),this.resolveTransition(d,o,o.context,i,s)},t.prototype.resolveRaisedTransition=function(e,r,n,i){var s,o=e.actions;return e=this.transition(e,r,void 0,i),e._event=n,e.event=n.data,(s=e.actions).unshift.apply(s,q([],P(o),!1)),e},t.prototype.resolveTransition=function(e,r,n,i,s){var o,c,u,d,h=this;s===void 0&&(s=ge);var l=e.configuration,a=!r||e.transitions.length>0,f=a?e.configuration:r?r.configuration:[],v=gt(f,this),y=a?Fi(this.machine,l):void 0,S=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,w=this.getActions(new Set(f),v,e,n,s,r,i),T=r?m({},r.activities):{};try{for(var b=x(w),O=b.next();!O.done;O=b.next()){var M=O.value;try{for(var D=(u=void 0,x(M.actions)),_=D.next();!_.done;_=D.next()){var $=_.value;$.type===et?T[$.activity.id||$.activity.type]=$:$.type===tt&&(T[$.activity.id||$.activity.type]=!1)}}catch(ne){u={error:ne}}finally{try{_&&!_.done&&(d=D.return)&&d.call(D)}finally{if(u)throw u.error}}}}catch(ne){o={error:ne}}finally{try{O&&!O.done&&(c=b.return)&&c.call(b)}finally{if(o)throw o.error}}var R=P(qe(this,r,n,s,w,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),B=R[0],A=R[1],F=P(yi(B,Lt),2),z=F[0],V=F[1],we=B.filter(function(ne){var W;return ne.type===et&&((W=ne.activity)===null||W===void 0?void 0:W.type)===it}),Te=we.reduce(function(ne,W){return ne[W.activity.id]=Mi(W.activity,h.machine,A,s),ne},r?m({},r.children):{}),p=new ue({value:y||r.value,context:A,_event:s,_sessionid:r?r._sessionid:null,historyValue:y?S?gi(S,y):void 0:r?r.historyValue:void 0,history:!y||e.source?r:void 0,actions:y?V:[],activities:y?T:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:Te,done:v,tags:Kr(f),machine:this}),E=n!==A;p.changed=s.name===st||E;var k=p.history;k&&delete k.history;var H=!v&&(this._transient||l.some(function(ne){return ne._transient}));if(!a&&(!H||s.name===_e))return p;var C=p;if(!v)for(H&&(C=this.resolveRaisedTransition(C,{type:vr},s,i));z.length;){var L=z.shift();C=this.resolveRaisedTransition(C,L._event,s,i)}var Ce=C.changed||(k?!!C.actions.length||E||typeof k.value!=typeof C.value||!Gr(C.value,k.value):void 0);return C.changed=Ce,C.history=k,C},t.prototype.getStateNode=function(e){if(Ne(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Ne(e)?e.slice(Kt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&Ne(e))try{return this.getStateNodeById(e.slice(1))}catch{}for(var r=Mt(e,this.delimiter).slice(),n=this;r.length;){var i=r.shift();if(!i.length)break;n=n.getStateNode(i)}return n},t.prototype.resolve=function(e){var r,n=this;if(!e)return this.initialStateValue||Pe;switch(this.type){case"parallel":return $e(this.initialStateValue,function(s,o){return s?n.getStateNode(o).resolve(e[o]||s):Pe});case"compound":if(U(e)){var i=this.getStateNode(e);return i.type==="parallel"||i.type==="compound"?(r={},r[e]=i.initialStateValue,r):e}return Object.keys(e).length?$e(e,function(s,o){return s?n.getStateNode(o).resolve(s):Pe}):this.initialStateValue||{};default:return e||Pe}},t.prototype.getResolvedPath=function(e){if(Ne(e)){var r=this.machine.idMap[e.slice(Kt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Mt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=Sr(this.states,function(n){return n.initialStateValue||Pe},function(n){return n.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));r=yt(this.states[this.initial])?this.initial:(e={},e[this.initial]=this.states[this.initial].initialStateValue,e)}else r={};return this.__cache.initialStateValue=r,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),t.prototype.getInitialState=function(e,r){this._init();var n=this.getStateNodes(e);return this.resolveTransition({configuration:n,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,r!=null?r:this.machine.context,void 0)},Object.defineProperty(t.prototype,"initialState",{get:function(){var e=this.initialStateValue;if(!e)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e;if(this.type==="history"){var r=this.config;U(r.target)?e=Ne(r.target)?at(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(yt(this))return[this];if(this.type==="compound"&&!this.initial)return K||J(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=ct(this.initialStateValue);return G(r.map(function(n){return e.getFromRelativePath(n)}))},enumerable:!1,configurable:!0}),t.prototype.getFromRelativePath=function(e){if(!e.length)return[this];var r=P(e),n=r[0],i=r.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(n,"' from node with no states"));var s=this.getStateNode(n);if(s.type==="history")return s.resolveHistory();if(!this.states[n])throw new Error("Child state '".concat(n,"' does not exist on '").concat(this.id,"'"));return this.states[n].getFromRelativePath(i)},t.prototype.historyValue=function(e){if(Object.keys(this.states).length)return{current:e||this.initialStateValue,states:Sr(this.states,function(r,n){if(!e)return r.historyValue();var i=U(e)?void 0:e[n];return r.historyValue(i||r.initialStateValue)},function(r){return!r.history})}},t.prototype.resolveHistory=function(e){var r=this;if(this.type!=="history")return[this];var n=this.parent;if(!e){var i=this.target;return i?G(ct(i).map(function(o){return n.getFromRelativePath(o)})):n.initialStateNodes}var s=fi(n.path,"states")(e).current;return U(s)?[n.getStateNode(s)]:G(ct(s).map(function(o){return r.history==="deep"?n.getFromRelativePath(o):[n.states[o[0]]]}))},Object.defineProperty(t.prototype,"stateIds",{get:function(){var e=this,r=G(Object.keys(this.states).map(function(n){return e.states[n].stateIds}));return[this.id].concat(r)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"events",{get:function(){var e,r,n,i;if(this.__cache.events)return this.__cache.events;var s=this.states,o=new Set(this.ownEvents);if(s)try{for(var c=x(Object.keys(s)),u=c.next();!u.done;u=c.next()){var d=u.value,h=s[d];if(h.states)try{for(var l=(n=void 0,x(h.events)),a=l.next();!a.done;a=l.next()){var f=a.value;o.add("".concat(f))}}catch(v){n={error:v}}finally{try{a&&!a.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}}catch(v){e={error:v}}finally{try{u&&!u.done&&(r=c.return)&&r.call(c)}finally{if(e)throw e.error}}return this.__cache.events=Array.from(o)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ownEvents",{get:function(){var e=new Set(this.transitions.filter(function(r){return!(!r.target&&!r.actions.length&&r.internal)}).map(function(r){return r.eventType}));return Array.from(e)},enumerable:!1,configurable:!0}),t.prototype.resolveTarget=function(e){var r=this;if(e!==void 0)return e.map(function(n){if(!U(n))return n;var i=n[0]===r.delimiter;if(i&&!r.parent)return r.getStateNodeByPath(n.slice(1));var s=i?r.key+n:n;if(r.parent)try{var o=r.parent.getStateNodeByPath(s);return o}catch(c){throw new Error("Invalid transition definition for state node '".concat(r.id,`':
|
|
19
|
+
`).concat(c.message))}else return r.getStateNodeByPath(s)})},t.prototype.formatTransition=function(e){var r=this,n=Ti(e.target),i="internal"in e?e.internal:n?n.some(function(u){return U(u)&&u[0]===r.delimiter}):!0,s=this.machine.options.guards,o=this.resolveTarget(n),c=m(m({},e),{actions:de(se(e.actions)),cond:Ir(e.cond,s),target:o,source:this,internal:i,eventType:e.event,toJSON:function(){return m(m({},c),{target:c.target?c.target.map(function(u){return"#".concat(u.id)}):void 0,source:"#".concat(r.id)})}});return c},t.prototype.formatTransitions=function(){var e,r,n=this,i;if(!this.config.on)i=[];else if(Array.isArray(this.config.on))i=this.config.on;else{var s=this.config.on,o=ze,c=s[o],u=c===void 0?[]:c,d=_t(s,[typeof o=="symbol"?o:o+""]);i=G(Object.keys(d).map(function(T){!K&&T===_e&&J(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var b=Ae(T,d[T]);return K||ts(n,T,b),b}).concat(Ae(ze,u)))}var h=this.config.always?Ae("",this.config.always):[],l=this.config.onDone?Ae(String(Fe(this.id)),this.config.onDone):[];K||J(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var a=G(this.invoke.map(function(T){var b=[];return T.onDone&&b.push.apply(b,q([],P(Ae(String(He(T.id)),T.onDone)),!1)),T.onError&&b.push.apply(b,q([],P(Ae(String(Ie(T.id)),T.onError)),!1)),b})),f=this.after,v=G(q(q(q(q([],P(l),!1),P(a),!1),P(i),!1),P(h),!1).map(function(T){return se(T).map(function(b){return n.formatTransition(b)})}));try{for(var y=x(f),S=y.next();!S.done;S=y.next()){var w=S.value;v.push(w)}}catch(T){e={error:T}}finally{try{S&&!S.done&&(r=y.return)&&r.call(y)}finally{if(e)throw e.error}}return v},t}(),zr=!1;function ve(t,e){return!K&&!("predictableActionArguments"in t)&&!zr&&(zr=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new rs(t,e)}var I=jr,X=me;/*! js-cookie v3.0.5 | MIT */function Et(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 ns={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function Gt(t,e){function r(i,s,o){if(typeof document!="undefined"){o=Et({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),i=encodeURIComponent(i).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var u in o)o[u]&&(c+="; "+u,o[u]!==!0&&(c+="="+o[u].split(";")[0]));return document.cookie=i+"="+t.write(s,i)+c}}function n(i){if(!(typeof document=="undefined"||arguments.length&&!i)){for(var s=document.cookie?document.cookie.split("; "):[],o={},c=0;c<s.length;c++){var u=s[c].split("="),d=u.slice(1).join("=");try{var h=decodeURIComponent(u[0]);if(o[h]=t.read(d,h),i===h)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",Et({},s,{expires:-1}))},withAttributes:function(i){return Gt(this.converter,Et({},this.attributes,i))},withConverter:function(i){return Gt(Et({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Bt=Gt(ns,{path:"/"}),zt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Yt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function is(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Wt={exports:{}};(function(t,e){(function(r){function n(i){var s=i&&i.Promise||r.Promise,o=i&&i.XMLHttpRequest||r.XMLHttpRequest;return function(){var c=Object.create(r,{fetch:{value:void 0,writable:!0}});return function(u,d){d(e)}(this,function(u){var d=typeof c!="undefined"&&c||typeof self!="undefined"&&self||typeof d!="undefined"&&d,h={searchParams:"URLSearchParams"in d,iterable:"Symbol"in d&&"iterator"in Symbol,blob:"FileReader"in d&&"Blob"in d&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in d,arrayBuffer:"ArrayBuffer"in d};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(h.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(p){return p&&a.indexOf(Object.prototype.toString.call(p))>-1};function v(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError("Invalid character in header field name");return p.toLowerCase()}function y(p){return typeof p!="string"&&(p=String(p)),p}function S(p){var E={next:function(){var k=p.shift();return{done:k===void 0,value:k}}};return h.iterable&&(E[Symbol.iterator]=function(){return E}),E}function w(p){this.map={},p instanceof w?p.forEach(function(E,k){this.append(k,E)},this):Array.isArray(p)?p.forEach(function(E){this.append(E[0],E[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(E){this.append(E,p[E])},this)}w.prototype.append=function(p,E){p=v(p),E=y(E);var k=this.map[p];this.map[p]=k?k+", "+E:E},w.prototype.delete=function(p){delete this.map[v(p)]},w.prototype.get=function(p){return p=v(p),this.has(p)?this.map[p]:null},w.prototype.has=function(p){return this.map.hasOwnProperty(v(p))},w.prototype.set=function(p,E){this.map[v(p)]=y(E)},w.prototype.forEach=function(p,E){for(var k in this.map)this.map.hasOwnProperty(k)&&p.call(E,this.map[k],k,this)},w.prototype.keys=function(){var p=[];return this.forEach(function(E,k){p.push(k)}),S(p)},w.prototype.values=function(){var p=[];return this.forEach(function(E){p.push(E)}),S(p)},w.prototype.entries=function(){var p=[];return this.forEach(function(E,k){p.push([k,E])}),S(p)},h.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function T(p){if(p.bodyUsed)return s.reject(new TypeError("Already read"));p.bodyUsed=!0}function b(p){return new s(function(E,k){p.onload=function(){E(p.result)},p.onerror=function(){k(p.error)}})}function O(p){var E=new FileReader,k=b(E);return E.readAsArrayBuffer(p),k}function M(p){var E=new FileReader,k=b(E);return E.readAsText(p),k}function D(p){for(var E=new Uint8Array(p),k=new Array(E.length),H=0;H<E.length;H++)k[H]=String.fromCharCode(E[H]);return k.join("")}function _(p){if(p.slice)return p.slice(0);var E=new Uint8Array(p.byteLength);return E.set(new Uint8Array(p)),E.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:h.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:h.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:h.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():h.arrayBuffer&&h.blob&&l(p)?(this._bodyArrayBuffer=_(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||f(p))?this._bodyArrayBuffer=_(p):this._bodyText=p=Object.prototype.toString.call(p):this._bodyText="",this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):h.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},h.blob&&(this.blob=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return s.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return s.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=T(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?s.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):s.resolve(this._bodyArrayBuffer))}else return this.blob().then(O)}),this.text=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return M(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(D(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return s.resolve(this._bodyText)},h.formData&&(this.formData=function(){return this.text().then(F)}),this.json=function(){return this.text().then(JSON.parse)},this}var R=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function B(p){var E=p.toUpperCase();return R.indexOf(E)>-1?E:p}function A(p,E){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E=E||{};var k=E.body;if(p instanceof A){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,E.headers||(this.headers=new w(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!k&&p._bodyInit!=null&&(k=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=E.credentials||this.credentials||"same-origin",(E.headers||!this.headers)&&(this.headers=new w(E.headers)),this.method=B(E.method||this.method||"GET"),this.mode=E.mode||this.mode||null,this.signal=E.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&k)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(k),(this.method==="GET"||this.method==="HEAD")&&(E.cache==="no-store"||E.cache==="no-cache")){var H=/([?&])_=[^&]*/;if(H.test(this.url))this.url=this.url.replace(H,"$1_="+new Date().getTime());else{var C=/\?/;this.url+=(C.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}A.prototype.clone=function(){return new A(this,{body:this._bodyInit})};function F(p){var E=new FormData;return p.trim().split("&").forEach(function(k){if(k){var H=k.split("="),C=H.shift().replace(/\+/g," "),L=H.join("=").replace(/\+/g," ");E.append(decodeURIComponent(C),decodeURIComponent(L))}}),E}function z(p){var E=new w,k=p.replace(/\r?\n[\t ]+/g," ");return k.split("\r").map(function(H){return H.indexOf(`
|
|
20
|
+
`)===0?H.substr(1,H.length):H}).forEach(function(H){var C=H.split(":"),L=C.shift().trim();if(L){var Ce=C.join(":").trim();E.append(L,Ce)}}),E}$.call(A.prototype);function V(p,E){if(!(this instanceof V))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E||(E={}),this.type="default",this.status=E.status===void 0?200:E.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in E?E.statusText:"",this.headers=new w(E.headers),this.url=E.url||"",this._initBody(p)}$.call(V.prototype),V.prototype.clone=function(){return new V(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},V.error=function(){var p=new V(null,{status:0,statusText:""});return p.type="error",p};var we=[301,302,303,307,308];V.redirect=function(p,E){if(we.indexOf(E)===-1)throw new RangeError("Invalid status code");return new V(null,{status:E,headers:{location:p}})},u.DOMException=d.DOMException;try{new u.DOMException}catch{u.DOMException=function(E,k){this.message=E,this.name=k;var H=Error(E);this.stack=H.stack},u.DOMException.prototype=Object.create(Error.prototype),u.DOMException.prototype.constructor=u.DOMException}function Te(p,E){return new s(function(k,H){var C=new A(p,E);if(C.signal&&C.signal.aborted)return H(new u.DOMException("Aborted","AbortError"));var L=new o;function Ce(){L.abort()}L.onload=function(){var W={status:L.status,statusText:L.statusText,headers:z(L.getAllResponseHeaders()||"")};W.url="responseURL"in L?L.responseURL:W.headers.get("X-Request-URL");var xt="response"in L?L.response:L.responseText;setTimeout(function(){k(new V(xt,W))},0)},L.onerror=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},L.ontimeout=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},L.onabort=function(){setTimeout(function(){H(new u.DOMException("Aborted","AbortError"))},0)};function ne(W){try{return W===""&&d.location.href?d.location.href:W}catch{return W}}L.open(C.method,ne(C.url),!0),C.credentials==="include"?L.withCredentials=!0:C.credentials==="omit"&&(L.withCredentials=!1),"responseType"in L&&(h.blob?L.responseType="blob":h.arrayBuffer&&C.headers.get("Content-Type")&&C.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(L.responseType="arraybuffer")),E&&typeof E.headers=="object"&&!(E.headers instanceof w)?Object.getOwnPropertyNames(E.headers).forEach(function(W){L.setRequestHeader(W,y(E.headers[W]))}):C.headers.forEach(function(W,xt){L.setRequestHeader(xt,W)}),C.signal&&(C.signal.addEventListener("abort",Ce),L.onreadystatechange=function(){L.readyState===4&&C.signal.removeEventListener("abort",Ce)}),L.send(typeof C._bodyInit=="undefined"?null:C._bodyInit)})}Te.polyfill=!0,d.fetch||(d.fetch=Te,d.Headers=w,d.Request=A,d.Response=V),u.Headers=w,u.Request=A,u.Response=V,u.fetch=Te,Object.defineProperty(u,"__esModule",{value:!0})}),{fetch:c.fetch,Headers:c.Headers,Request:c.Request,Response:c.Response,DOMException:c.DOMException}}()}t.exports=n})(typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:zt)})(Wt,Wt.exports);var ss=Wt.exports;const Jt=Yt(ss),Ue="nhostRefreshToken",Ye="nhostRefreshTokenId",Ee="nhostRefreshTokenExpiresAt",Yr=3,Wr=60,Xt=5,Qt=0,Zt=1,oe=10,De=20;let ye=class extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Zt,message:e.message}):(this.name=e.error,this.error=e)}};const ae={status:oe,error:"invalid-email",message:"Email is incorrectly formatted"},Jr={status:oe,error:"invalid-mfa-type",message:"MFA type is invalid"},Xr={status:oe,error:"invalid-mfa-code",message:"MFA code is invalid"},wt={status:oe,error:"invalid-password",message:"Password is incorrectly formatted"},er={status:oe,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:oe,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Zr={status:oe,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},en={status:oe,error:"no-refresh-token",message:"No refresh token has been provided"},tn={status:De,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},ee={status:De,error:"already-signed-in",message:"User is already signed in"},rn={status:De,error:"unauthenticated-user",message:"User is not authenticated"},os={status:De,error:"user-not-anonymous",message:"User is not anonymous"},nn={status:De,error:"unverified-user",message:"Email needs verification"},sn={status:oe,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},on={status:Zt,error:"invalid-sign-in-method",message:"Invalid sign-in method"},Tt={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function as(t){return new TextEncoder().encode(t)}function he(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function tr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let c=0;c<i.length;c++)o[c]=i.charCodeAt(c);return s}function an(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function cn(t){const{id:e}=t;return{...t,id:tr(e),transports:t.transports}}function un(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class Z extends Error{constructor({message:e,code:r,cause:n,name:i}){super(e,{cause:n}),this.name=i!=null?i:n.name,this.code=r}}function cs({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 instanceof AbortSignal)return new Z({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)==null?void 0:r.requireResidentKey)===!0)return new Z({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(((n=i.authenticatorSelection)==null?void 0:n.userVerification)==="required")return new Z({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new Z({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Z({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(s=>s.type==="public-key").length===0?new Z({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Z({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(un(s)){if(i.rp.id!==s)return new Z({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Z({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Z({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new Z({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}class us{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ln=new us,ls=["cross-platform","platform"];function dn(t){if(t&&!(ls.indexOf(t)<0))return t}async function hn(t){var e;if(!an())throw new Error("WebAuthn is not supported in this browser");const r={publicKey:{...t,challenge:tr(t.challenge),user:{...t.user,id:as(t.user.id)},excludeCredentials:(e=t.excludeCredentials)==null?void 0:e.map(cn)}};r.signal=ln.createNewAbortSignal();let n;try{n=await navigator.credentials.create(r)}catch(a){throw cs({error:a,options:r})}if(!n)throw new Error("Registration was not completed");const{id:i,rawId:s,response:o,type:c}=n;let u;typeof o.getTransports=="function"&&(u=o.getTransports());let d;if(typeof o.getPublicKeyAlgorithm=="function")try{d=o.getPublicKeyAlgorithm()}catch(a){rr("getPublicKeyAlgorithm()",a)}let h;if(typeof o.getPublicKey=="function")try{const a=o.getPublicKey();a!==null&&(h=he(a))}catch(a){rr("getPublicKey()",a)}let l;if(typeof o.getAuthenticatorData=="function")try{l=he(o.getAuthenticatorData())}catch(a){rr("getAuthenticatorData()",a)}return{id:i,rawId:he(s),response:{attestationObject:he(o.attestationObject),clientDataJSON:he(o.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:h,authenticatorData:l},type:c,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:dn(n.authenticatorAttachment)}}function rr(t,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${t}. You should report this error to them.
|
|
21
|
+
`,e)}function ds(t){return new TextDecoder("utf-8").decode(t)}function hs(){const t=window.PublicKeyCredential;return t.isConditionalMediationAvailable===void 0?new Promise(e=>e(!1)):t.isConditionalMediationAvailable()}function fs({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Z({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Z({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(un(n)){if(r.rpId!==n)return new Z({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Z({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Z({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}async function nr(t,e=!1){var r,n;if(!an())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)==null?void 0:r.length)!==0&&(i=(n=t.allowCredentials)==null?void 0:n.map(cn));const s={...t,challenge:tr(t.challenge),allowCredentials:i},o={};if(e){if(!await hs())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation="conditional",s.allowCredentials=[]}o.publicKey=s,o.signal=ln.createNewAbortSignal();let c;try{c=await navigator.credentials.get(o)}catch(f){throw fs({error:f,options:o})}if(!c)throw new Error("Authentication was not completed");const{id:u,rawId:d,response:h,type:l}=c;let a;return h.userHandle&&(a=ds(h.userHandle)),{id:u,rawId:he(d),response:{authenticatorData:he(h.authenticatorData),clientDataJSON:he(h.clientDataJSON),signature:he(h.signature),userHandle:a},type:l,clientExtensionResults:c.getClientExtensionResults(),authenticatorAttachment:dn(c.authenticatorAttachment)}}const St=typeof window!="undefined",bt=new Map,ps=t=>{var e;return St&&typeof localStorage!="undefined"?localStorage.getItem(t):(e=bt.get(t))!=null?e:null},vs=(t,e)=>{St&&typeof localStorage!="undefined"?e?localStorage.setItem(t,e):localStorage.removeItem(t):e?bt.set(t,e):bt.has(t)&&bt.delete(t)},fn=(t,e)=>{if(t==="localStorage"||t==="web")return ps;if(t==="cookie")return r=>{var n;return St&&(n=Bt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},pn=(t,e)=>{if(t==="localStorage"||t==="web")return vs;if(t==="cookie")return(r,n)=>{St&&(n?Bt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Bt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},We=t=>!t||!t.accessToken.value||!t.accessToken.expiresAt||!t.user?null:{accessToken:t.accessToken.value,accessTokenExpiresIn:(t.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:t.refreshToken.value,user:t.user},ie=({accessToken:t,refreshToken:e,isError:r,user:n,error:i})=>r?{session:null,error:i}:n&&t?{session:{accessToken:t,accessTokenExpiresIn:0,refreshToken:e,user:n},error:null}:{session:null,error:null},Je=()=>typeof window!="undefined"&&typeof window.location!="undefined";let vn=globalThis.fetch;typeof EdgeRuntime!="string"&&(vn=Jt().fetch);const yn=async(t,e,{token:r,body:n,extraHeaders:i}={})=>{const s={"Content-Type":"application/json",Accept:"*/*"};r&&(s.Authorization=`Bearer ${r}`);const o={...s,...i},c={method:e,headers:o};n&&(c.body=JSON.stringify(n));try{const u=await vn(t,c);if(!u.ok){const d=await u.json();return Promise.reject({error:d})}try{return{data:await u.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 u={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:u})}},te=async(t,e,r,n)=>yn(t,"POST",{token:r,body:e,extraHeaders:n}),gn=(t,e)=>yn(t,"GET",{token:e}),kt=(t,e)=>{const r=e&&Object.entries(e).map(([n,i])=>{const s=Array.isArray(i)?i.join(","):typeof i=="object"?JSON.stringify(i):i;return`${n}=${encodeURIComponent(s)}`}).join("&");return r?`${t}?${r}`:t},re=(t,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!t)return r.startsWith("/")?n:e;const i=new URL(t),s=Object.fromEntries(new URLSearchParams(i.search)),o=new URL(r.startsWith("/")?i.origin+r:r),c=new URLSearchParams(o.search);let u=Object.fromEntries(c);r.startsWith("/")&&(u={...s,...u});let d=i.pathname;return o.pathname.length>1&&(d+=o.pathname.slice(1)),{...n,redirectTo:kt(o.origin+d,u)}};function Xe(t,e){var r;if(!e){if(typeof window=="undefined")return;e=((r=window.location)==null?void 0:r.href)||""}t=t.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+t+"(=([^&#]*)|&|#|$)"),i=n.exec(e);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function ir(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const ce=t=>!!t&&typeof t=="string"&&!!String(t).toLowerCase().match(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/),At=t=>!!t&&typeof t=="string"&&t.length>=Yr,sr=t=>!!t&&typeof t=="string",mn=t=>t&&typeof t=="string"&&t.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),En=({backendUrl:t,clientUrl:e,broadcastKey:r,clientStorageType:n="web",clientStorage:i,refreshIntervalTime:s,autoRefreshToken:o=!0,autoSignIn:c=!0})=>{const u=fn(n,i),d=pn(n,i),h=async(l,a,f,v)=>(await te(`${t}${l}`,a,f,v)).data;return ve({schema:{context:{},events:{},services:{}},tsTypes:{},context:Tt,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:["clearContextExceptTokens"],exit:["destroyAccessToken","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_SECURITY_KEY:"authenticating.securityKey",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat",SIGNIN_ID_TOKEN:"authenticating.idToken"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},idToken:{invoke:{src:"signInIdToken",id:"authenticateWithIdToken",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},securityKey:{invoke:{src:"signInSecurityKey",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{cond:"isUnauthorizedError",target:"#nhost.authentication.signedOut"},{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",SIGNIN_EMAIL_OTP:"signInEmailOTP",VERIFY_EMAIL_OTP:"verifyEmailOTP"},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"}}},signInEmailOTP:{entry:["resetErrors"],invoke:{src:"signInEmailOTP",id:"signInEmailOTP",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},verifyEmailOTP:{entry:["resetErrors"],invoke:{src:"verifyEmailOTP",id:"verifyEmailOTP",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:I({importTokenAttempts:({importTokenAttempts:l})=>l+1}),clearContext:I(()=>(d(Ee,null),d(Ue,null),d(Ye,null),{...Tt})),clearContextExceptTokens:I(({accessToken:l,refreshToken:a})=>({...Tt,accessToken:l,refreshToken:a})),saveSession:I({user:(l,{data:a})=>{var f;return((f=a==null?void 0:a.session)==null?void 0:f.user)||null},accessToken:(l,{data:a})=>{if(a.session){const{accessTokenExpiresIn:f,accessToken:v}=a.session,y=new Date(Date.now()+f*1e3);return d(Ee,y.toISOString()),{value:v,expiresAt:y,expiresInSeconds:f}}return d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(l,{data:a})=>{var f,v;const y=((f=a.session)==null?void 0:f.refreshToken)||null,S=((v=a.session)==null?void 0:v.refreshTokenId)||null;return y&&d(Ue,y),S&&d(Ye,S),{value:y}}}),savePATSession:I({user:(l,{data:a})=>{var f;return((f=a==null?void 0:a.session)==null?void 0:f.user)||null},accessToken:(l,{data:a})=>{if(a.session){const{accessTokenExpiresIn:f,accessToken:v}=a.session,y=new Date(Date.now()+f*1e3);return d(Ee,y.toISOString()),{value:v,expiresAt:y,expiresInSeconds:f}}return d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(l,{data:a})=>{var f,v;const y=((f=a.session)==null?void 0:f.refreshToken)||null,S=((v=a.session)==null?void 0:v.refreshTokenId)||null;return y&&d(Ue,y),S&&d(Ye,S),{value:y,isPAT:!0}}}),saveMfaTicket:I({mfa:(l,a)=>{var f;return(f=a.data)==null?void 0:f.mfa}}),resetTimer:I({refreshTimer:l=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:I({refreshTimer:(l,a)=>({startedAt:l.refreshTimer.startedAt,attempts:l.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:I({errors:({errors:l},{data:{error:a}})=>({...l,authentication:a})}),resetErrors:I({errors:l=>({}),importTokenAttempts:l=>0}),saveRegistrationError:I({errors:({errors:l},{data:{error:a}})=>({...l,registration:a})}),destroyRefreshToken:I({refreshToken:l=>(d(Ue,null),d(Ye,null),{value:null})}),destroyAccessToken:I({accessToken:l=>(d(Ee,null),{value:null,expiresAt:null,expiresInSeconds:null})}),cleanUrl:()=>{c&&Xe("refreshToken")&&(ir("refreshToken"),ir("type"))},broadcastToken:l=>{if(c&&r)try{new BroadcastChannel(r).postMessage({type:"broadcast_token",payload:{token:l.refreshToken.value}})}catch{}}},guards:{isAnonymous:(l,a)=>{var f;return!!((f=l.user)!=null&&f.isAnonymous)},isSignedIn:l=>!!l.user&&!!l.accessToken.value,noToken:l=>!l.refreshToken.value,isRefreshTokenPAT:l=>{var a;return!!((a=l.refreshToken)!=null&&a.isPAT)},hasRefreshToken:l=>!!l.refreshToken.value,isAutoRefreshDisabled:()=>!o,refreshTimerShouldRefresh:l=>{const{expiresAt:a}=l.accessToken;if(!a)return!1;if(l.refreshTimer.lastAttempt)return l.refreshTimer.attempts>Xt?!1:Date.now()-l.refreshTimer.lastAttempt.getTime()>Math.pow(2,l.refreshTimer.attempts-1)*5e3;if(a.getTime()<Date.now()||s&&Date.now()-l.refreshTimer.startedAt.getTime()>s*1e3)return!0;const f=l.accessToken.expiresInSeconds;return f?a.getTime()-Date.now()-1e3*Math.min(Wr,f*.5)<=0:!1},shouldRetryImportToken:(l,a)=>l.importTokenAttempts<Xt&&(a.data.error.status===Qt||a.data.error.status>=500),unverified:(l,{data:{error:a}})=>a.status===401&&(a.message==="Email is not verified"||a.error==="unverified-user"),hasSession:(l,a)=>{var f;return!!((f=a.data)!=null&&f.session)},hasMfaTicket:(l,a)=>{var f;return!!((f=a.data)!=null&&f.mfa)},isUnauthorizedError:(l,{data:{error:a}})=>a.status===401},services:{signInPassword:(l,{email:a,password:f})=>ce(a)?At(f)?h("/signin/email-password",{email:a,password:f}):Promise.reject({error:wt}):Promise.reject({error:ae}),signInPAT:(l,{pat:a})=>h("/signin/pat",{personalAccessToken:a}),signInIdToken:(l,{provider:a,idToken:f,nonce:v})=>h("/signin/idtoken",{provider:a,idToken:f,...v&&{nonce:v}}),passwordlessSms:(l,{phoneNumber:a,options:f})=>{var v;return sr(a)?(v=l.user)!=null&&v.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:a,options:re(e,f)},l.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:a,options:re(e,f)}):Promise.reject({error:er})},passwordlessSmsOtp:(l,{phoneNumber:a,otp:f})=>sr(a)?h("/signin/passwordless/sms/otp",{phoneNumber:a,otp:f}):Promise.reject({error:er}),signInEmailOTP:(l,{email:a,options:f})=>ce(a)?h("/signin/otp/email",{email:a,options:re(e,f)}):Promise.reject({error:ae}),verifyEmailOTP:(l,{email:a,otp:f})=>ce(a)?h("/signin/otp/email/verify",{email:a,otp:f}):Promise.reject({error:ae}),passwordlessEmail:(l,{email:a,options:f})=>{var v;return ce(a)?(v=l.user)!=null&&v.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:a,options:re(e,f)},l.accessToken.value):h("/signin/passwordless/email",{email:a,options:re(e,f)}):Promise.reject({error:ae})},signInAnonymous:l=>h("/signin/anonymous"),signInMfaTotp:(l,a)=>{var f;const v=a.ticket||((f=l.mfa)==null?void 0:f.ticket);return v?mn(v)?h("/signin/mfa/totp",{ticket:v,otp:a.otp}):Promise.reject({error:Qr}):Promise.reject({error:Zr})},signInSecurityKeyEmail:async(l,{email:a})=>{if(!ce(a))throw new ye(ae);const f=await h("/signin/webauthn",{email:a});let v;try{v=await nr(f)}catch(y){throw new ye(y)}return h("/signin/webauthn/verify",{email:a,credential:v})},refreshToken:async(l,a)=>{const f=a.type==="TRY_TOKEN"?a.token:l.refreshToken.value;return{session:await h("/token",{refreshToken:f}),error:null}},signInSecurityKey:async()=>{try{const l=await h("/signin/webauthn",{});let a;try{a=await nr(l)}catch(f){throw new ye(f)}return h("/signin/webauthn/verify",{credential:a})}catch(l){throw new ye(l)}},signout:async(l,a)=>{const f=await h("/signout",{refreshToken:l.refreshToken.value,all:!!a.all},a.all?l.accessToken.value:void 0);if(r)try{new BroadcastChannel(r).postMessage({type:"signout"})}catch{}return f},signUpEmailPassword:async(l,{email:a,password:f,options:v,requestOptions:y})=>{var S;return ce(a)?At(f)?(S=l.user)!=null&&S.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:a,password:f,options:re(e,v)},l.accessToken.value,y==null?void 0:y.headers):h("/signup/email-password",{email:a,password:f,options:re(e,v)},null,y==null?void 0:y.headers):Promise.reject({error:wt}):Promise.reject({error:ae})},signUpSecurityKey:async(l,{email:a,options:f,requestOptions:v})=>{if(!ce(a))return Promise.reject({error:ae});const y=f==null?void 0:f.nickname;y&&delete f.nickname;const S=await h("/signup/webauthn",{email:a,options:f},null,v==null?void 0:v.headers);let w;try{w=await hn(S)}catch(T){throw new ye(T)}return h("/signup/webauthn/verify",{credential:w,options:{redirectTo:f==null?void 0:f.redirectTo,nickname:y}})},importRefreshToken:async l=>{if(l.user&&l.refreshToken.value&&l.accessToken.value&&l.accessToken.expiresAt)return{session:{accessToken:l.accessToken.value,accessTokenExpiresIn:l.accessToken.expiresAt.getTime()-Date.now(),refreshToken:l.refreshToken.value,user:l.user},error:null};let a=null;if(c){const v=Xe("refreshToken")||null;if(v)try{return{session:await h("/token",{refreshToken:v}),error:null}}catch(y){a=y.error}else{const y=Xe("error"),S=Xe("errorDescription");if(y&&S!=="social user already exists")return Promise.reject({session:null,error:{status:oe,error:y,message:S||y}})}}const f=await u(Ue);if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(v){a=v.error}return a?Promise.reject({error:a,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:l})=>Math.pow(2,l-1)*5e3}})},wn=({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:I({error:n=>ae}),saveRequestError:I({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!ce(i)},services:{requestChange:async(n,{email:i,options:s})=>(await te(`${t}/user/email/change`,{newEmail:i,options:re(e,s)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),Tn=({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:I({error:r=>wt}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!At(n)},services:{requestChange:(r,{password:n,ticket:i})=>te(`${t}/user/password`,{newPassword:n,ticket:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ys=({backendUrl:t,interpreter:e})=>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:I({error:r=>Jr}),saveInvalidMfaCodeError:I({error:r=>Xr}),saveError:I({error:(r,{data:{error:n}})=>n}),saveGeneration:I({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:X((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS"),reportGeneratedSuccess:X("GENERATED"),reportGeneratedError:X(r=>({type:"GENERATED_ERROR",error:r.error}))},guards:{invalidMfaCode:(r,{code:n})=>!n,invalidMfaType:(r,{activeMfaType:n})=>!n||n!=="totp"},services:{generate:async r=>{const{data:n}=await gn(`${t}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:i})=>te(`${t}/user/mfa`,{code:n,activeMfaType:i},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Sn=({backendUrl:t,clientUrl:e})=>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:I({error:r=>ae}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ce(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:re(e,i)})}}),bn=({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:I({error:r=>ae}),saveRequestError:I({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!ce(n)},services:{request:async(r,{email:n,options:i})=>(await te(`${t}/user/email/send-verification-email`,{email:n,options:re(e,i)})).data}});class or{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,broadcastKey:c,devTools:u,...d}){var h;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=En({...d,backendUrl:s,clientUrl:o,broadcastKey:c,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined"&&c)try{this._channel=new BroadcastChannel(c),r&&((h=this._channel)==null||h.addEventListener("message",l=>{var a;const{type:f,payload:v}=l.data;if(f==="broadcast_token"){const y=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&v.token&&v.token!==y&&this.interpreter.send("TRY_TOKEN",{token:v.token})}})),this._channel.addEventListener("message",l=>{const{type:a}=l.data;a==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context,accessToken:{...this.machine.context.accessToken},refreshToken:{...this.machine.context.refreshToken}};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const c=this.machine.withContext(o);this._interpreter||(this._interpreter=n||xe(c,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(u=>u())),this._interpreter.start(c.initialState),this._subscriptionsQueue.forEach(u=>u(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 kn extends or{constructor({...e}){super({...e,autoSignIn:Je()&&e.autoSignIn,autoRefreshToken:Je()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const gs=kn,An=async({backendUrl:t,interpreter:e},r)=>{try{const{data:n}=await te(`${t}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let i;try{i=await hn(n)}catch(o){throw new ye(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},On=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),In=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),ms=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),Es=(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})})}),Rn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),xn=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),_n=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value,refreshToken:n.context.refreshToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),Pn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_PASSWORD",{email:e,password:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1});t.onTransition(s=>{s.matches("registration.incomplete.failed")?n({error:s.context.errors.registration||null,isError:!0,isSuccess:!1}):s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),Nn=(t,e)=>new Promise(r=>{const{changed:n,context:i}=t.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});t.onTransition(s=>{s.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):s.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):s.matches({authentication:"signedIn"})&&r({accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:s.context.user})})}),Un=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:c}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let u;try{u=await nr(c)}catch(d){throw new ye(d)}try{const{data:{session:d},error:h}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:u},o);d&&!h&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:d}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(d){const{error:h}=d;r({error:h,isError:!0,isSuccess:!1,elevated:!1})}}),Dn=(t,e,r)=>new Promise(n=>{const{changed:i,context:s}=t.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!i)return n({accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,error:ee,isError:!0,isSuccess:!1,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:o.context.user})})}),Cn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),cr=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Mn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Ln=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:rn});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),ur=(t,e,r,n,i)=>new Promise(s=>{const{changed:o,context:c}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n,requestOptions:i});if(!o)return s({error:ee,accessToken:c.accessToken.value,refreshToken:c.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:c.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?s({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?s({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&s({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),jn=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_SECURITY_KEY",{email:e,options:r,requestOptions:n});if(!s)return i({error:ee,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(c=>{c.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:c.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):c.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:c.context.accessToken.value,refreshToken:c.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:c.context.user})})}),$n=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("SIGNIN_EMAIL_OTP",{email:e,options:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,needsOtp:!1});t.onTransition(s=>{s.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!0,needsOtp:!0}):s.matches("registration.incomplete.failed")&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Fn=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"VERIFY_EMAIL_OTP",email:e,otp:r});if(!i)return n({error:ee,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Hn=(t,{provider:e,idToken:r,nonce:n})=>new Promise(i=>{const{changed:s}=t.send("SIGNIN_ID_TOKEN",{provider:e,idToken:r,...n&&{nonce:n}});s||i({isSuccess:!1,isError:!0,error:ee,user:null,accessToken:null,refreshToken:null}),t.onTransition(o=>{if(o.matches({authentication:{signedOut:"failed"}}))return i({accessToken:null,refreshToken:null,user:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1});if(o.matches({authentication:"signedIn"}))return i({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,user:o.context.user,error:null,isError:!1,isSuccess:!0})})}),qn=async({backendUrl:t,interpreter:e},{provider:r,idToken:n,nonce:i})=>{try{return await te(`${t}/link/idtoken`,{provider:r,idToken:n,...i&&{nonce:i}},e==null?void 0:e.getSnapshot().context.accessToken.value),{isError:!1,error:null,isSuccess:!0}}catch(s){const{error:o}=s;return{isError:!0,error:o,isSuccess:!1}}},Vn=t=>new Promise(e=>{const{changed:r,context:n}=t.send({type:"SIGNIN_SECURITY_KEY"});if(!r)return e({accessToken:n.accessToken.value,refreshToken:n.refreshToken.value,error:ee,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:n.user});t.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?e({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?e({accessToken:null,refreshToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&e({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),ws=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.toISOString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:i?{id:i.id||null,personalAccessToken:i.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(i){const{error:s}=i;return{isError:!0,error:s,isSuccess:!1,data:null}}};class Kn{constructor({url:e,broadcastKey:r,autoRefreshToken:n=!0,autoSignIn:i=!0,clientStorage:s,clientStorageType:o,refreshIntervalTime:c,start:u=!0}){var d;this.url=e,this._client=new or({backendUrl:e,clientUrl:typeof window!="undefined"&&((d=window.location)==null?void 0:d.origin)||"",broadcastKey:r,autoRefreshToken:n,autoSignIn:i,start:u,clientStorage:s,clientStorageType:o,refreshIntervalTime:c})}async signUp(e,r){const n=await this.waitUntilReady();if("securityKey"in e){const{email:c,options:u}=e;return ie(await jn(n,c,u,r))}const{email:i,password:s,options:o}=e;return ie(await ur(n,i,s,o,r))}async connectProvider(e){const r=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:n,options:i}=e,s=kt(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,{...i,connect:r}));return Je()&&(window.location.href=s),{providerUrl:s}}async signInIdToken(e){const r=await this.waitUntilReady(),n=await Hn(r,e);return{...ie(n),mfa:null}}async linkIdToken(e){return qn(this._client,e)}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await _n(r);return{...ie(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=kt(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,i));return Je()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Pn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:nn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...ie(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Nn(r,e.email);return{...ie(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await ar(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Mn(r,e.phoneNumber,e.otp);return{...ie(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await cr(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Dn(r,e.otp,e.ticket);return{...ie(n),mfa:null}}return{error:on,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Cn(r,e);return ie(n)}async signInEmailOTP(e,r){const n=await this.waitUntilReady(),{error:i}=await $n(n,e,r);return{error:i,session:null,mfa:null}}async verifyEmailOTP(e,r){const n=await this.waitUntilReady(),i=await Fn(n,e,r);return{...ie(i),mfa:null}}async signInSecurityKey(){const e=await this.waitUntilReady(),r=await Vn(e);return{...ie(r),mfa:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await Ln(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(Sn(this._client)).start(),{error:i}=await Rn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(Tn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(bn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(wn(this._client)).start(),{error:i}=await On(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await ar(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await cr(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await ur(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await An(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Un(this._client,e),mfa:null}}async createPAT(e,r){return ws(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(We(s))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{(i.type==="SIGNED_IN"||i.type==="SIGNED_OUT")&&e(i.type,We(s))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var e;const r=((e=this.client.interpreter)==null?void 0:e.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:r}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:r}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?pr(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const i=e||r.getSnapshot().context.refreshToken.value;if(!i)return n({session:null,error:en});const{changed:s}=r.send("TRY_TOKEN",{token:i});if(!s)return n({session:null,error:tn});r.onTransition(o=>{o.matches({token:{idle:"error"}})?n({session:null,error:sn}):o.event.type==="TOKEN_CHANGED"&&n({session:We(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return We((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}async initWithSession({session:e}){this.client.start({initialSession:e}),await this.waitUntilReady()}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Ts=typeof self=="object"?self.FormData:window.FormData;const lr=Yt(Ts);let Gn=globalThis.fetch;const dr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:c,headers:u={}}={})=>{var d;const h={...u};s&&e.append("bucket-id",s),o&&(h["x-hasura-admin-secret"]=o),r&&(h.Authorization=`Bearer ${r}`);const l=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof lr&&(Gn=Jt().fetch);const a=await Gn(l,{method:"POST",headers:h,body:e}),f=await a.json();return a.ok?{fileMetadata:f,error:null}:{error:{status:a.status,message:((d=f==null?void 0:f.error)==null?void 0:d.message)||a.statusText,error:a.statusText},fileMetadata:null}}catch(a){return{error:{status:0,message:a.message,error:a.message},fileMetadata:null}}return new Promise(a=>{let f=new XMLHttpRequest;f.responseType="json",f.onload=()=>{var v,y,S,w,T,b,O,M;if(f.status<200||f.status>=300){const D={error:(T=(w=(y=(v=f.response)==null?void 0:v.error)==null?void 0:y.message)!=null?w:(S=f.response)==null?void 0:S.error)!=null?T:f.response,message:(M=(O=(b=f.response)==null?void 0:b.error)==null?void 0:O.message)!=null?M:f.response,status:f.status};return a({fileMetadata:null,error:D})}return a({fileMetadata:f.response,error:null})},f.onerror=()=>{const v={error:f.statusText,message:f.statusText,status:f.status};return a({fileMetadata:null,error:v})},c&&f.upload.addEventListener("progress",c,!1),f.open("POST",l,!0),Object.entries(h).forEach(([v,y])=>{f.setRequestHeader(v,y)}),f.send(e)})};function Ot(t,e){if(!e||Object.keys(e).length===0)return t;const r=new URL(t),n=Object.entries(e).reduce((i,[s,o])=>({...i,[s.charAt(0)]:o}),{});return Object.entries(n).forEach(([i,s])=>{s&&r.searchParams.set(i,s)}),r.toString()}let Qe;typeof Qe=="undefined"&&(Qe=Jt().fetch);class Bn{constructor({url:e}){this.headers={},this.url=e}async uploadFormData({formData:e,bucketId:r,headers:n}){const{error:i,fileMetadata:s}=await dr(this.url,e,{bucketId:r,headers:{...this.headers,...n},accessToken:this.accessToken,adminSecret:this.adminSecret});return i?{fileMetadata:null,error:i}:s&&!("processedFiles"in s)?{fileMetadata:{processedFiles:[s]},error:null}:{fileMetadata:s,error:null}}async uploadFile({file:e,bucketId:r,id:n,name:i,headers:s}){const o=typeof window=="undefined"?new lr:new FormData;o.append("file[]",e),o.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:c,fileMetadata:u}=await dr(this.url,o,{accessToken:this.accessToken,adminSecret:this.adminSecret,bucketId:r,fileId:n,name:i,headers:{...this.headers,...s}});return c?{fileMetadata:null,error:c}:u&&"processedFiles"in u?{fileMetadata:u.processedFiles[0],error:null}:{fileMetadata:u,error:null}}async downloadFile(e){try{const{fileId:r,headers:n,...i}=e,s=Ot(`${this.url}/files/${r}`,i),o=await Qe(s,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!o.ok)throw new Error(await o.text());return{file:await o.blob(),error:null}}catch(r){return{file:null,error:r}}}async getPresignedUrl(e){try{const{fileId:r,headers:n}=e,i=await Qe(`${this.url}/files/${r}/presignedurl`,{method:"GET",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!i.ok)throw new Error(await i.text());return{presignedUrl:await i.json(),error:null}}catch(r){return{presignedUrl:null,error:r}}}async delete(e){try{const{fileId:r,headers:n}=e,i=await Qe(`${this.url}/files/${r}`,{method:"DELETE",headers:{...this.generateAuthHeaders(),...this.headers,...n}});if(!i.ok)throw new Error(await i.text());return{error:null}}catch(r){return{error:r}}}setAccessToken(e){return this.accessToken=e,this}setAdminSecret(e){return this.adminSecret=e,this}getHeaders(){return this.headers}setHeaders(e){return e?(this.headers={...this.headers,...e},this):this}unsetHeaders(){const e=this.headers["x-hasura-role"];return this.headers=e?{"x-hasura-role":e}:{},this}generateAuthHeaders(){if(!(!this.adminSecret&&!this.accessToken))return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:{Authorization:`Bearer ${this.accessToken}`}}}class zn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new Bn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return Ot(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,headers:n,...i}=e,{presignedUrl:s,error:o}=await this.api.getPresignedUrl(e);if(o)return{presignedUrl:null,error:o};if(!s)return{presignedUrl:null,error:new Error("Invalid file id")};const c=Ot(s.url,i);return{presignedUrl:{...s,url:c},error:null}}async download(e){const{file:r,error:n}=await this.api.downloadFile(e);return n?{file:null,error:n}:r?{file:r,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}getHeaders(){return this.api.getHeaders()}setHeaders(e){return this.api.setHeaders(e),this}unsetHeaders(){return this.api.unsetHeaders(),this}}let hr;typeof hr=="undefined"&&(hr=lr);const It={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Yn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...It},initial:"idle",on:{DESTROY:{actions:"sendDestroy",target:"stopped"}},states:{idle:{on:{ADD:{actions:"addFile"},UPLOAD:{cond:"hasFile",target:"uploading"}}},uploading:{entry:"resetProgress",on:{UPLOAD_PROGRESS:{actions:["incrementProgress","sendProgress"]},UPLOAD_DONE:"uploaded",UPLOAD_ERROR:"error",CANCEL:"idle"},invoke:{src:"uploadFile"}},uploaded:{entry:["setFileMetadata","sendDone"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},error:{entry:["setError","sendError"],on:{ADD:{actions:"addFile",target:"idle"},UPLOAD:{actions:"resetContext",target:"uploading"}}},stopped:{type:"final"}}},{guards:{hasFile:(t,e)=>!!t.file||!!e.file},actions:{incrementProgress:I({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:I({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:I({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:I({progress:t=>null,loaded:t=>0}),resetContext:I(t=>It),addFile:I({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new hr;i.append("file[]",n);let s=0;return dr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const c=o.total?Math.round(o.loaded*n.size/o.total):0,u=c-s;s=c,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(c*100/o.total):0,loaded:c,additions:u})}}).then(({fileMetadata:o,error:c})=>{if(c&&r({type:"UPLOAD_ERROR",error:c}),o&&!("processedFiles"in o)){const{id:u,bucketId:d}=o;r({type:"UPLOAD_DONE",id:u,bucketId:d})}if(o&&"processedFiles"in o){const{id:u,bucketId:d}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:u,bucketId:d})}}),()=>{}}}}),{pure:fr,sendParent:Rt}=Di,Ss=()=>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:I((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:I({progress:t=>100,loaded:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetTotal:I({total:({files:t})=>t.map(e=>e.getSnapshot()).filter(e=>!e.matches("uploaded")).reduce((e,r)=>{var n;return e+((n=r.context.file)==null?void 0:n.size)},0)}),resetLoaded:I({loaded:t=>0}),startProgress:I({progress:t=>0}),resetProgress:I({progress:t=>null}),addItem:I((t,{files:e,bucketId:r})=>{const n=e?Array.isArray(e)?e:"item"in e?Array.from(e):[e]:[],i=t.total+n.reduce((o,c)=>o+c.size,0),s=Math.round(t.loaded*100/i);return{files:[...t.files,...n.map(o=>Qi(Yn().withConfig({actions:{sendProgress:Rt((c,{additions:u})=>({type:"UPLOAD_PROGRESS",additions:u})),sendDone:Rt("UPLOAD_DONE"),sendError:Rt("UPLOAD_ERROR"),sendDestroy:Rt("REMOVE")}}).withContext({...It,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:I({files:t=>t.files.filter(e=>{var r,n;const i=(r=e.getSnapshot())==null?void 0:r.matches("stopped");return i&&((n=e.stop)==null||n.call(e)),!i})}),clearList:fr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:fr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:fr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),bs=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),ks=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),As=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Ze(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(As);if(i!=null&&i.groups){const{protocol:s,host:o,port:c}=i.groups,u=Rs(e);return u||(o==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${s||"http"}://localhost:${c||1337}/v1/${e}`):c?`${s||"https"}://local.${e}.local.nhost.run:${c}/v1`:`${s||"https"}://local.${e}.local.nhost.run/v1`)}if(!n)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${r}.${e}.${n}.nhost.run/v1`}function Os(){return typeof window!="undefined"}function Is(){return typeof process!="undefined"&&process.env}function Rs(t){return Os()||!Is()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function xs(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Wn(t){const e="subdomain"in t?Ze(t,"auth"):t.authUrl,{subdomain:r,region:n}=t;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Kn({url:e,broadcastKey:`${r}${n!=null?n:"local"}`,...t})}function _s(t,e){return e=e||{},new Promise(function(r,n){var i=new XMLHttpRequest,s=[],o=[],c={},u=function(){return{ok:(i.status/100|0)==2,statusText:i.statusText,status:i.status,url:i.responseURL,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},clone:u,headers:{keys:function(){return s},entries:function(){return o},get:function(h){return c[h.toLowerCase()]},has:function(h){return h.toLowerCase()in c}}}};for(var d in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(h,l,a){s.push(l=l.toLowerCase()),o.push([l,a]),c[l]=c[l]?c[l]+","+a:a}),r(u())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(d,e.headers[d]);i.send(e.body||null)})}const Jn=is(Object.freeze(Object.defineProperty({__proto__:null,default:_s},Symbol.toStringTag,{value:"Module"})));var Ps=self.fetch||(self.fetch=Jn.default||Jn);const Xn=Yt(Ps);function Qn(t){const e="subdomain"in t?Ze(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Zn({url:e,...t})}class Zn{constructor(e){this.headers={};const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n}async call(e,r,n){var o,c;const i={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers,...this.headers},s=xs(this.url,e);try{const u=await Xn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!u.ok){let h;return(o=u.headers.get("content-type"))!=null&&o.includes("application/json")?h=await u.json():h=await u.text(),{res:null,error:{message:h,error:u.statusText,status:u.status}}}let d;return(c=u.headers.get("content-type"))!=null&&c.includes("application/json")?d=await u.json():d=await u.text(),{res:{data:d,status:u.status,statusText:u.statusText},error:null}}catch(u){const d=u;return{res:null,error:{message:d.message,status:d.name==="AbortError"?0:500,error:d.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function Ns(t,e,r){return t.document?t:{document:t,variables:e,config:r}}function ei(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 Us(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=ei(n)}catch{}return{query:t,operationName:r}}const e=ei(t);return{query:Se.print(t),operationName:e}}class Ds{constructor(e){this.headers={},this.isAccessTokenValidOrNull=()=>{if(!this.accessToken)return!0;try{const i=pr(this.accessToken);return i.exp!=null&&i.exp*1e3>Date.now()}catch(i){return console.error("Error decoding token:",i),!1}},this.awaitForValidAccessTokenOrNull=async()=>{if(this.isAccessTokenValidOrNull())return!0;const i=()=>this.isAccessTokenValidOrNull()?Promise.resolve(!0):new Promise(s=>{setTimeout(()=>i().then(s),100)});return i()};const{url:r,adminSecret:n}=e;this._url=r,this.accessToken=null,this.adminSecret=n}async request(e,...r){const[n,i]=r,s=Ns(e,n,i),{headers:o,...c}=i||{},{query:u,operationName:d}=Us(s.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const h=await Xn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:d,query:u,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...o},...c});if(!h.ok)return{data:null,error:{error:h.statusText,message:h.statusText,status:h.status}};const{data:l,errors:a}=await h.json();return a?{data:null,error:a}: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(h){const l=h;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}getHeaders(){return this.headers}setHeaders(e){e&&(this.headers={...this.headers,...e})}unsetHeaders(){const e=this.headers["x-hasura-role"];this.headers=e?{"x-hasura-role":e}:{}}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function ti(t){const e="subdomain"in t?Ze(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new Ds({url:e,...t})}function ri(t){const e="subdomain"in t?Ze(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new zn({url:e,...t})}const Cs=t=>new ni(t);class ni{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:c,start:u=!0,...d}){this.auth=Wn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:u,...d}),this.storage=ri({adminSecret:o,...d}),this.functions=Qn({adminSecret:o,...d}),this.graphql=ti({adminSecret:o,...d}),this.auth.onAuthStateChanged((h,l)=>{if(h==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const a=l==null?void 0:l.accessToken;this.storage.setAccessToken(a),this.functions.setAccessToken(a),this.graphql.setAccessToken(a)}),this.auth.onTokenChanged(h=>{const l=h==null?void 0:h.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this._adminSecret=o,this.devTools=c}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}setRole(e){this.graphql.setHeaders({"x-hasura-role":e}),this.storage.setHeaders({"x-hasura-role":e}),this.functions.setHeaders({"x-hasura-role":e})}unsetRole(){this.graphql.setHeaders((({"x-hasura-role":e,...r})=>r)(this.graphql.getHeaders())),this.storage.setHeaders((({"x-hasura-role":e,...r})=>r)(this.storage.getHeaders())),this.functions.setHeaders((({"x-hasura-role":e,...r})=>r)(this.functions.getHeaders()))}}g.AuthClient=or,g.AuthClientSSR=gs,g.AuthCookieClient=kn,g.CodifiedError=ye,g.EMAIL_NEEDS_VERIFICATION=nn,g.HasuraAuthClient=Kn,g.HasuraStorageApi=Bn,g.HasuraStorageClient=zn,g.INITIAL_FILE_CONTEXT=It,g.INITIAL_MACHINE_CONTEXT=Tt,g.INVALID_EMAIL_ERROR=ae,g.INVALID_MFA_CODE_ERROR=Xr,g.INVALID_MFA_TICKET_ERROR=Qr,g.INVALID_MFA_TYPE_ERROR=Jr,g.INVALID_PASSWORD_ERROR=wt,g.INVALID_PHONE_NUMBER_ERROR=er,g.INVALID_REFRESH_TOKEN=sn,g.INVALID_SIGN_IN_METHOD=on,g.MIN_PASSWORD_LENGTH=Yr,g.NETWORK_ERROR_CODE=Qt,g.NHOST_JWT_EXPIRES_AT_KEY=Ee,g.NHOST_REFRESH_TOKEN_ID_KEY=Ye,g.NHOST_REFRESH_TOKEN_KEY=Ue,g.NO_MFA_TICKET_ERROR=Zr,g.NO_REFRESH_TOKEN=en,g.NhostClient=ni,g.NhostFunctionsClient=Zn,g.OTHER_ERROR_CODE=Zt,g.REFRESH_TOKEN_MAX_ATTEMPTS=Xt,g.STATE_ERROR_CODE=De,g.TOKEN_REFRESHER_RUNNING_ERROR=tn,g.TOKEN_REFRESH_MARGIN_SECONDS=Wr,g.USER_ALREADY_SIGNED_IN=ee,g.USER_NOT_ANONYMOUS=os,g.USER_UNAUTHENTICATED=rn,g.VALIDATION_ERROR_CODE=oe,g.activateMfaPromise=Es,g.addSecurityKeyPromise=An,g.appendImageTransformationParameters=Ot,g.changeEmailPromise=On,g.changePasswordPromise=In,g.createAuthClient=Wn,g.createAuthMachine=En,g.createChangeEmailMachine=wn,g.createChangePasswordMachine=Tn,g.createEnableMfaMachine=ys,g.createFileUploadMachine=Yn,g.createFunctionsClient=Qn,g.createGraphqlClient=ti,g.createMultipleFilesUploadMachine=Ss,g.createNhostClient=Cs,g.createResetPasswordMachine=Sn,g.createSendVerificationEmailMachine=bn,g.createStorageClient=ri,g.elevateEmailSecurityKeyPromise=Un,g.encodeQueryParameters=kt,g.generateQrCodePromise=ms,g.getAuthenticationResult=ie,g.getFetch=gn,g.getParameterByName=Xe,g.getSession=We,g.isBrowser=Je,g.isValidEmail=ce,g.isValidPassword=At,g.isValidPhoneNumber=sr,g.isValidTicket=mn,g.linkIdTokenPromise=qn,g.localStorageGetter=fn,g.localStorageSetter=pn,g.postFetch=te,g.removeParameterFromWindow=ir,g.resetPasswordPromise=Rn,g.rewriteRedirectTo=re,g.sendVerificationEmailPromise=xn,g.signInAnonymousPromise=_n,g.signInEmailOTPPromise=$n,g.signInEmailPasswordPromise=Pn,g.signInEmailPasswordlessPromise=ar,g.signInEmailSecurityKeyPromise=Nn,g.signInIdTokenPromise=Hn,g.signInMfaTotpPromise=Dn,g.signInPATPromise=Cn,g.signInSecurityKeyPromise=Vn,g.signInSmsPasswordlessOtpPromise=Mn,g.signInSmsPasswordlessPromise=cr,g.signOutPromise=Ln,g.signUpEmailPasswordPromise=ur,g.signUpEmailSecurityKeyPromise=jn,g.uploadFilePromise=bs,g.uploadMultipleFilesPromise=ks,g.urlFromSubdomain=Ze,g.verifyEmailOTPPromise=Fn,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
22
22
|
//# sourceMappingURL=nhost-js.umd.js.map
|