@nhost/nhost-js 3.1.0 → 3.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/nhost.d.ts +21 -4
- package/dist/clients/nhost.d.ts.map +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +21 -4
- package/dist/index.esm.js.map +1 -1
- package/package.json +2 -2
- package/umd/nhost-js.umd.js +1 -1
- package/umd/nhost-js.umd.js.map +1 -1
package/umd/nhost-js.umd.js
CHANGED
|
@@ -18,5 +18,5 @@ Event: `).concat(JSON.stringify(event)));else if(this.status!==W.Running)throw n
|
|
|
18
18
|
`).concat(O.message))}if(E&&S){l.target!==void 0&&(c=l.target),u.push.apply(u,q([],P(l.actions),!1)),h=l;break}}}catch(O){n={error:O}}finally{try{d&&!d.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}if(h){if(!c.length)return{transitions:[h],exitSet:[],configuration:e.value?[this]:[],source:e,actions:u};var T=B(c.map(function(O){return s.getRelativeStateNodes(O,e.historyValue)})),b=!!h.internal;return{transitions:[h],exitSet:b?[]:B(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,h,a,d,l=this,f=o?Ve([],this.getStateNodes(o.value)):[],v=new Set;try{for(var y=x(Array.from(e).sort(function(k,F){return k.order-F.order})),S=y.next();!S.done;S=y.next()){var E=S.value;(!Be(f,E)||Be(n.exitSet,E)||E.parent&&v.has(E.parent))&&v.add(E)}}catch(k){c={error:k}}finally{try{S&&!S.done&&(h=y.return)&&h.call(y)}finally{if(c)throw c.error}}try{for(var T=x(f),b=T.next();!b.done;b=T.next()){var E=b.value;(!Be(e,E)||Be(n.exitSet,E.parent))&&n.exitSet.push(E)}}catch(k){a={error:k}}finally{try{b&&!b.done&&(d=T.return)&&d.call(T)}finally{if(a)throw a.error}}n.exitSet.sort(function(k,F){return F.order-k.order});var O=Array.from(v).sort(function(k,F){return k.order-F.order}),$=new Set(n.exitSet),C=B(O.map(function(k){var F=[];if(k.type!=="final")return F;var z=k.parent;if(!z.parent)return F;F.push(Fe(k.id,k.doneData),Fe(z.id,k.doneData?ut(k.doneData,i,s):void 0));var G=z.parent;return G.type==="parallel"&&Ge(G).every(function(Ee){return gt(n.configuration,Ee)})&&F.push(Fe(G.id)),F})),_=O.map(function(k){var F=k.onEntry,z=k.activities.map(function(G){return Cr(G)});return{type:"entry",actions:ce(u?q(q([],P(F),!1),P(z),!1):q(q([],P(z),!1),P(F),!1),l.machine.options.actions)}}).concat({type:"state_done",actions:C.map(function(k){return _r(k)})}),j=Array.from($).map(function(k){return{type:"exit",actions:ce(q(q([],P(k.onExit),!1),P(k.activities.map(function(F){return Mr(F)})),!1),l.machine.options.actions)}}),I=j.concat({type:"transition",actions:ce(n.actions,this.machine.options.actions)}).concat(_);if(r){var K=ce(B(q([],P(e),!1).sort(function(k,F){return F.order-k.order}).map(function(k){return k.onExit})),this.machine.options.actions).filter(function(k){return!Lt(k)});return I.concat({type:"stop",actions:K})}return I},t.prototype.transition=function(e,r,n,i){e===void 0&&(e=this.initialState);var s=Q(r),o;if(e instanceof oe)o=n===void 0?e:this.resolveState(oe.from(e,n));else{var u=U(e)?this.resolve(at(this.getResolvedPath(e))):this.resolve(e),c=n!=null?n:this.machine.context;o=this.resolveState(oe.from(u,c))}if(!V&&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 h=this._transition(o.value,o,s)||{transitions:[],configuration:[],exitSet:[],source:o,actions:[]},a=Ve([],this.getStateNodes(o.value)),d=h.configuration.length?Ve(a,h.configuration):a;return h.configuration=q([],P(d),!1),this.resolveTransition(h,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,h,a=this;s===void 0&&(s=ge);var d=e.configuration,l=!r||e.transitions.length>0,f=l?e.configuration:r?r.configuration:[],v=gt(f,this),y=l?Fi(this.machine,d):void 0,S=r?r.historyValue?r.historyValue:e.source?this.machine.historyValue(r.value):void 0:void 0,E=this.getActions(new Set(f),v,e,n,s,r,i),T=r?m({},r.activities):{};try{for(var b=x(E),O=b.next();!O.done;O=b.next()){var $=O.value;try{for(var C=(c=void 0,x($.actions)),_=C.next();!_.done;_=C.next()){var j=_.value;j.type===et?T[j.activity.id||j.activity.type]=j:j.type===tt&&(T[j.activity.id||j.activity.type]=!1)}}catch(ee){c={error:ee}}finally{try{_&&!_.done&&(h=C.return)&&h.call(C)}finally{if(c)throw c.error}}}}catch(ee){o={error:ee}}finally{try{O&&!O.done&&(u=b.return)&&u.call(b)}finally{if(o)throw o.error}}var I=P(qe(this,r,n,s,E,i,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),K=I[0],k=I[1],F=P(yi(K,Lt),2),z=F[0],G=F[1],Ee=K.filter(function(ee){var J;return ee.type===et&&((J=ee.activity)===null||J===void 0?void 0:J.type)===it}),Te=Ee.reduce(function(ee,J){return ee[J.activity.id]=Mi(J.activity,a.machine,k,s),ee},r?m({},r.children):{}),p=new oe({value:y||r.value,context:k,_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?G:[],activities:y?T:r?r.activities:{},events:[],configuration:f,transitions:e.transitions,children:Te,done:v,tags:Vr(f),machine:this}),w=n!==k;p.changed=s.name===st||w;var A=p.history;A&&delete A.history;var H=!v&&(this._transient||d.some(function(ee){return ee._transient}));if(!l&&(!H||s.name===_e))return p;var D=p;if(!v)for(H&&(D=this.resolveRaisedTransition(D,{type:vr},s,i));z.length;){var M=z.shift();D=this.resolveRaisedTransition(D,M._event,s,i)}var Me=D.changed||(A?!!D.actions.length||w||typeof A.value!=typeof D.value||!Br(D.value,A.value):void 0);return D.changed=Me,D.history=A,D},t.prototype.getStateNode=function(e){if(Ne(e))return this.machine.getStateNodeById(e);if(!this.states)throw new Error("Unable to retrieve child state '".concat(e,"' from '").concat(this.id,"'; no child states exist."));var r=this.states[e];if(!r)throw new Error("Child state '".concat(e,"' does not exist on '").concat(this.id,"'"));return r},t.prototype.getStateNodeById=function(e){var r=Ne(e)?e.slice(Vt.length):e;if(r===this.id)return this;var n=this.machine.idMap[r];if(!n)throw new Error("Child state node '#".concat(r,"' does not exist on machine '").concat(this.id,"'"));return n},t.prototype.getStateNodeByPath=function(e){if(typeof e=="string"&&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(Vt.length)];if(!r)throw new Error("Unable to find state node '".concat(e,"'"));return r.path}return Mt(e,this.delimiter)},Object.defineProperty(t.prototype,"initialStateValue",{get:function(){var e;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var r;if(this.type==="parallel")r=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 V||Y(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var r=ct(this.initialStateValue);return B(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?B(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)]:B(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=B(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 h=c.value,a=s[h];if(a.states)try{for(var d=(n=void 0,x(a.events)),l=d.next();!l.done;l=d.next()){var f=l.value;o.add("".concat(f))}}catch(v){n={error:v}}finally{try{l&&!l.done&&(i=d.return)&&i.call(d)}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
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:ce(ne(e.actions)),cond:Rr(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,h=_t(s,[typeof o=="symbol"?o:o+""]);i=B(Object.keys(h).map(function(T){!V&&T===_e&&Y(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(n.id,'".'));var b=ke(T,h[T]);return V||ts(n,T,b),b}).concat(ke(ze,c)))}var a=this.config.always?ke("",this.config.always):[],d=this.config.onDone?ke(String(Fe(this.id)),this.config.onDone):[];V||Y(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var l=B(this.invoke.map(function(T){var b=[];return T.onDone&&b.push.apply(b,q([],P(ke(String(He(T.id)),T.onDone)),!1)),T.onError&&b.push.apply(b,q([],P(ke(String(Re(T.id)),T.onError)),!1)),b})),f=this.after,v=B(q(q(q(q([],P(d),!1),P(l),!1),P(i),!1),P(a),!1).map(function(T){return ne(T).map(function(b){return n.formatTransition(b)})}));try{for(var y=x(f),S=y.next();!S.done;S=y.next()){var E=S.value;v.push(E)}}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!V&&!("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 R=jr,X=me;/*! js-cookie v3.0.5 | MIT */function wt(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 Bt(t,e){function r(i,s,o){if(typeof document!="undefined"){o=wt({},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("="),h=c.slice(1).join("=");try{var a=decodeURIComponent(c[0]);if(o[a]=t.read(h,a),i===a)break}catch{}}return i?o[i]:o}}return Object.create({set:r,get:n,remove:function(i,s){r(i,"",wt({},s,{expires:-1}))},withAttributes:function(i){return Bt(this.converter,wt({},this.attributes,i))},withConverter:function(i){return Bt(wt({},this.converter,i),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var Kt=Bt(ns,{path:"/"}),zt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function 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 Jt={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,h){h(e)}(this,function(c){var h=typeof u!="undefined"&&u||typeof self!="undefined"&&self||typeof h!="undefined"&&h,a={searchParams:"URLSearchParams"in h,iterable:"Symbol"in h&&"iterator"in Symbol,blob:"FileReader"in h&&"Blob"in h&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in h,arrayBuffer:"ArrayBuffer"in h};function d(p){return p&&DataView.prototype.isPrototypeOf(p)}if(a.arrayBuffer)var l=["[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&&l.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 w={next:function(){var A=p.shift();return{done:A===void 0,value:A}}};return a.iterable&&(w[Symbol.iterator]=function(){return w}),w}function E(p){this.map={},p instanceof E?p.forEach(function(w,A){this.append(A,w)},this):Array.isArray(p)?p.forEach(function(w){this.append(w[0],w[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(w){this.append(w,p[w])},this)}E.prototype.append=function(p,w){p=v(p),w=y(w);var A=this.map[p];this.map[p]=A?A+", "+w:w},E.prototype.delete=function(p){delete this.map[v(p)]},E.prototype.get=function(p){return p=v(p),this.has(p)?this.map[p]:null},E.prototype.has=function(p){return this.map.hasOwnProperty(v(p))},E.prototype.set=function(p,w){this.map[v(p)]=y(w)},E.prototype.forEach=function(p,w){for(var A in this.map)this.map.hasOwnProperty(A)&&p.call(w,this.map[A],A,this)},E.prototype.keys=function(){var p=[];return this.forEach(function(w,A){p.push(A)}),S(p)},E.prototype.values=function(){var p=[];return this.forEach(function(w){p.push(w)}),S(p)},E.prototype.entries=function(){var p=[];return this.forEach(function(w,A){p.push([A,w])}),S(p)},a.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function T(p){if(p.bodyUsed)return s.reject(new TypeError("Already read"));p.bodyUsed=!0}function b(p){return new s(function(w,A){p.onload=function(){w(p.result)},p.onerror=function(){A(p.error)}})}function O(p){var w=new FileReader,A=b(w);return w.readAsArrayBuffer(p),A}function $(p){var w=new FileReader,A=b(w);return w.readAsText(p),A}function C(p){for(var w=new Uint8Array(p),A=new Array(w.length),H=0;H<w.length;H++)A[H]=String.fromCharCode(w[H]);return A.join("")}function _(p){if(p.slice)return p.slice(0);var w=new Uint8Array(p.byteLength);return w.set(new Uint8Array(p)),w.buffer}function j(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:a.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:a.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():a.arrayBuffer&&a.blob&&d(p)?(this._bodyArrayBuffer=_(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.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):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return s.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return s.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=T(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?s.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):s.resolve(this._bodyArrayBuffer))}else return this.blob().then(O)}),this.text=function(){var p=T(this);if(p)return p;if(this._bodyBlob)return $(this._bodyBlob);if(this._bodyArrayBuffer)return s.resolve(C(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return s.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(F)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function K(p){var w=p.toUpperCase();return I.indexOf(w)>-1?w:p}function k(p,w){if(!(this instanceof k))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');w=w||{};var A=w.body;if(p instanceof k){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,w.headers||(this.headers=new E(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!A&&p._bodyInit!=null&&(A=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=w.credentials||this.credentials||"same-origin",(w.headers||!this.headers)&&(this.headers=new E(w.headers)),this.method=K(w.method||this.method||"GET"),this.mode=w.mode||this.mode||null,this.signal=w.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&A)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(A),(this.method==="GET"||this.method==="HEAD")&&(w.cache==="no-store"||w.cache==="no-cache")){var H=/([?&])_=[^&]*/;if(H.test(this.url))this.url=this.url.replace(H,"$1_="+new Date().getTime());else{var D=/\?/;this.url+=(D.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}k.prototype.clone=function(){return new k(this,{body:this._bodyInit})};function F(p){var w=new FormData;return p.trim().split("&").forEach(function(A){if(A){var H=A.split("="),D=H.shift().replace(/\+/g," "),M=H.join("=").replace(/\+/g," ");w.append(decodeURIComponent(D),decodeURIComponent(M))}}),w}function z(p){var w=new E,A=p.replace(/\r?\n[\t ]+/g," ");return A.split("\r").map(function(H){return H.indexOf(`
|
|
20
20
|
`)===0?H.substr(1,H.length):H}).forEach(function(H){var D=H.split(":"),M=D.shift().trim();if(M){var Me=D.join(":").trim();w.append(M,Me)}}),w}j.call(k.prototype);function G(p,w){if(!(this instanceof G))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');w||(w={}),this.type="default",this.status=w.status===void 0?200:w.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in w?w.statusText:"",this.headers=new E(w.headers),this.url=w.url||"",this._initBody(p)}j.call(G.prototype),G.prototype.clone=function(){return new G(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},G.error=function(){var p=new G(null,{status:0,statusText:""});return p.type="error",p};var Ee=[301,302,303,307,308];G.redirect=function(p,w){if(Ee.indexOf(w)===-1)throw new RangeError("Invalid status code");return new G(null,{status:w,headers:{location:p}})},c.DOMException=h.DOMException;try{new c.DOMException}catch{c.DOMException=function(w,A){this.message=w,this.name=A;var H=Error(w);this.stack=H.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function Te(p,w){return new s(function(A,H){var D=new k(p,w);if(D.signal&&D.signal.aborted)return H(new c.DOMException("Aborted","AbortError"));var M=new o;function Me(){M.abort()}M.onload=function(){var J={status:M.status,statusText:M.statusText,headers:z(M.getAllResponseHeaders()||"")};J.url="responseURL"in M?M.responseURL:J.headers.get("X-Request-URL");var xt="response"in M?M.response:M.responseText;setTimeout(function(){A(new G(xt,J))},0)},M.onerror=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},M.ontimeout=function(){setTimeout(function(){H(new TypeError("Network request failed"))},0)},M.onabort=function(){setTimeout(function(){H(new c.DOMException("Aborted","AbortError"))},0)};function ee(J){try{return J===""&&h.location.href?h.location.href:J}catch{return J}}M.open(D.method,ee(D.url),!0),D.credentials==="include"?M.withCredentials=!0:D.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&(a.blob?M.responseType="blob":a.arrayBuffer&&D.headers.get("Content-Type")&&D.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(M.responseType="arraybuffer")),w&&typeof w.headers=="object"&&!(w.headers instanceof E)?Object.getOwnPropertyNames(w.headers).forEach(function(J){M.setRequestHeader(J,y(w.headers[J]))}):D.headers.forEach(function(J,xt){M.setRequestHeader(xt,J)}),D.signal&&(D.signal.addEventListener("abort",Me),M.onreadystatechange=function(){M.readyState===4&&D.signal.removeEventListener("abort",Me)}),M.send(typeof D._bodyInit=="undefined"?null:D._bodyInit)})}Te.polyfill=!0,h.fetch||(h.fetch=Te,h.Headers=E,h.Request=k,h.Response=G),c.Headers=E,c.Request=k,c.Response=G,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)})(Jt,Jt.exports);var ss=Jt.exports;const Yt=Wt(ss),Ue="nhostRefreshToken",We="nhostRefreshTokenId",we="nhostRefreshTokenExpiresAt",Wr=3,Jr=60,Xt=5,Qt=0,Zt=1,ie=10,De=20;let Ce=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 ue={status:ie,error:"invalid-email",message:"Email is incorrectly formatted"},Yr={status:ie,error:"invalid-mfa-type",message:"MFA type is invalid"},Xr={status:ie,error:"invalid-mfa-code",message:"MFA code is invalid"},Et={status:ie,error:"invalid-password",message:"Password is incorrectly formatted"},er={status:ie,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},Qr={status:ie,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},Zr={status:ie,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},en={status:ie,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."},se={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:ie,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 le(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function tr(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),i=atob(n),s=new ArrayBuffer(i.length),o=new Uint8Array(s);for(let u=0;u<i.length;u++)o[u]=i.charCodeAt(u);return s}function an(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function cn(t){const{id:e}=t;return{...t,id:tr(e),transports:t.transports}}function un(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}let Z=class extends Error{constructor({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(l){throw cs({error:l,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 h;if(typeof o.getPublicKeyAlgorithm=="function")try{h=o.getPublicKeyAlgorithm()}catch(l){rr("getPublicKeyAlgorithm()",l)}let a;if(typeof o.getPublicKey=="function")try{const l=o.getPublicKey();l!==null&&(a=le(l))}catch(l){rr("getPublicKey()",l)}let d;if(typeof o.getAuthenticatorData=="function")try{d=le(o.getAuthenticatorData())}catch(l){rr("getAuthenticatorData()",l)}return{id:i,rawId:le(s),response:{attestationObject:le(o.attestationObject),clientDataJSON:le(o.clientDataJSON),transports:c,publicKeyAlgorithm:h,publicKey:a,authenticatorData:d},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 fn(t,e=!1){var r,n;if(!an())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)==null?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:h,response:a,type:d}=u;let l;return a.userHandle&&(l=ds(a.userHandle)),{id:c,rawId:le(h),response:{authenticatorData:le(a.authenticatorData),clientDataJSON:le(a.clientDataJSON),signature:le(a.signature),userHandle:l},type:d,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)},pn=(t,e)=>{if(t==="localStorage"||t==="web")return ps;if(t==="cookie")return r=>{var n;return St&&(n=Kt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},vn=(t,e)=>{if(t==="localStorage"||t==="web")return vs;if(t==="cookie")return(r,n)=>{St&&(n?Kt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Kt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},Je=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},de=({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},Ye=()=>typeof window!="undefined";let yn=globalThis.fetch;typeof EdgeRuntime!="string"&&(yn=Yt().fetch);const gn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await yn(t,s);if(!o.ok){const u=await o.json();return Promise.reject({error:u})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:o})}},te=async(t,e,r)=>gn(t,"POST",{token:r,body:e}),mn=(t,e)=>gn(t,"GET",{token:e}),At=(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 h=i.pathname;return o.pathname.length>1&&(h+=o.pathname.slice(1)),{...n,redirectTo:At(o.origin+h,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 nr(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const he=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,}))$/),kt=t=>!!t&&typeof t=="string"&&t.length>=Wr,ir=t=>!!t&&typeof t=="string",wn=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,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const u=pn(r,n),c=vn(r,n),h=async(a,d,l)=>(await te(`${t}${a}`,d,l)).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:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:R({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:R(()=>(c(we,null),c(Ue,null),c(We,null),{...Tt})),clearContextExceptRefreshToken:R(({refreshToken:{value:a}})=>(c(we,null),{...Tt,refreshToken:{value:a}})),saveSession:R({user:(a,{data:d})=>{var l;return((l=d==null?void 0:d.session)==null?void 0:l.user)||null},accessToken:(a,{data:d})=>{if(d.session){const{accessTokenExpiresIn:l,accessToken:f}=d.session,v=new Date(Date.now()+l*1e3);return c(we,v.toISOString()),{value:f,expiresAt:v,expiresInSeconds:l}}return c(we,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:d})=>{var l,f;const v=((l=d.session)==null?void 0:l.refreshToken)||null,y=((f=d.session)==null?void 0:f.refreshTokenId)||null;return v&&c(Ue,v),y&&c(We,y),{value:v}}}),savePATSession:R({user:(a,{data:d})=>{var l;return((l=d==null?void 0:d.session)==null?void 0:l.user)||null},accessToken:(a,{data:d})=>{if(d.session){const{accessTokenExpiresIn:l,accessToken:f}=d.session,v=new Date(Date.now()+l*1e3);return c(we,v.toISOString()),{value:f,expiresAt:v,expiresInSeconds:l}}return c(we,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:d})=>{var l,f;const v=((l=d.session)==null?void 0:l.refreshToken)||null,y=((f=d.session)==null?void 0:f.refreshTokenId)||null;return v&&c(Ue,v),y&&c(We,y),{value:v,isPAT:!0}}}),saveMfaTicket:R({mfa:(a,d)=>{var l;return(l=d.data)==null?void 0:l.mfa}}),resetTimer:R({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:R({refreshTimer:(a,d)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:R({errors:({errors:a},{data:{error:d}})=>({...a,authentication:d})}),resetErrors:R({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:R({errors:({errors:a},{data:{error:d}})=>({...a,registration:d})}),destroyRefreshToken:R({refreshToken:a=>(c(Ue,null),c(We,null),{value:null})}),cleanUrl:()=>{o&&Xe("refreshToken")&&(nr("refreshToken"),nr("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage({type:"broadcast_token",payload:{token:a.refreshToken.value}})}catch{}}},guards:{isAnonymous:(a,d)=>{var l;return!!((l=a.user)!=null&&l.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var d;return!!((d=a.refreshToken)!=null&&d.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:d}=a.accessToken;if(!d)return!1;if(d.getTime()<Date.now())return!0;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>Xt?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const l=a.accessToken.expiresInSeconds;return l?d.getTime()-Date.now()-1e3*Math.min(Jr,l*.5)<=0:!1},shouldRetryImportToken:(a,d)=>a.importTokenAttempts<Xt&&(d.data.error.status===Qt||d.data.error.status>=500),unverified:(a,{data:{error:d}})=>d.status===401&&(d.message==="Email is not verified"||d.error==="unverified-user"),hasSession:(a,d)=>{var l;return!!((l=d.data)!=null&&l.session)},hasMfaTicket:(a,d)=>{var l;return!!((l=d.data)!=null&&l.mfa)}},services:{signInPassword:(a,{email:d,password:l})=>he(d)?kt(l)?h("/signin/email-password",{email:d,password:l}):Promise.reject({error:Et}):Promise.reject({error:ue}),signInPAT:(a,{pat:d})=>h("/signin/pat",{personalAccessToken:d}),passwordlessSms:(a,{phoneNumber:d,options:l})=>{var f;return ir(d)?(f=a.user)!=null&&f.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:d,options:re(e,l)},a.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:d,options:re(e,l)}):Promise.reject({error:er})},passwordlessSmsOtp:(a,{phoneNumber:d,otp:l})=>ir(d)?h("/signin/passwordless/sms/otp",{phoneNumber:d,otp:l}):Promise.reject({error:er}),passwordlessEmail:(a,{email:d,options:l})=>{var f;return he(d)?(f=a.user)!=null&&f.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:d,options:re(e,l)},a.accessToken.value):h("/signin/passwordless/email",{email:d,options:re(e,l)}):Promise.reject({error:ue})},signInAnonymous:a=>h("/signin/anonymous"),signInMfaTotp:(a,d)=>{var l;const f=d.ticket||((l=a.mfa)==null?void 0:l.ticket);return f?wn(f)?h("/signin/mfa/totp",{ticket:f,otp:d.otp}):Promise.reject({error:Qr}):Promise.reject({error:Zr})},signInSecurityKeyEmail:async(a,{email:d})=>{if(!he(d))throw new Ce(ue);const l=await h("/signin/webauthn",{email:d});let f;try{f=await fn(l)}catch(v){throw new Ce(v)}return h("/signin/webauthn/verify",{email:d,credential:f})},refreshToken:async(a,d)=>{const l=d.type==="TRY_TOKEN"?d.token:a.refreshToken.value;return{session:await h("/token",{refreshToken:l}),error:null}},signout:async(a,d)=>{const l=await h("/signout",{refreshToken:a.refreshToken.value,all:!!d.all});try{new BroadcastChannel("nhost").postMessage({type:"signout"})}catch{}return l},signUpEmailPassword:async(a,{email:d,password:l,options:f})=>{var v;return he(d)?kt(l)?(v=a.user)!=null&&v.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:d,password:l,options:re(e,f)},a.accessToken.value):h("/signup/email-password",{email:d,password:l,options:re(e,f)}):Promise.reject({error:Et}):Promise.reject({error:ue})},signUpSecurityKey:async(a,{email:d,options:l})=>{if(!he(d))return Promise.reject({error:ue});const f=l==null?void 0:l.nickname;f&&delete l.nickname;const v=await h("/signup/webauthn",{email:d,options:l});let y;try{y=await hn(v)}catch(S){throw new Ce(S)}return h("/signup/webauthn/verify",{credential:y,options:{redirectTo:l==null?void 0:l.redirectTo,nickname:f}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let d=null;if(o){const f=Xe("refreshToken")||null;if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(v){d=v.error}else{const v=Xe("error"),y=Xe("errorDescription");if(v&&y!=="social user already exists")return Promise.reject({session:null,error:{status:ie,error:v,message:y||v}})}}const l=await u(Ue);if(l)try{return{session:await h("/token",{refreshToken:l}),error:null}}catch(f){d=f.error}return d?Promise.reject({error:d,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},Tn=({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:R({error:n=>ue}),saveRequestError:R({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!he(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}}),Sn=({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:R({error:r=>Et}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!kt(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:R({error:r=>Yr}),saveInvalidMfaCodeError:R({error:r=>Xr}),saveError:R({error:(r,{data:{error:n}})=>n}),saveGeneration:R({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 mn(`${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)}}),bn=({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:R({error:r=>ue}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!he(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:re(e,i)})}}),An=({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:R({error:r=>ue}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!he(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 sr{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:u,...c}){var h;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=En({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined")try{this._channel=new BroadcastChannel("nhost"),r&&((h=this._channel)==null||h.addEventListener("message",a=>{var d;const{type:l,payload:f}=a.data;if(l==="broadcast_token"){const v=(d=this.interpreter)==null?void 0:d.getSnapshot().context.refreshToken.value;this.interpreter&&f.token.data!==v&&this.interpreter.send("TRY_TOKEN",{token:f.token.data})}})),this._channel.addEventListener("message",a=>{const{type:d}=a.data;d==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||xe(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class kn extends sr{constructor({...e}){super({...e,autoSignIn:Ye()&&e.autoSignIn,autoRefreshToken:Ye()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const gs=kn,On=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 Ce(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},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,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),In=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),ms=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),ws=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),xn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),_n=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Pn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,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})})}),Nn=(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:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),or=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,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})})}),Un=(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:se,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})})}),Dn=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:u}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let c;try{c=await fn(u)}catch(h){throw new Ce(h)}try{const{data:{session:h},error:a}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:c},o);h&&!a&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:h}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(h){const{error:a}=h;r({error:a,isError:!0,isSuccess:!1,elevated:!1})}}),Cn=(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:se,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})})}),Mn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,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})})}),Ln=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),jn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:rn});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),cr=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:se,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),$n=(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:se,accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Es=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.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 Fn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:u=!0}){var c;this.url=e,this._client=new sr({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?de(await $n(r,n,i)):de(await cr(r,n,e.password,i))}async connectProvider(e){const r=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:n,options:i}=e,s=At(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,{...i,connect:r}));return Ye()&&(window.location.href=s),{providerUrl:s}}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Pn(r);return{...de(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=At(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,i));return Ye()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Nn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:nn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...de(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Un(r,e.email);return{...de(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await or(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Ln(r,e.phoneNumber,e.otp);return{...de(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Cn(r,e.otp,e.ticket);return{...de(n),mfa:null}}return{error:on,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Mn(r,e);return de(n)}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await jn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(bn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(Sn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(An(this._client)).start(),{error:i}=await _n(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(Tn(this._client)).start(),{error:i}=await Rn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await or(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await cr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await On(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Dn(this._client,e),mfa:null}}async createPAT(e,r){return Es(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(Je(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,Je(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:Je(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return Je((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Ts=typeof self=="object"?self.FormData:window.FormData;const ur=Wt(Ts);let Hn=globalThis.fetch;const lr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u,headers:c={}}={})=>{var h;const a={...c};s&&e.append("bucket-id",s),o&&(a["x-hasura-admin-secret"]=o),r&&(a.Authorization=`Bearer ${r}`);const d=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof ur&&(Hn=Yt().fetch);const l=await Hn(d,{method:"POST",headers:a,body:e}),f=await l.json();return l.ok?{fileMetadata:f,error:null}:{error:{status:l.status,message:((h=f==null?void 0:f.error)==null?void 0:h.message)||l.statusText,error:l.statusText},fileMetadata:null}}catch(l){return{error:{status:0,message:l.message,error:l.message},fileMetadata:null}}return new Promise(l=>{let f=new XMLHttpRequest;f.responseType="json",f.onload=()=>{var v,y,S,E,T;return f.status<200||f.status>=300?l({fileMetadata:null,error:{error:(y=(v=f.response)==null?void 0:v.error)!=null?y:f.response,message:(T=(E=(S=f.response)==null?void 0:S.error)==null?void 0:E.message)!=null?T:f.response,status:f.status}}):l({fileMetadata:f.response,error:null})},f.onerror=()=>l({fileMetadata:null,error:{error:f.statusText,message:f.statusText,status:f.status}}),u&&f.upload.addEventListener("progress",u,!1),f.open("POST",d,!0),Object.entries(a).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=Yt().fetch);class qn{constructor({url:e}){this.headers={},this.url=e}async uploadFormData({formData:e,bucketId:r,headers:n}){const{error:i,fileMetadata:s}=await lr(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 ur:new FormData;o.append("file[]",e),o.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:u,fileMetadata:c}=await lr(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 Gn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new qn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return Ot(`${this.url}/files/${r}`,n)}async getPresignedUrl(e){const{fileId:r,...n}=e,{presignedUrl:i,error:s}=await this.api.getPresignedUrl(e);if(s)return{presignedUrl:null,error:s};if(!i)return{presignedUrl:null,error:new Error("Invalid file id")};const o=Ot(i.url,n);return{presignedUrl:{...i,url:o},error:null}}async download(e){const{file:r,error:n}=await this.api.downloadFile(e);return n?{file:null,error:n}:r?{file:r,error:null}:{file:null,error:new Error("File does not exist")}}async delete(e){const{error:r}=await this.api.delete(e);return r?{error:r}:{error:null}}setAccessToken(e){return this.api.setAccessToken(e),this}setAdminSecret(e){return this.api.setAdminSecret(e),this}getHeaders(){return this.getHeaders()}setHeaders(e){return this.api.setHeaders(e),this}unsetHeaders(){return this.api.unsetHeaders(),this}}let dr;typeof dr=="undefined"&&(dr=ur);const Rt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Vn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...Rt},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:R({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:R({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:R({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:R({progress:t=>null,loaded:t=>0}),resetContext:R(t=>Rt),addFile:R({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new dr;i.append("file[]",n);let s=0;return lr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o&&!("processedFiles"in o)){const{id:c,bucketId:h}=o;r({type:"UPLOAD_DONE",id:c,bucketId:h})}if(o&&"processedFiles"in o){const{id:c,bucketId:h}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:c,bucketId:h})}}),()=>{}}}}),{pure:hr,sendParent:It}=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:R((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:R({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:R({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:R({loaded:t=>0}),startProgress:R({progress:t=>0}),resetProgress:R({progress:t=>null}),addItem:R((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(Vn().withConfig({actions:{sendProgress:It((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:It("UPLOAD_DONE"),sendError:It("UPLOAD_ERROR"),sendDestroy:It("REMOVE")}}).withContext({...Rt,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:R({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:hr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:hr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:hr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),bs=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),As=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ks=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Ze(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(ks);if(i!=null&&i.groups){const{protocol:s,host:o,port:u}=i.groups,c=Is(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 Rs(){return typeof process!="undefined"&&process.env}function Is(t){return Os()||!Rs()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function xs(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Bn(t){const e="subdomain"in t?Ze(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Fn({url:e,...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(a){return u[a.toLowerCase()]},has:function(a){return a.toLowerCase()in u}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,d,l){s.push(d=d.toLowerCase()),o.push([d,l]),u[d]=u[d]?u[d]+","+l:l}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}const Kn=is(Object.freeze(Object.defineProperty({__proto__:null,default:_s},Symbol.toStringTag,{value:"Module"})));var Ps=self.fetch||(self.fetch=Kn.default||Kn);const zn=Wt(Ps);function Wn(t){const e="subdomain"in t?Ze(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Jn({url:e,...t})}class Jn{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 zn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let h;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?h=await c.json():h=await c.text(),{res:{data:h,status:c.status,statusText:c.statusText},error:null}}catch(c){const h=c;return{res:null,error:{message:h.message,status:h.name==="AbortError"?0:500,error:h.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 Yn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function Us(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Yn(n)}catch{}return{query:t,operationName:r}}const e=Yn(t);return{query:Se.print(t),operationName:e}}class 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:h}=Us(s.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const a=await zn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...o},...u});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:d,errors:l}=await a.json();return l?{data:null,error:l}:typeof d!="object"||Array.isArray(d)||d===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:d,error:null}}catch(a){const d=a;return{data:null,error:{message:d.message,status:d.name==="AbortError"?0:500,error:d.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 Xn(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 Qn(t){const e="subdomain"in t?Ze(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Gn({url:e,...t})}const Cs=t=>new Zn(t);class Zn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...h}){this.auth=Bn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...h}),this.storage=Qn({adminSecret:o,...h}),this.functions=Wn({adminSecret:o,...h}),this.graphql=Xn({adminSecret:o,...h}),this.auth.onAuthStateChanged((a,d)=>{if(a==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const l=d==null?void 0:d.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this.auth.onTokenChanged(a=>{const d=a==null?void 0:a.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),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=sr,g.AuthClientSSR=gs,g.AuthCookieClient=kn,g.CodifiedError=Ce,g.EMAIL_NEEDS_VERIFICATION=nn,g.HasuraAuthClient=Fn,g.HasuraStorageApi=qn,g.HasuraStorageClient=Gn,g.INITIAL_FILE_CONTEXT=Rt,g.INITIAL_MACHINE_CONTEXT=Tt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=Xr,g.INVALID_MFA_TICKET_ERROR=Qr,g.INVALID_MFA_TYPE_ERROR=Yr,g.INVALID_PASSWORD_ERROR=Et,g.INVALID_PHONE_NUMBER_ERROR=er,g.INVALID_REFRESH_TOKEN=sn,g.INVALID_SIGN_IN_METHOD=on,g.MIN_PASSWORD_LENGTH=Wr,g.NETWORK_ERROR_CODE=Qt,g.NHOST_JWT_EXPIRES_AT_KEY=we,g.NHOST_REFRESH_TOKEN_ID_KEY=We,g.NHOST_REFRESH_TOKEN_KEY=Ue,g.NO_MFA_TICKET_ERROR=Zr,g.NO_REFRESH_TOKEN=en,g.NhostClient=Zn,g.NhostFunctionsClient=Jn,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=Jr,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=os,g.USER_UNAUTHENTICATED=rn,g.VALIDATION_ERROR_CODE=ie,g.activateMfaPromise=ws,g.addSecurityKeyPromise=On,g.appendImageTransformationParameters=Ot,g.changeEmailPromise=Rn,g.changePasswordPromise=In,g.createAuthClient=Bn,g.createAuthMachine=En,g.createChangeEmailMachine=Tn,g.createChangePasswordMachine=Sn,g.createEnableMfaMachine=ys,g.createFileUploadMachine=Vn,g.createFunctionsClient=Wn,g.createGraphqlClient=Xn,g.createMultipleFilesUploadMachine=Ss,g.createNhostClient=Cs,g.createResetPasswordMachine=bn,g.createSendVerificationEmailMachine=An,g.createStorageClient=Qn,g.elevateEmailSecurityKeyPromise=Dn,g.encodeQueryParameters=At,g.generateQrCodePromise=ms,g.getAuthenticationResult=de,g.getFetch=mn,g.getParameterByName=Xe,g.getSession=Je,g.isBrowser=Ye,g.isValidEmail=he,g.isValidPassword=kt,g.isValidPhoneNumber=ir,g.isValidTicket=wn,g.localStorageGetter=pn,g.localStorageSetter=vn,g.postFetch=te,g.removeParameterFromWindow=nr,g.resetPasswordPromise=xn,g.rewriteRedirectTo=re,g.sendVerificationEmailPromise=_n,g.signInAnonymousPromise=Pn,g.signInEmailPasswordPromise=Nn,g.signInEmailPasswordlessPromise=or,g.signInEmailSecurityKeyPromise=Un,g.signInMfaTotpPromise=Cn,g.signInPATPromise=Mn,g.signInSmsPasswordlessOtpPromise=Ln,g.signInSmsPasswordlessPromise=ar,g.signOutPromise=jn,g.signUpEmailPasswordPromise=cr,g.signUpEmailSecurityKeyPromise=$n,g.uploadFilePromise=bs,g.uploadMultipleFilesPromise=As,g.urlFromSubdomain=Ze,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
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 fn(t,e=!1){var r,n;if(!an())throw new Error("WebAuthn is not supported in this browser");let i;((r=t.allowCredentials)==null?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:h,response:a,type:d}=u;let l;return a.userHandle&&(l=ds(a.userHandle)),{id:c,rawId:le(h),response:{authenticatorData:le(a.authenticatorData),clientDataJSON:le(a.clientDataJSON),signature:le(a.signature),userHandle:l},type:d,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)},pn=(t,e)=>{if(t==="localStorage"||t==="web")return ps;if(t==="cookie")return r=>{var n;return St&&(n=Kt.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${t}' but no clientStorage has been given`);if(t==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(t==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(t==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};if(t==="custom"){if(e.getItem&&e.removeItem)return e.getItem;if(e.getItemAsync)return e.getItemAsync;throw Error(`clientStorageType is set to 'custom' but clientStorage is missing either "getItem" and "removeItem" properties or "getItemAsync" property`)}throw Error(`Unknown storage type: ${t}`)},vn=(t,e)=>{if(t==="localStorage"||t==="web")return vs;if(t==="cookie")return(r,n)=>{St&&(n?Kt.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Kt.remove(r))};if(!e)throw Error(`clientStorageType is set to '${t}' but no clienStorage has been given`);if(t==="react-native")return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(t==="capacitor")return(r,n)=>{var i,s;return n?(i=e.set)==null?void 0:i.call(e,{key:r,value:n}):(s=e.remove)==null?void 0:s.call(e,{key:r})};if(t==="expo-secure-storage")return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.deleteItemAsync)==null?void 0:s.call(e,r)};if(t==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var i,s;return n?(i=e.setItem)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var i,s;return n?(i=e.setItemAsync)==null?void 0:i.call(e,r,n):(s=e.removeItem)==null?void 0:s.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${t}`)},Je=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},de=({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},Ye=()=>typeof window!="undefined";let yn=globalThis.fetch;typeof EdgeRuntime!="string"&&(yn=Yt().fetch);const gn=async(t,e,{token:r,body:n}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const s={method:e,headers:i};n&&(s.body=JSON.stringify(n));try{const o=await yn(t,s);if(!o.ok){const u=await o.json();return Promise.reject({error:u})}try{return{data:await o.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${t}`),{data:"OK",error:null}}}catch{const o={message:"Network Error",status:Qt,error:"network"};return Promise.reject({error:o})}},te=async(t,e,r)=>gn(t,"POST",{token:r,body:e}),mn=(t,e)=>gn(t,"GET",{token:e}),At=(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 h=i.pathname;return o.pathname.length>1&&(h+=o.pathname.slice(1)),{...n,redirectTo:At(o.origin+h,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 nr(t){var e;if(typeof window=="undefined")return;const r=window==null?void 0:window.location;if(r&&r){const n=new URLSearchParams(r.search),i=new URLSearchParams((e=r.hash)==null?void 0:e.slice(1));n.delete(t),i.delete(t);let s=window.location.pathname;Array.from(n).length&&(s+=`?${n.toString()}`),Array.from(i).length&&(s+=`#${i.toString()}`),window.history.pushState({},"",s)}}const he=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,}))$/),kt=t=>!!t&&typeof t=="string"&&t.length>=Wr,ir=t=>!!t&&typeof t=="string",wn=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,clientStorageType:r="web",clientStorage:n,refreshIntervalTime:i,autoRefreshToken:s=!0,autoSignIn:o=!0})=>{const u=pn(r,n),c=vn(r,n),h=async(a,d,l)=>(await te(`${t}${a}`,d,l)).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:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:X("SIGNED_IN"),reportSignedOut:X("SIGNED_OUT"),reportTokenChanged:X("TOKEN_CHANGED"),incrementTokenImportAttempts:R({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:R(()=>(c(we,null),c(Ue,null),c(We,null),{...Tt})),clearContextExceptRefreshToken:R(({refreshToken:{value:a}})=>(c(we,null),{...Tt,refreshToken:{value:a}})),saveSession:R({user:(a,{data:d})=>{var l;return((l=d==null?void 0:d.session)==null?void 0:l.user)||null},accessToken:(a,{data:d})=>{if(d.session){const{accessTokenExpiresIn:l,accessToken:f}=d.session,v=new Date(Date.now()+l*1e3);return c(we,v.toISOString()),{value:f,expiresAt:v,expiresInSeconds:l}}return c(we,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:d})=>{var l,f;const v=((l=d.session)==null?void 0:l.refreshToken)||null,y=((f=d.session)==null?void 0:f.refreshTokenId)||null;return v&&c(Ue,v),y&&c(We,y),{value:v}}}),savePATSession:R({user:(a,{data:d})=>{var l;return((l=d==null?void 0:d.session)==null?void 0:l.user)||null},accessToken:(a,{data:d})=>{if(d.session){const{accessTokenExpiresIn:l,accessToken:f}=d.session,v=new Date(Date.now()+l*1e3);return c(we,v.toISOString()),{value:f,expiresAt:v,expiresInSeconds:l}}return c(we,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:d})=>{var l,f;const v=((l=d.session)==null?void 0:l.refreshToken)||null,y=((f=d.session)==null?void 0:f.refreshTokenId)||null;return v&&c(Ue,v),y&&c(We,y),{value:v,isPAT:!0}}}),saveMfaTicket:R({mfa:(a,d)=>{var l;return(l=d.data)==null?void 0:l.mfa}}),resetTimer:R({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:R({refreshTimer:(a,d)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:R({errors:({errors:a},{data:{error:d}})=>({...a,authentication:d})}),resetErrors:R({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:R({errors:({errors:a},{data:{error:d}})=>({...a,registration:d})}),destroyRefreshToken:R({refreshToken:a=>(c(Ue,null),c(We,null),{value:null})}),cleanUrl:()=>{o&&Xe("refreshToken")&&(nr("refreshToken"),nr("type"))},broadcastToken:a=>{if(o)try{new BroadcastChannel("nhost").postMessage({type:"broadcast_token",payload:{token:a.refreshToken.value}})}catch{}}},guards:{isAnonymous:(a,d)=>{var l;return!!((l=a.user)!=null&&l.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var d;return!!((d=a.refreshToken)!=null&&d.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!s,refreshTimerShouldRefresh:a=>{const{expiresAt:d}=a.accessToken;if(!d)return!1;if(d.getTime()<Date.now())return!0;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>Xt?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const l=a.accessToken.expiresInSeconds;return l?d.getTime()-Date.now()-1e3*Math.min(Jr,l*.5)<=0:!1},shouldRetryImportToken:(a,d)=>a.importTokenAttempts<Xt&&(d.data.error.status===Qt||d.data.error.status>=500),unverified:(a,{data:{error:d}})=>d.status===401&&(d.message==="Email is not verified"||d.error==="unverified-user"),hasSession:(a,d)=>{var l;return!!((l=d.data)!=null&&l.session)},hasMfaTicket:(a,d)=>{var l;return!!((l=d.data)!=null&&l.mfa)}},services:{signInPassword:(a,{email:d,password:l})=>he(d)?kt(l)?h("/signin/email-password",{email:d,password:l}):Promise.reject({error:Et}):Promise.reject({error:ue}),signInPAT:(a,{pat:d})=>h("/signin/pat",{personalAccessToken:d}),passwordlessSms:(a,{phoneNumber:d,options:l})=>{var f;return ir(d)?(f=a.user)!=null&&f.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),h("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:d,options:re(e,l)},a.accessToken.value)):h("/signin/passwordless/sms",{phoneNumber:d,options:re(e,l)}):Promise.reject({error:er})},passwordlessSmsOtp:(a,{phoneNumber:d,otp:l})=>ir(d)?h("/signin/passwordless/sms/otp",{phoneNumber:d,otp:l}):Promise.reject({error:er}),passwordlessEmail:(a,{email:d,options:l})=>{var f;return he(d)?(f=a.user)!=null&&f.isAnonymous?h("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:d,options:re(e,l)},a.accessToken.value):h("/signin/passwordless/email",{email:d,options:re(e,l)}):Promise.reject({error:ue})},signInAnonymous:a=>h("/signin/anonymous"),signInMfaTotp:(a,d)=>{var l;const f=d.ticket||((l=a.mfa)==null?void 0:l.ticket);return f?wn(f)?h("/signin/mfa/totp",{ticket:f,otp:d.otp}):Promise.reject({error:Qr}):Promise.reject({error:Zr})},signInSecurityKeyEmail:async(a,{email:d})=>{if(!he(d))throw new Ce(ue);const l=await h("/signin/webauthn",{email:d});let f;try{f=await fn(l)}catch(v){throw new Ce(v)}return h("/signin/webauthn/verify",{email:d,credential:f})},refreshToken:async(a,d)=>{const l=d.type==="TRY_TOKEN"?d.token:a.refreshToken.value;return{session:await h("/token",{refreshToken:l}),error:null}},signout:async(a,d)=>{const l=await h("/signout",{refreshToken:a.refreshToken.value,all:!!d.all});try{new BroadcastChannel("nhost").postMessage({type:"signout"})}catch{}return l},signUpEmailPassword:async(a,{email:d,password:l,options:f})=>{var v;return he(d)?kt(l)?(v=a.user)!=null&&v.isAnonymous?h("/user/deanonymize",{signInMethod:"email-password",email:d,password:l,options:re(e,f)},a.accessToken.value):h("/signup/email-password",{email:d,password:l,options:re(e,f)}):Promise.reject({error:Et}):Promise.reject({error:ue})},signUpSecurityKey:async(a,{email:d,options:l})=>{if(!he(d))return Promise.reject({error:ue});const f=l==null?void 0:l.nickname;f&&delete l.nickname;const v=await h("/signup/webauthn",{email:d,options:l});let y;try{y=await hn(v)}catch(S){throw new Ce(S)}return h("/signup/webauthn/verify",{credential:y,options:{redirectTo:l==null?void 0:l.redirectTo,nickname:f}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let d=null;if(o){const f=Xe("refreshToken")||null;if(f)try{return{session:await h("/token",{refreshToken:f}),error:null}}catch(v){d=v.error}else{const v=Xe("error"),y=Xe("errorDescription");if(v&&y!=="social user already exists")return Promise.reject({session:null,error:{status:ie,error:v,message:y||v}})}}const l=await u(Ue);if(l)try{return{session:await h("/token",{refreshToken:l}),error:null}}catch(f){d=f.error}return d?Promise.reject({error:d,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},Tn=({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:R({error:n=>ue}),saveRequestError:R({error:(n,{data:{error:i}})=>i}),reportError:X(n=>({type:"ERROR",error:n.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!he(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}}),Sn=({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:R({error:r=>Et}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!kt(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:R({error:r=>Yr}),saveInvalidMfaCodeError:R({error:r=>Xr}),saveError:R({error:(r,{data:{error:n}})=>n}),saveGeneration:R({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 mn(`${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)}}),bn=({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:R({error:r=>ue}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!he(n)},services:{requestChange:(r,{email:n,options:i})=>te(`${t}/user/password/reset`,{email:n,options:re(e,i)})}}),An=({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:R({error:r=>ue}),saveRequestError:R({error:(r,{data:{error:n}})=>n}),reportError:X(r=>({type:"ERROR",error:r.error})),reportSuccess:X("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!he(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 sr{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:i=!0,backendUrl:s,clientUrl:o,devTools:u,...c}){var h;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=s,this.clientUrl=o,this._machine=En({...c,backendUrl:s,clientUrl:o,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),i&&this.start({devTools:u}),typeof window!="undefined")try{this._channel=new BroadcastChannel("nhost"),r&&((h=this._channel)==null||h.addEventListener("message",a=>{var d;const{type:l,payload:f}=a.data;if(l==="broadcast_token"){const v=(d=this.interpreter)==null?void 0:d.getSnapshot().context.refreshToken.value;this.interpreter&&f.token.data!==v&&this.interpreter.send("TRY_TOKEN",{token:f.token.data})}})),this._channel.addEventListener("message",a=>{const{type:d}=a.data;d==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var i,s;const o={...this.machine.context};r&&(o.user=r.user,o.refreshToken.value=(i=r.refreshToken)!=null?i:null,o.accessToken.value=(s=r.accessToken)!=null?s:null,o.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const u=this.machine.withContext(o);this._interpreter||(this._interpreter=n||xe(u,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(u.initialState),this._subscriptionsQueue.forEach(c=>c(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class kn extends sr{constructor({...e}){super({...e,autoSignIn:Ye()&&e.autoSignIn,autoRefreshToken:Ye()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const gs=kn,On=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 Ce(o)}const{data:s}=await te(`${t}/user/webauthn/verify`,{credential:i,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:s,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},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,needsEmailVerification:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),In=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{password:e,ticket:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSuccess:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),ms=t=>new Promise(e=>{t.send("GENERATE"),t.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),ws=(t,e)=>new Promise(r=>{t.send("ACTIVATE",{activeMfaType:"totp",code:e}),t.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),xn=async(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),_n=(t,e,r)=>new Promise(n=>{t.send("REQUEST",{email:e,options:r}),t.onTransition(i=>{i.matches({idle:"error"})?n({error:i.context.error,isError:!0,isSent:!1}):i.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Pn=t=>new Promise(e=>{const{changed:r}=t.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:se,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})})}),Nn=(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:se,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:s.user});t.onTransition(o=>{o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:o.context.mfa,user:null}):o.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:o.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):o.matches({authentication:"signedIn"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:o.context.user})})}),or=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!i)return n({error:se,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})})}),Un=(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:se,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})})}),Dn=(t,e)=>new Promise(async r=>{var n,i;const s=(n=t.interpreter)==null?void 0:n.getSnapshot(),o=s==null?void 0:s.context.accessToken.value,{data:u}=await te(`${t.backendUrl}/elevate/webauthn`,{email:e},o);let c;try{c=await fn(u)}catch(h){throw new Ce(h)}try{const{data:{session:h},error:a}=await te(`${t.backendUrl}/elevate/webauthn/verify`,{email:e,credential:c},o);h&&!a&&((i=t.interpreter)==null||i.send({type:"SESSION_UPDATE",data:{session:h}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(h){const{error:a}=h;r({error:a,isError:!0,isSuccess:!1,elevated:!1})}}),Cn=(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:se,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})})}),Mn=(t,e)=>new Promise(r=>{const{changed:n}=t.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:se,user:null,accessToken:null,refreshToken:null}),t.onTransition(i=>{if(i.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1});if(i.matches({authentication:"signedIn"}))return r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,user:i.context.user,error:null,isError:!1,isSuccess:!0})})}),ar=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!i)return n({error:se,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})})}),Ln=(t,e,r)=>new Promise(n=>{const{changed:i}=t.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!i)return n({error:se,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});t.onTransition(s=>{s.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:s.context.user,accessToken:s.context.accessToken.value,refreshToken:s.context.refreshToken.value}):s.matches({registration:{incomplete:"failed"}})&&n({error:s.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),jn=async(t,e)=>new Promise(r=>{const{event:n}=t.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:rn});t.onTransition(i=>{i.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):i.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:i.context.errors.signout||null})})}),cr=(t,e,r,n)=>new Promise(i=>{const{changed:s,context:o}=t.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n});if(!s)return i({error:se,accessToken:o.accessToken.value,refreshToken:o.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:o.user});t.onTransition(u=>{u.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),$n=(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:se,accessToken:s.accessToken.value,refreshToken:s.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:s.user});t.onTransition(o=>{o.matches("registration.incomplete.failed")?n({accessToken:null,refreshToken:null,error:o.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):o.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):o.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:o.context.accessToken.value,refreshToken:o.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:o.context.user})})}),Es=async({backendUrl:t,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:i}=await te(`${t}/pat`,{expiresAt:r.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 Fn{constructor({url:e,autoRefreshToken:r=!0,autoSignIn:n=!0,clientStorage:i,clientStorageType:s,refreshIntervalTime:o,start:u=!0}){var c;this.url=e,this._client=new sr({backendUrl:e,clientUrl:typeof window!="undefined"&&((c=window.location)==null?void 0:c.origin)||"",autoRefreshToken:r,autoSignIn:n,start:u,clientStorage:i,clientStorageType:s,refreshIntervalTime:o})}async signUp(e){const r=await this.waitUntilReady(),{email:n,options:i}=e;return"securityKey"in e?de(await $n(r,n,i)):de(await cr(r,n,e.password,i))}async connectProvider(e){const r=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:n,options:i}=e,s=At(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,{...i,connect:r}));return Ye()&&(window.location.href=s),{providerUrl:s}}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Pn(r);return{...de(n),mfa:null}}if("provider"in e){const{provider:n,options:i}=e,s=At(`${this._client.backendUrl}/signin/provider/${n}`,re(this._client.clientUrl,i));return Ye()&&(window.location.href=s),{providerUrl:s,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Nn(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:nn}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{...de(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Un(r,e.email);return{...de(n),mfa:null}}if("email"in e){const{email:n,options:i}=e,{error:s}=await or(r,n,i);return{session:null,mfa:null,error:s}}if("phoneNumber"in e&&"otp"in e){const n=await Ln(r,e.phoneNumber,e.otp);return{...de(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await Cn(r,e.otp,e.ticket);return{...de(n),mfa:null}}return{error:on,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Mn(r,e);return de(n)}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await jn(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=xe(bn(this._client)).start(),{error:i}=await xn(n,e,r);return{error:i}}async changePassword({newPassword:e,ticket:r}){const n=xe(Sn(this._client)).start(),{error:i}=await In(n,e,r);return{error:i}}async sendVerificationEmail({email:e,options:r}){const n=xe(An(this._client)).start(),{error:i}=await _n(n,e,r);return{error:i}}async changeEmail({newEmail:e,options:r}){const n=xe(Tn(this._client)).start(),{error:i}=await Rn(n,e,r);return{error:i}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await or(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await ar(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await cr(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await On(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Dn(this._client,e),mfa:null}}async createPAT(e,r){return Es(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:i,context:s})=>{i.type==="TOKEN_CHANGED"&&e(Je(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,Je(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:Je(o.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return Je((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const e=this._client.interpreter;if(!e)throw Error("Auth interpreter not set");return e.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n("The state machine is not yet ready after 15 seconds."),15e3);e.onTransition(s=>{if(!s.hasTag("loading"))return clearTimeout(i),r(e)})}):Promise.resolve(e)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}var Ts=typeof self=="object"?self.FormData:window.FormData;const ur=Wt(Ts);let Hn=globalThis.fetch;const lr=async(t,e,{accessToken:r,name:n,fileId:i,bucketId:s,adminSecret:o,onUploadProgress:u,headers:c={}}={})=>{var h;const a={...c};s&&e.append("bucket-id",s),o&&(a["x-hasura-admin-secret"]=o),r&&(a.Authorization=`Bearer ${r}`);const d=`${t}/files`;if(typeof XMLHttpRequest=="undefined")try{e instanceof ur&&(Hn=Yt().fetch);const l=await Hn(d,{method:"POST",headers:a,body:e}),f=await l.json();return l.ok?{fileMetadata:f,error:null}:{error:{status:l.status,message:((h=f==null?void 0:f.error)==null?void 0:h.message)||l.statusText,error:l.statusText},fileMetadata:null}}catch(l){return{error:{status:0,message:l.message,error:l.message},fileMetadata:null}}return new Promise(l=>{let f=new XMLHttpRequest;f.responseType="json",f.onload=()=>{var v,y,S,E,T;return f.status<200||f.status>=300?l({fileMetadata:null,error:{error:(y=(v=f.response)==null?void 0:v.error)!=null?y:f.response,message:(T=(E=(S=f.response)==null?void 0:S.error)==null?void 0:E.message)!=null?T:f.response,status:f.status}}):l({fileMetadata:f.response,error:null})},f.onerror=()=>l({fileMetadata:null,error:{error:f.statusText,message:f.statusText,status:f.status}}),u&&f.upload.addEventListener("progress",u,!1),f.open("POST",d,!0),Object.entries(a).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=Yt().fetch);class qn{constructor({url:e}){this.headers={},this.url=e}async uploadFormData({formData:e,bucketId:r,headers:n}){const{error:i,fileMetadata:s}=await lr(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 ur:new FormData;o.append("file[]",e),o.append("metadata[]",JSON.stringify({id:n,name:i}));const{error:u,fileMetadata:c}=await lr(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 Gn{constructor({url:e,adminSecret:r}){this.url=e,this.api=new qn({url:e}),this.setAdminSecret(r)}async upload(e){return"file"in e?this.api.uploadFile(e):this.api.uploadFormData(e)}getPublicUrl(e){const{fileId:r,...n}=e;return 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.getHeaders()}setHeaders(e){return this.api.setHeaders(e),this}unsetHeaders(){return this.api.unsetHeaders(),this}}let dr;typeof dr=="undefined"&&(dr=ur);const Rt={progress:null,loaded:0,error:null,bucketId:void 0,file:void 0,id:void 0},Vn=()=>ve({predictableActionArguments:!0,schema:{context:{},events:{}},tsTypes:{},context:{...Rt},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:R({loaded:(t,{loaded:e})=>e,progress:(t,{progress:e})=>e}),setFileMetadata:R({id:(t,{id:e})=>e,bucketId:(t,{bucketId:e})=>e,progress:t=>100}),setError:R({error:(t,{error:e})=>e}),sendProgress:()=>{},sendError:()=>{},sendDestroy:()=>{},sendDone:()=>{},resetProgress:R({progress:t=>null,loaded:t=>0}),resetContext:R(t=>Rt),addFile:R({file:(t,{file:e})=>e,bucketId:(t,{bucketId:e})=>e,id:(t,{id:e})=>e})},services:{uploadFile:(t,e)=>r=>{const n=e.file||t.file,i=new dr;i.append("file[]",n);let s=0;return lr(e.url,i,{fileId:e.id||t.id,bucketId:e.bucketId||t.bucketId,accessToken:e.accessToken,adminSecret:e.adminSecret,name:e.name||n.name,onUploadProgress:o=>{const u=o.total?Math.round(o.loaded*n.size/o.total):0,c=u-s;s=u,r({type:"UPLOAD_PROGRESS",progress:o.total?Math.round(u*100/o.total):0,loaded:u,additions:c})}}).then(({fileMetadata:o,error:u})=>{if(u&&r({type:"UPLOAD_ERROR",error:u}),o&&!("processedFiles"in o)){const{id:c,bucketId:h}=o;r({type:"UPLOAD_DONE",id:c,bucketId:h})}if(o&&"processedFiles"in o){const{id:c,bucketId:h}=o.processedFiles[0];r({type:"UPLOAD_DONE",id:c,bucketId:h})}}),()=>{}}}}),{pure:hr,sendParent:It}=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:R((t,e)=>{const r=t.loaded+e.additions,n=Math.round(r*100/t.total);return{...t,loaded:r,progress:n}}),setUploaded:R({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:R({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:R({loaded:t=>0}),startProgress:R({progress:t=>0}),resetProgress:R({progress:t=>null}),addItem:R((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(Vn().withConfig({actions:{sendProgress:It((u,{additions:c})=>({type:"UPLOAD_PROGRESS",additions:c})),sendDone:It("UPLOAD_DONE"),sendError:It("UPLOAD_ERROR"),sendDestroy:It("REMOVE")}}).withContext({...Rt,file:o,bucketId:r}),{sync:!0}))],total:i,loaded:t.loaded,progress:s}}),removeItem:R({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:hr(t=>t.files.map(e=>X({type:"DESTROY"},{to:e.id}))),upload:hr((t,e)=>t.files.map(r=>X(e,{to:r.id}))),cancel:hr(t=>t.files.map(e=>X({type:"CANCEL"},{to:e.id})))}}),bs=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t}),e.subscribe(n=>{var i;n.matches("error")?r({error:n.context.error,isError:!0,isUploaded:!1}):n.matches("uploaded")&&r({error:null,isError:!1,isUploaded:!0,id:n.context.id,bucketId:n.context.id,name:(i=n.context.file)==null?void 0:i.name})})}),As=async(t,e)=>new Promise(r=>{e.send({type:"UPLOAD",...t,files:t.files}),e.onTransition(n=>{n.matches("error")?r({errors:n.context.files.filter(i=>{var s;return(s=i.getSnapshot())==null?void 0:s.context.error}),isError:!0,files:[]}):n.matches("uploaded")&&r({errors:[],isError:!1,files:n.context.files})})}),ks=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function Ze(t,e){const{subdomain:r,region:n}=t;if(!r)throw new Error("A `subdomain` must be set.");const i=r.match(ks);if(i!=null&&i.groups){const{protocol:s,host:o,port:u}=i.groups,c=Is(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 Rs(){return typeof process!="undefined"&&process.env}function Is(t){return Os()||!Rs()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function xs(t,e){const n=e.startsWith("/")?e:`/${e}`;return t+n}function Bn(t){const e="subdomain"in t?Ze(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new Fn({url:e,...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(a){return u[a.toLowerCase()]},has:function(a){return a.toLowerCase()in u}}}};for(var h in i.open(e.method||"get",t,!0),i.onload=function(){i.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(a,d,l){s.push(d=d.toLowerCase()),o.push([d,l]),u[d]=u[d]?u[d]+","+l:l}),r(c())},i.onerror=n,i.withCredentials=e.credentials=="include",e.headers)i.setRequestHeader(h,e.headers[h]);i.send(e.body||null)})}const Kn=is(Object.freeze(Object.defineProperty({__proto__:null,default:_s},Symbol.toStringTag,{value:"Module"})));var Ps=self.fetch||(self.fetch=Kn.default||Kn);const zn=Wt(Ps);function Wn(t){const e="subdomain"in t?Ze(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new Jn({url:e,...t})}class Jn{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 zn(s,{body:r?JSON.stringify(r):null,headers:i,method:"POST"});if(!c.ok){let a;return(o=c.headers.get("content-type"))!=null&&o.includes("application/json")?a=await c.json():a=await c.text(),{res:null,error:{message:a,error:c.statusText,status:c.status}}}let h;return(u=c.headers.get("content-type"))!=null&&u.includes("application/json")?h=await c.json():h=await c.text(),{res:{data:h,status:c.status,statusText:c.statusText},error:null}}catch(c){const h=c;return{res:null,error:{message:h.message,status:h.name==="AbortError"?0:500,error:h.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 Yn(t){var e;let r;const n=t.definitions.filter(i=>i.kind==="OperationDefinition");return n.length===1&&(r=(e=n[0].name)==null?void 0:e.value),r}function Us(t){if(typeof t=="string"){let r;try{const n=Se.parse(t);r=Yn(n)}catch{}return{query:t,operationName:r}}const e=Yn(t);return{query:Se.print(t),operationName:e}}class 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:h}=Us(s.document);typeof process!="undefined"&&!process.env.TEST_MODE&&await this.awaitForValidAccessTokenOrNull();try{const a=await zn(this.httpUrl,{method:"POST",body:JSON.stringify({operationName:h,query:c,variables:n}),headers:{"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...this.headers,...o},...u});if(!a.ok)return{data:null,error:{error:a.statusText,message:a.statusText,status:a.status}};const{data:d,errors:l}=await a.json();return l?{data:null,error:l}:typeof d!="object"||Array.isArray(d)||d===null?{data:null,error:{error:"invalid-response",message:"incorrect response data from GraphQL server",status:0}}:{data:d,error:null}}catch(a){const d=a;return{data:null,error:{message:d.message,status:d.name==="AbortError"?0:500,error:d.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 Xn(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 Qn(t){const e="subdomain"in t?Ze(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new Gn({url:e,...t})}const Cs=t=>new Zn(t);class Zn{constructor({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,adminSecret:o,devTools:u,start:c=!0,...h}){this.auth=Bn({refreshIntervalTime:e,clientStorage:r,clientStorageType:n,autoRefreshToken:i,autoSignIn:s,start:c,...h}),this.storage=Qn({adminSecret:o,...h}),this.functions=Wn({adminSecret:o,...h}),this.graphql=Xn({adminSecret:o,...h}),this.auth.onAuthStateChanged((a,d)=>{if(a==="SIGNED_OUT"){this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0);return}const l=d==null?void 0:d.accessToken;this.storage.setAccessToken(l),this.functions.setAccessToken(l),this.graphql.setAccessToken(l)}),this.auth.onTokenChanged(a=>{const d=a==null?void 0:a.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),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=sr,g.AuthClientSSR=gs,g.AuthCookieClient=kn,g.CodifiedError=Ce,g.EMAIL_NEEDS_VERIFICATION=nn,g.HasuraAuthClient=Fn,g.HasuraStorageApi=qn,g.HasuraStorageClient=Gn,g.INITIAL_FILE_CONTEXT=Rt,g.INITIAL_MACHINE_CONTEXT=Tt,g.INVALID_EMAIL_ERROR=ue,g.INVALID_MFA_CODE_ERROR=Xr,g.INVALID_MFA_TICKET_ERROR=Qr,g.INVALID_MFA_TYPE_ERROR=Yr,g.INVALID_PASSWORD_ERROR=Et,g.INVALID_PHONE_NUMBER_ERROR=er,g.INVALID_REFRESH_TOKEN=sn,g.INVALID_SIGN_IN_METHOD=on,g.MIN_PASSWORD_LENGTH=Wr,g.NETWORK_ERROR_CODE=Qt,g.NHOST_JWT_EXPIRES_AT_KEY=we,g.NHOST_REFRESH_TOKEN_ID_KEY=We,g.NHOST_REFRESH_TOKEN_KEY=Ue,g.NO_MFA_TICKET_ERROR=Zr,g.NO_REFRESH_TOKEN=en,g.NhostClient=Zn,g.NhostFunctionsClient=Jn,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=Jr,g.USER_ALREADY_SIGNED_IN=se,g.USER_NOT_ANONYMOUS=os,g.USER_UNAUTHENTICATED=rn,g.VALIDATION_ERROR_CODE=ie,g.activateMfaPromise=ws,g.addSecurityKeyPromise=On,g.appendImageTransformationParameters=Ot,g.changeEmailPromise=Rn,g.changePasswordPromise=In,g.createAuthClient=Bn,g.createAuthMachine=En,g.createChangeEmailMachine=Tn,g.createChangePasswordMachine=Sn,g.createEnableMfaMachine=ys,g.createFileUploadMachine=Vn,g.createFunctionsClient=Wn,g.createGraphqlClient=Xn,g.createMultipleFilesUploadMachine=Ss,g.createNhostClient=Cs,g.createResetPasswordMachine=bn,g.createSendVerificationEmailMachine=An,g.createStorageClient=Qn,g.elevateEmailSecurityKeyPromise=Dn,g.encodeQueryParameters=At,g.generateQrCodePromise=ms,g.getAuthenticationResult=de,g.getFetch=mn,g.getParameterByName=Xe,g.getSession=Je,g.isBrowser=Ye,g.isValidEmail=he,g.isValidPassword=kt,g.isValidPhoneNumber=ir,g.isValidTicket=wn,g.localStorageGetter=pn,g.localStorageSetter=vn,g.postFetch=te,g.removeParameterFromWindow=nr,g.resetPasswordPromise=xn,g.rewriteRedirectTo=re,g.sendVerificationEmailPromise=_n,g.signInAnonymousPromise=Pn,g.signInEmailPasswordPromise=Nn,g.signInEmailPasswordlessPromise=or,g.signInEmailSecurityKeyPromise=Un,g.signInMfaTotpPromise=Cn,g.signInPATPromise=Mn,g.signInSmsPasswordlessOtpPromise=Ln,g.signInSmsPasswordlessPromise=ar,g.signOutPromise=jn,g.signUpEmailPasswordPromise=cr,g.signUpEmailSecurityKeyPromise=$n,g.uploadFilePromise=bs,g.uploadMultipleFilesPromise=As,g.urlFromSubdomain=Ze,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
|
|
22
22
|
//# sourceMappingURL=nhost-js.umd.js.map
|