@nhost/hasura-auth-js
Advanced tools
Comparing version 1.12.4 to 2.0.0
@@ -9,3 +9,3 @@ import { AuthClient } from './internal-client'; | ||
readonly url: string; | ||
constructor({ url, autoRefreshToken, autoSignIn, autoLogin, clientStorage, clientStorageType, clientStorageGetter, clientStorageSetter, refreshIntervalTime, start }: NhostAuthConstructorParams); | ||
constructor({ url, autoRefreshToken, autoSignIn, clientStorage, clientStorageType, refreshIntervalTime, start }: NhostAuthConstructorParams); | ||
/** | ||
@@ -273,8 +273,2 @@ * Use `nhost.auth.signUp` to sign up a user using email and password. If you want to sign up a user using passwordless email (Magic Link), SMS, or an OAuth provider, use the `signIn` function instead. | ||
/** | ||
* @internal | ||
* @deprecated Use `nhost.auth.getAccessToken()` instead. | ||
* @docs https://docs.nhost.io/reference/javascript/auth/get-access-token | ||
*/ | ||
getJWTToken(): string | undefined; | ||
/** | ||
* Use `nhost.auth.getAccessToken` to get the access token of the user. | ||
@@ -281,0 +275,0 @@ * |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Le=require("jwt-decode"),l=require("xstate"),q=require("js-cookie"),Ge=require("axios"),P="nhostRefreshToken",N="nhostRefreshTokenExpiresAt",re=3,te=300,H=5,z=0,Q=1,_=10,O=20;class D extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Q,message:e.message}):(this.name=e.error,this.error=e)}}const R={status:_,error:"invalid-email",message:"Email is incorrectly formatted"},se={status:_,error:"invalid-mfa-type",message:"MFA type is invalid"},ne={status:_,error:"invalid-mfa-code",message:"MFA code is invalid"},x={status:_,error:"invalid-password",message:"Password is incorrectly formatted"},W={status:_,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},ie={status:_,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},oe={status:_,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},ae={status:_,error:"no-refresh-token",message:"No refresh token has been provided"},ce={status:O,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},y={status:O,error:"already-signed-in",message:"User is already signed in"},ue={status:O,error:"unauthenticated-user",message:"User is not authenticated"},qe={status:O,error:"user-not-anonymous",message:"User is not anonymous"},le={status:O,error:"unverified-user",message:"Email needs verification"},de={status:_,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},he={status:Q,error:"invalid-sign-in-method",message:"Invalid sign-in method"},M={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function He(s){return new TextEncoder().encode(s)}function k(s){const e=new Uint8Array(s);let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function X(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,r=e.padEnd(e.length+t,"="),n=atob(r),i=new ArrayBuffer(n.length),c=new Uint8Array(i);for(let d=0;d<n.length;d++)c[d]=n.charCodeAt(d);return i}function fe(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function me(s){const{id:e}=s;return{...s,id:X(e),transports:s.transports}}function Ee(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}class T extends Error{constructor(e,t="WebAuthnError"){super(e),this.name=t}}function We({error:s,options:e}){var t,r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal===new AbortController().signal)return new T("Registration ceremony was sent an abort signal","AbortError")}else if(s.name==="ConstraintError"){if(((t=n.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new T("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((r=n.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new T("User verification was required but no available authenticator supported it","ConstraintError")}else{if(s.name==="InvalidStateError")return new T("The authenticator was previously registered","InvalidStateError");if(s.name==="NotAllowedError")return new T("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(s.name==="NotSupportedError")return n.pubKeyCredParams.filter(c=>c.type==="public-key").length===0?new T('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new T("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(s.name==="SecurityError"){const i=window.location.hostname;if(Ee(i)){if(n.rp.id!==i)return new T(`The RP ID "${n.rp.id}" is invalid for this domain`,"SecurityError")}else return new T(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(s.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new T("User ID was not between 1 and 64 characters","TypeError")}else if(s.name==="UnknownError")return new T("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return s}class $e{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const K=new $e;async function ge(s){if(!fe())throw new Error("WebAuthn is not supported in this browser");const t={publicKey:{...s,challenge:X(s.challenge),user:{...s.user,id:He(s.user.id)},excludeCredentials:s.excludeCredentials.map(me)}};t.signal=K.createNewAbortSignal();let r;try{r=await navigator.credentials.create(t)}catch(g){throw We({error:g,options:t})}finally{K.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:c,type:d}=r,m={id:n,rawId:k(i),response:{attestationObject:k(c.attestationObject),clientDataJSON:k(c.clientDataJSON)},type:d,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof c.getTransports=="function"&&(m.transports=c.getTransports()),m}function Fe(s){return new TextDecoder("utf-8").decode(s)}async function Ye(){if(navigator.credentials.conditionalMediationSupported)return!0;const s=window.PublicKeyCredential;return s.isConditionalMediationAvailable!==void 0&&s.isConditionalMediationAvailable()}function je({error:s,options:e}){var t;const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal===new AbortController().signal)return new T("Authentication ceremony was sent an abort signal","AbortError")}else{if(s.name==="NotAllowedError")return!((t=r.allowCredentials)===null||t===void 0)&&t.length?new T("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new T("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(s.name==="SecurityError"){const n=window.location.hostname;if(Ee(n)){if(r.rpId!==n)return new T(`The RP ID "${r.rpId}" is invalid for this domain`,"SecurityError")}else return new T(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(s.name==="UnknownError")return new T("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return s}async function Be(s,e=!1){var t,r;if(!fe())throw new Error("WebAuthn is not supported in this browser");let n;((t=s.allowCredentials)===null||t===void 0?void 0:t.length)!==0&&(n=(r=s.allowCredentials)===null||r===void 0?void 0:r.map(me));const i={...s,challenge:X(s.challenge),allowCredentials:n},c={};if(e){if(!await Ye())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');c.mediation="conditional",i.allowCredentials=[]}c.publicKey=i,c.signal=K.createNewAbortSignal();let d;try{d=await navigator.credentials.get(c)}catch(o){throw je({error:o,options:c})}finally{K.reset()}if(!d)throw new Error("Authentication was not completed");const{id:m,rawId:g,response:p,type:S}=d;let f;return p.userHandle&&(f=Fe(p.userHandle)),{id:m,rawId:k(g),response:{authenticatorData:k(p.authenticatorData),clientDataJSON:k(p.clientDataJSON),signature:k(p.signature),userHandle:f},type:S,clientExtensionResults:d.getClientExtensionResults(),authenticatorAttachment:d.authenticatorAttachment}}const G=typeof window<"u",U=new Map,ze=s=>G&&typeof localStorage<"u"?localStorage.getItem(s):U.get(s)??null,Qe=(s,e)=>{G&&typeof localStorage<"u"?e?localStorage.setItem(s,e):localStorage.removeItem(s):e?U.set(s,e):U.has(s)&&U.delete(s)},pe=(s,e)=>{if(s==="localStorage"||s==="web")return ze;if(s==="cookie")return t=>G?q.get(t)??null:null;if(!e)throw Error(`clientStorageType is set to '${s}' but no clientStorage has been given`);if(s==="react-native")return t=>{var r;return(r=e.getItem)==null?void 0:r.call(e,t)};if(s==="capacitor")return t=>{var r;return(r=e.get)==null?void 0:r.call(e,{key:t})};if(s==="expo-secure-storage")return t=>{var r;return(r=e.getItemAsync)==null?void 0:r.call(e,t)};if(s==="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: ${s}`)},Te=(s,e)=>{if(s==="localStorage"||s==="web")return Qe;if(s==="cookie")return(t,r)=>{G&&(r?q.set(t,r,{expires:30,sameSite:"lax",httpOnly:!1}):q.remove(t))};if(!e)throw Error(`clientStorageType is set to '${s}' but no clienStorage has been given`);if(s==="react-native")return(t,r)=>{var n,i;return r?(n=e.setItem)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};if(s==="capacitor")return(t,r)=>{var n,i;return r?(n=e.set)==null?void 0:n.call(e,{key:t,value:r}):(i=e.remove)==null?void 0:i.call(e,{key:t})};if(s==="expo-secure-storage")return async(t,r)=>{var n,i;return r?(n=e.setItemAsync)==null?void 0:n.call(e,t,r):(i=e.deleteItemAsync)==null?void 0:i.call(e,t)};if(s==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(t,r)=>{var n,i;return r?(n=e.setItem)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};if(e.setItemAsync)return async(t,r)=>{var n,i;return r?(n=e.setItemAsync)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${s}`)},v=s=>{const e=Ge.create({baseURL:s});return e.interceptors.response.use(t=>t,t=>{var r,n,i,c,d,m,g;return Promise.reject({error:{message:((n=(r=t.response)==null?void 0:r.data)==null?void 0:n.message)??t.message??t.request.responseText??JSON.stringify(t),status:((i=t.response)==null?void 0:i.status)??((d=(c=t.response)==null?void 0:c.data)==null?void 0:d.statusCode)??z,error:((g=(m=t.response)==null?void 0:m.data)==null?void 0:g.error)||t.request.statusText||"network"}})}),e},b=s=>!s||!s.accessToken.value||!s.refreshToken.value||!s.accessToken.expiresAt||!s.user?null:{accessToken:s.accessToken.value,accessTokenExpiresIn:(s.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:s.refreshToken.value,user:s.user},A=({accessToken:s,isError:e,user:t,error:r})=>e?{session:null,error:r}:t&&s?{session:{accessToken:s,accessTokenExpiresIn:0,refreshToken:"",user:t},error:null}:{session:null,error:null},V=()=>typeof window<"u",J=(s,e)=>{const t=e&&Object.entries(e).map(([r,n])=>{const i=Array.isArray(n)?n.join(","):typeof n=="object"?JSON.stringify(n):n;return`${r}=${encodeURIComponent(i)}`}).join("&");return t?`${s}?${t}`:s},w=(s,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:t,...r}=e;if(!s)return t.startsWith("/")?r:e;const n=new URL(s),i=Object.fromEntries(new URLSearchParams(n.search)),c=new URL(t.startsWith("/")?n.origin+t:t),d=new URLSearchParams(c.search);let m=Object.fromEntries(d);t.startsWith("/")&&(m={...i,...m});let g=n.pathname;return c.pathname.length>1&&(g+=c.pathname.slice(1)),{...r,redirectTo:J(c.origin+g,m)}};function C(s,e){var n;if(!e){if(typeof window>"u")return;e=((n=window.location)==null?void 0:n.href)||""}s=s.replace(/[\[\]]/g,"\\$&");const t=new RegExp("[?&#]"+s+"(=([^&#]*)|&|#|$)"),r=t.exec(e);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}function $(s){var t;if(typeof window>"u")return;const e=window==null?void 0:window.location;if(e&&e){const r=new URLSearchParams(e.search),n=new URLSearchParams((t=e.hash)==null?void 0:t.slice(1));r.delete(s),n.delete(s);let i=window.location.pathname;Array.from(r).length&&(i+=`?${r.toString()}`),Array.from(n).length&&(i+=`#${n.toString()}`),window.history.pushState({},"",i)}}const I=s=>!!s&&typeof s=="string"&&!!String(s).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,}))$/),L=s=>!!s&&typeof s=="string"&&s.length>=re,F=s=>!!s&&typeof s=="string",we=s=>s&&typeof s=="string"&&s.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),_e=({backendUrl:s,clientUrl:e,clientStorageGetter:t,clientStorageSetter:r,clientStorageType:n="web",clientStorage:i,refreshIntervalTime:c,autoRefreshToken:d=!0,autoSignIn:m=!0})=>{const g=t||pe(n,i),p=r||Te(n,i),S=v(s),f=async(o,a,u)=>(await S.post(o,a,u)).data;return l.createMachine({schema:{context:{},events:{},services:{}},tsTypes:{},context:M,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:l.send("SIGNED_IN"),reportSignedOut:l.send("SIGNED_OUT"),reportTokenChanged:l.send("TOKEN_CHANGED"),incrementTokenImportAttempts:l.assign({importTokenAttempts:({importTokenAttempts:o})=>o+1}),clearContext:l.assign(()=>(p(N,null),p(P,null),{...M})),clearContextExceptRefreshToken:l.assign(({refreshToken:{value:o}})=>(p(N,null),{...M,refreshToken:{value:o}})),saveSession:l.assign({user:(o,{data:a})=>{var u;return((u=a==null?void 0:a.session)==null?void 0:u.user)||null},accessToken:(o,{data:a})=>{if(a.session){const{accessTokenExpiresIn:u,accessToken:h}=a.session,E=new Date(Date.now()+u*1e3);return p(N,E.toISOString()),{value:h,expiresAt:E}}return p(N,null),{value:null,expiresAt:null}},refreshToken:(o,{data:a})=>{var h;const u=((h=a.session)==null?void 0:h.refreshToken)||null;return u&&p(P,u),{value:u}}}),saveMfaTicket:l.assign({mfa:(o,a)=>{var u;return(u=a.data)==null?void 0:u.mfa}}),resetTimer:l.assign({refreshTimer:o=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:l.assign({refreshTimer:(o,a)=>({startedAt:o.refreshTimer.startedAt,attempts:o.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:l.assign({errors:({errors:o},{data:{error:a}})=>({...o,authentication:a})}),resetErrors:l.assign({errors:o=>({}),importTokenAttempts:o=>0}),saveRegistrationError:l.assign({errors:({errors:o},{data:{error:a}})=>({...o,registration:a})}),destroyRefreshToken:l.assign({refreshToken:o=>(p(P,null),{value:null})}),cleanUrl:()=>{m&&C("refreshToken")&&($("refreshToken"),$("type"))},broadcastToken:o=>{if(m)try{new BroadcastChannel("nhost").postMessage(o.refreshToken.value)}catch{}}},guards:{isAnonymous:(o,a)=>{var u;return!!((u=o.user)!=null&&u.isAnonymous)},isSignedIn:o=>!!o.user&&!!o.refreshToken.value&&!!o.accessToken.value,noToken:o=>!o.refreshToken.value,hasRefreshToken:o=>!!o.refreshToken.value,isAutoRefreshDisabled:()=>!d,refreshTimerShouldRefresh:o=>{const{expiresAt:a}=o.accessToken;return a?o.refreshTimer.lastAttempt?o.refreshTimer.attempts>H?!1:Date.now()-o.refreshTimer.lastAttempt.getTime()>Math.pow(2,o.refreshTimer.attempts-1)*5e3:c&&Date.now()-o.refreshTimer.startedAt.getTime()>c*1e3?!0:a.getTime()-Date.now()-1e3*te<=0:!1},shouldRetryImportToken:(o,a)=>o.importTokenAttempts<H&&(a.data.error.status===z||a.data.error.status>=500),unverified:(o,{data:{error:a}})=>a.status===401&&(a.message==="Email is not verified"||a.error==="unverified-user"),hasSession:(o,a)=>{var u;return!!((u=a.data)!=null&&u.session)},hasMfaTicket:(o,a)=>{var u;return!!((u=a.data)!=null&&u.mfa)}},services:{signInPassword:(o,{email:a,password:u})=>I(a)?L(u)?f("/signin/email-password",{email:a,password:u}):Promise.reject({error:x}):Promise.reject({error:R}),passwordlessSms:(o,{phoneNumber:a,options:u})=>{var h;return F(a)?(h=o.user)!=null&&h.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:a,options:w(e,u)},{headers:{authorization:`Bearer ${o.accessToken.value}`}})):f("/signin/passwordless/sms",{phoneNumber:a,options:w(e,u)}):Promise.reject({error:W})},passwordlessSmsOtp:(o,{phoneNumber:a,otp:u})=>F(a)?f("/signin/passwordless/sms/otp",{phoneNumber:a,otp:u}):Promise.reject({error:W}),passwordlessEmail:(o,{email:a,options:u})=>{var h;return I(a)?(h=o.user)!=null&&h.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:a,options:w(e,u)},{headers:{authorization:`Bearer ${o.accessToken.value}`}}):f("/signin/passwordless/email",{email:a,options:w(e,u)}):Promise.reject({error:R})},signInAnonymous:o=>f("/signin/anonymous"),signInMfaTotp:(o,a)=>{var h;const u=a.ticket||((h=o.mfa)==null?void 0:h.ticket);return u?we(u)?f("/signin/mfa/totp",{ticket:u,otp:a.otp}):Promise.reject({error:ie}):Promise.reject({error:oe})},signInSecurityKeyEmail:async(o,{email:a})=>{if(!I(a))throw new D(R);const u=await f("/signin/webauthn",{email:a});let h;try{h=await Be(u)}catch(E){throw new D(E)}return f("/signin/webauthn/verify",{email:a,credential:h})},refreshToken:async(o,a)=>{const u=a.type==="TRY_TOKEN"?a.token:o.refreshToken.value;return{session:await f("/token",{refreshToken:u}),error:null}},signout:(o,a)=>f("/signout",{refreshToken:o.refreshToken.value,all:!!a.all}),signUpEmailPassword:async(o,{email:a,password:u,options:h})=>{var E;return I(a)?L(u)?(E=o.user)!=null&&E.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:a,password:u,options:w(e,h)},{headers:{authorization:`Bearer ${o.accessToken.value}`}}):f("/signup/email-password",{email:a,password:u,options:w(e,h)}):Promise.reject({error:x}):Promise.reject({error:R})},signUpSecurityKey:async(o,{email:a,options:u})=>{if(!I(a))return Promise.reject({error:R});const h=u==null?void 0:u.nickname;h&&delete u.nickname;const E=await f("/signup/webauthn",{email:a,options:u});let ee;try{ee=await ge(E)}catch(Ve){throw new D(Ve)}return f("/signup/webauthn/verify",{credential:ee,options:{redirectTo:u==null?void 0:u.redirectTo,nickname:h}})},importRefreshToken:async o=>{if(o.user&&o.refreshToken.value&&o.accessToken.value&&o.accessToken.expiresAt)return{session:{accessToken:o.accessToken.value,accessTokenExpiresIn:o.accessToken.expiresAt.getTime()-Date.now(),refreshToken:o.refreshToken.value,user:o.user},error:null};let a=null;if(m){const h=C("refreshToken")||null;if(h)try{return{session:await f("/token",{refreshToken:h}),error:null}}catch(E){a=E.error}else{const E=C("error");if(E)return Promise.reject({session:null,error:{status:_,error:E,message:C("errorDescription")||E}})}}const u=await g(P);if(u)try{return{session:await f("/token",{refreshToken:u}),error:null}}catch(h){a=h.error}return a?Promise.reject({error:a,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:o})=>Math.pow(2,o-1)*5e3}})},ye=({backendUrl:s,clientUrl:e,interpreter:t})=>{const r=v(s);return l.createMachine({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:l.assign({error:n=>R}),saveRequestError:l.assign({error:(n,{data:{error:i}})=>i}),reportError:l.send(n=>({type:"ERROR",error:n.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(n,{email:i})=>!I(i)},services:{requestChange:async(n,{email:i,options:c})=>(await r.post("/user/email/change",{newEmail:i,options:w(e,c)},{headers:{authorization:`Bearer ${t==null?void 0:t.getSnapshot().context.accessToken.value}`}})).data}})},Se=({backendUrl:s,interpreter:e})=>{const t=v(s);return l.createMachine({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:l.assign({error:r=>x}),saveRequestError:l.assign({error:(r,{data:{error:n}})=>n}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!L(n)},services:{requestChange:(r,{password:n,ticket:i})=>t.post("/user/password",{newPassword:n,ticket:i},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}})}})},Xe=({backendUrl:s,interpreter:e})=>{const t=v(s);return l.createMachine({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:l.assign({error:r=>se}),saveInvalidMfaCodeError:l.assign({error:r=>ne}),saveError:l.assign({error:(r,{data:{error:n}})=>n}),saveGeneration:l.assign({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS"),reportGeneratedSuccess:l.send("GENERATED"),reportGeneratedError:l.send(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 t.get("/mfa/totp/generate",{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});return n},activate:(r,{code:n,activeMfaType:i})=>t.post("/user/mfa",{code:n,activeMfaType:i},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}})}})},Re=({backendUrl:s,clientUrl:e})=>{const t=v(s);return l.createMachine({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:l.assign({error:r=>R}),saveRequestError:l.assign({error:(r,{data:{error:n}})=>n}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!I(n)},services:{requestChange:(r,{email:n,options:i})=>t.post("/user/password/reset",{email:n,options:w(e,i)})}})},Ie=({backendUrl:s,clientUrl:e})=>{const t=v(s);return l.createMachine({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:l.assign({error:r=>R}),saveRequestError:l.assign({error:(r,{data:{error:n}})=>n}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!I(n)},services:{request:async(r,{email:n,options:i})=>(await t.post("/user/email/send-verification-email",{email:n,options:w(e,i)})).data}})};class Z{constructor({clientStorageType:e="web",autoSignIn:t=!0,autoRefreshToken:r=!0,start:n=!0,backendUrl:i,clientUrl:c,devTools:d,...m}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=i,this.clientUrl=c,this._machine=_e({...m,backendUrl:i,clientUrl:c,clientStorageType:e,autoSignIn:t,autoRefreshToken:r}),n&&this.start({devTools:d}),typeof window<"u"&&t)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",g=>{var S;const p=(S=this.interpreter)==null?void 0:S.getSnapshot().context.refreshToken.value;this.interpreter&&g.data!==p&&this.interpreter.send("TRY_TOKEN",{token:g.data})})}catch{}}start({devTools:e=!1,initialSession:t,interpreter:r}={}){const n={...this.machine.context};t&&(n.user=t.user,n.refreshToken.value=t.refreshToken??null,n.accessToken.value=t.accessToken??null,n.accessToken.expiresAt=new Date(Date.now()+t.accessTokenExpiresIn*1e3));const i=this.machine.withContext(n);this._interpreter||(this._interpreter=r||l.interpret(i,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(i.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 t=e(this);return this._subscriptions.add(t),t}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class Ae extends Z{constructor({...e}){super({...e,autoSignIn:V()&&e.autoSignIn,autoRefreshToken:V()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Je=Ae,ve=async({backendUrl:s,interpreter:e},t)=>{const r=v(s);try{const{data:n}=await r.post("/user/webauthn/add",{},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});let i;try{i=await ge(n)}catch(d){throw new D(d)}const{data:c}=await r.post("/user/webauthn/verify",{credential:i,nickname:t},{headers:{authorization:`Bearer ${e==null?void 0:e.getSnapshot().context.accessToken.value}`}});return{key:c,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:i}=n;return{isError:!0,error:i,isSuccess:!1}}},ke=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,needsEmailVerification:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,needsEmailVerification:!0})})}),Oe=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{password:e,ticket:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSuccess:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSuccess:!0})})}),Ze=s=>new Promise(e=>{s.send("GENERATE"),s.onTransition(t=>{t.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:t.context.imageUrl||""}):t.matches({idle:"error"})&&e({error:t.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),er=(s,e)=>new Promise(t=>{s.send("ACTIVATE",{activeMfaType:"totp",code:e}),s.onTransition(r=>{r.matches({generated:"activated"})?t({error:null,isActivated:!0,isError:!1}):r.matches({generated:{idle:"error"}})&&t({error:r.context.error,isActivated:!1,isError:!0})})}),Pe=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSent:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),Ne=(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSent:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),be=s=>new Promise(e=>{const{changed:t}=s.send("SIGNIN_ANONYMOUS");t||e({isSuccess:!1,isError:!0,error:y,user:null,accessToken:null}),s.onTransition(r=>{r.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:r.context.user,accessToken:r.context.accessToken.value}),r.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:r.context.errors.authentication||null,user:null,accessToken:null})})}),Ce=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNIN_PASSWORD",{email:e,password:t});if(!n)return r({accessToken:i.accessToken.value,error:y,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:i.user});s.onTransition(c=>{c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):c.matches({authentication:{signedOut:"needsMfa"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:c.context.mfa,user:null}):c.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:c.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):c.matches({authentication:"signedIn"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:c.context.user})})}),Y=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send("PASSWORDLESS_EMAIL",{email:e,options:t});if(!n)return r({error:y,isError:!0,isSuccess:!1});s.onTransition(i=>{i.matches("registration.incomplete.failed")?r({error:i.context.errors.registration||null,isError:!0,isSuccess:!1}):i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&r({error:null,isError:!1,isSuccess:!0})})}),De=(s,e)=>new Promise(t=>{const{changed:r,context:n}=s.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!r)return t({accessToken:n.accessToken.value,error:y,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:n.user});s.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?t({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?t({accessToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&t({accessToken:i.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),Me=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNIN_MFA_TOTP",{otp:e,ticket:t});if(!n)return r({accessToken:i.accessToken.value,error:y,isError:!0,isSuccess:!1,user:i.user});s.onTransition(c=>{c.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:c.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):c.matches({authentication:"signedIn"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:c.context.user})})}),j=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send("PASSWORDLESS_SMS",{phoneNumber:e,options:t});if(!n)return r({error:y,isError:!0,isSuccess:!1,needsOtp:!1});s.onTransition(i=>{i.matches("registration.incomplete.needsOtp")?r({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):i.matches("registration.incomplete.failed")&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Ue=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:t});if(!n)return r({error:y,isError:!0,isSuccess:!1,user:null,accessToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?r({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value}):i.matches({registration:{incomplete:"failed"}})&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),xe=async(s,e)=>new Promise(t=>{const{event:r}=s.send("SIGNOUT",{all:e});if(r.type!=="SIGNED_OUT")return t({isSuccess:!1,isError:!0,error:ue});s.onTransition(n=>{n.matches({authentication:{signedOut:"success"}})?t({isSuccess:!0,isError:!1,error:null}):n.matches("authentication.signedOut.failed")&&t({isSuccess:!1,isError:!0,error:n.context.errors.signout||null})})}),B=(s,e,t,r)=>new Promise(n=>{const{changed:i,context:c}=s.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:t,options:r});if(!i)return n({error:y,accessToken:c.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:c.user});s.onTransition(d=>{d.matches("registration.incomplete.failed")?n({accessToken:null,error:d.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):d.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):d.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:d.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:d.context.user})})}),Ke=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNUP_SECURITY_KEY",{email:e,options:t});if(!n)return r({error:y,accessToken:i.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});s.onTransition(c=>{c.matches("registration.incomplete.failed")?r({accessToken:null,error:c.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):c.matches({authentication:"signedIn",registration:"complete"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:c.context.user})})});class rr{constructor({url:e,autoRefreshToken:t=!0,autoSignIn:r=!0,autoLogin:n,clientStorage:i,clientStorageType:c,clientStorageGetter:d,clientStorageSetter:m,refreshIntervalTime:g,start:p=!0}){var S;this.url=e,this._client=new Z({backendUrl:e,clientUrl:typeof window<"u"&&((S=window.location)==null?void 0:S.origin)||"",autoRefreshToken:t,autoSignIn:typeof n=="boolean"?n:r,start:p,clientStorage:i,clientStorageType:c,clientStorageGetter:d,clientStorageSetter:m,refreshIntervalTime:g})}async signUp(e){const t=await this.waitUntilReady(),{email:r,options:n}=e;return"securityKey"in e?A(await Ke(t,r,n)):A(await B(t,r,e.password,n))}async signIn(e){const t=await this.waitUntilReady();if(!e){const r=await be(t);return{...A(r),mfa:null}}if("provider"in e){const{provider:r,options:n}=e,i=J(`${this._client.backendUrl}/signin/provider/${r}`,w(this._client.clientUrl,n));return V()&&(window.location.href=i),{providerUrl:i,provider:r,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const r=await Ce(t,e.email,e.password);return r.needsEmailVerification?{session:null,mfa:null,error:le}:r.needsMfaOtp?{session:null,mfa:r.mfa,error:null}:{...A(r),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const r=await De(t,e.email);return{...A(r),mfa:null}}if("email"in e){const{email:r,options:n}=e,{error:i}=await Y(t,r,n);return{session:null,mfa:null,error:i}}if("phoneNumber"in e&&"otp"in e){const r=await Ue(t,e.phoneNumber,e.otp);return{...A(r),mfa:null}}if("phoneNumber"in e){const{error:r}=await j(t,e.phoneNumber,e.options);return{error:r,mfa:null,session:null}}if("otp"in e){const r=await Me(t,e.otp,e.ticket);return{...A(r),mfa:null}}return{error:he,mfa:null,session:null}}async signOut(e){const t=await this.waitUntilReady(),{error:r}=await xe(t,e==null?void 0:e.all);return{error:r}}async resetPassword({email:e,options:t}){const r=l.interpret(Re(this._client)).start(),{error:n}=await Pe(r,e,t);return{error:n}}async changePassword({newPassword:e,ticket:t}){const r=l.interpret(Se(this._client)).start(),{error:n}=await Oe(r,e,t);return{error:n}}async sendVerificationEmail({email:e,options:t}){const r=l.interpret(Ie(this._client)).start(),{error:n}=await Ne(r,e,t);return{error:n}}async changeEmail({newEmail:e,options:t}){const r=l.interpret(ye(this._client)).start(),{error:n}=await ke(r,e,t);return{error:n}}async deanonymize(e){const t=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:r}=await Y(t,e.email,e.options);return{error:r}}if(e.connection==="sms"){const{error:r}=await j(t,e.phoneNumber,e.options);return{error:r}}}if(e.signInMethod==="email-password"){const{error:r}=await B(t,e.email,e.password,e.options);return{error:r}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:t,key:r}=await ve(this._client,e);return{error:t,key:r}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const t=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:n,context:i})=>{n.type==="TOKEN_CHANGED"&&e(b(i))});return()=>t==null?void 0:t.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const t=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:n,context:i})=>{(n.type==="SIGNED_IN"||n.type==="SIGNED_OUT")&&e(n.type,b(i))});return()=>t==null?void 0:t.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 t;const e=((t=this.client.interpreter)==null?void 0:t.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:e}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:e}}getJWTToken(){return this.getAccessToken()}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Le(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var t;return((t=this.getHasuraClaims())==null?void 0:t[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const t=await this.waitUntilReady();return new Promise(r=>{const n=e||t.getSnapshot().context.refreshToken.value;if(!n)return r({session:null,error:ae});const{changed:i}=t.send("TRY_TOKEN",{token:n});if(!i)return r({session:null,error:ce});t.onTransition(c=>{c.matches({token:{idle:"error"}})?r({session:null,error:de}):c.event.type==="TOKEN_CHANGED"&&r({session:b(c.context),error:null})})})}catch(t){return{session:null,error:t.message}}}getSession(){var e,t;return b((t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:t.context)}getUser(){var e,t,r;return((r=(t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:t.context)==null?void 0:r.user)||null}waitUntilReady(){const t=this._client.interpreter;if(!t)throw Error("Auth interpreter not set");return t.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);t.onTransition(c=>{if(!c.hasTag("loading"))return clearTimeout(i),r(t)})}):Promise.resolve(t)}isReady(){var e,t;return!((t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&t.hasTag("loading"))}get client(){return this._client}}exports.AuthClient=Z;exports.AuthClientSSR=Je;exports.AuthCookieClient=Ae;exports.CodifiedError=D;exports.EMAIL_NEEDS_VERIFICATION=le;exports.HasuraAuthClient=rr;exports.INITIAL_MACHINE_CONTEXT=M;exports.INVALID_EMAIL_ERROR=R;exports.INVALID_MFA_CODE_ERROR=ne;exports.INVALID_MFA_TICKET_ERROR=ie;exports.INVALID_MFA_TYPE_ERROR=se;exports.INVALID_PASSWORD_ERROR=x;exports.INVALID_PHONE_NUMBER_ERROR=W;exports.INVALID_REFRESH_TOKEN=de;exports.INVALID_SIGN_IN_METHOD=he;exports.MIN_PASSWORD_LENGTH=re;exports.NETWORK_ERROR_CODE=z;exports.NHOST_JWT_EXPIRES_AT_KEY=N;exports.NHOST_REFRESH_TOKEN_KEY=P;exports.NO_MFA_TICKET_ERROR=oe;exports.NO_REFRESH_TOKEN=ae;exports.OTHER_ERROR_CODE=Q;exports.REFRESH_TOKEN_MAX_ATTEMPTS=H;exports.STATE_ERROR_CODE=O;exports.TOKEN_REFRESHER_RUNNING_ERROR=ce;exports.TOKEN_REFRESH_MARGIN=te;exports.USER_ALREADY_SIGNED_IN=y;exports.USER_NOT_ANONYMOUS=qe;exports.USER_UNAUTHENTICATED=ue;exports.VALIDATION_ERROR_CODE=_;exports.activateMfaPromise=er;exports.addSecurityKeyPromise=ve;exports.changeEmailPromise=ke;exports.changePasswordPromise=Oe;exports.createAuthMachine=_e;exports.createChangeEmailMachine=ye;exports.createChangePasswordMachine=Se;exports.createEnableMfaMachine=Xe;exports.createResetPasswordMachine=Re;exports.createSendVerificationEmailMachine=Ie;exports.encodeQueryParameters=J;exports.generateQrCodePromise=Ze;exports.getAuthenticationResult=A;exports.getParameterByName=C;exports.getSession=b;exports.isBrowser=V;exports.isValidEmail=I;exports.isValidPassword=L;exports.isValidPhoneNumber=F;exports.isValidTicket=we;exports.localStorageGetter=pe;exports.localStorageSetter=Te;exports.nhostApiClient=v;exports.removeParameterFromWindow=$;exports.resetPasswordPromise=Pe;exports.rewriteRedirectTo=w;exports.sendVerificationEmailPromise=Ne;exports.signInAnonymousPromise=be;exports.signInEmailPasswordPromise=Ce;exports.signInEmailPasswordlessPromise=Y;exports.signInEmailSecurityKeyPromise=De;exports.signInMfaTotpPromise=Me;exports.signInSmsPasswordlessOtpPromise=Ue;exports.signInSmsPasswordlessPromise=j;exports.signOutPromise=xe;exports.signUpEmailPasswordPromise=B;exports.signUpEmailSecurityKeyPromise=Ke; | ||
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ve=require("jwt-decode"),l=require("xstate"),V=require("js-cookie"),Le=require("cross-fetch"),v="nhostRefreshToken",k="nhostRefreshTokenExpiresAt",J=3,Z=300,L=5,j=0,Y=1,T=10,A=20;class N extends Error{constructor(e){super(e.message),Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Y,message:e.message}):(this.name=e.error,this.error=e)}}const y={status:T,error:"invalid-email",message:"Email is incorrectly formatted"},ee={status:T,error:"invalid-mfa-type",message:"MFA type is invalid"},re={status:T,error:"invalid-mfa-code",message:"MFA code is invalid"},D={status:T,error:"invalid-password",message:"Password is incorrectly formatted"},G={status:T,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},te={status:T,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},se={status:T,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},ne={status:T,error:"no-refresh-token",message:"No refresh token has been provided"},ie={status:A,error:"refresher-already-running",message:"The token refresher is already running. You must wait until is has finished before submitting a new token."},w={status:A,error:"already-signed-in",message:"User is already signed in"},oe={status:A,error:"unauthenticated-user",message:"User is not authenticated"},Ge={status:A,error:"user-not-anonymous",message:"User is not anonymous"},ae={status:A,error:"unverified-user",message:"Email needs verification"},ce={status:T,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},ue={status:Y,error:"invalid-sign-in-method",message:"Invalid sign-in method"},b={user:null,mfa:null,accessToken:{value:null,expiresAt:null},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function qe(s){return new TextEncoder().encode(s)}function I(s){const e=new Uint8Array(s);let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function B(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,r=e.padEnd(e.length+t,"="),n=atob(r),i=new ArrayBuffer(n.length),c=new Uint8Array(i);for(let h=0;h<n.length;h++)c[h]=n.charCodeAt(h);return i}function le(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function de(s){const{id:e}=s;return{...s,id:B(e),transports:s.transports}}function he(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}class g extends Error{constructor(e,t="WebAuthnError"){super(e),this.name=t}}function He({error:s,options:e}){var t,r;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal===new AbortController().signal)return new g("Registration ceremony was sent an abort signal","AbortError")}else if(s.name==="ConstraintError"){if(((t=n.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new g("Discoverable credentials were required but no available authenticator supported it","ConstraintError");if(((r=n.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new g("User verification was required but no available authenticator supported it","ConstraintError")}else{if(s.name==="InvalidStateError")return new g("The authenticator was previously registered","InvalidStateError");if(s.name==="NotAllowedError")return new g("User clicked cancel, or the registration ceremony timed out","NotAllowedError");if(s.name==="NotSupportedError")return n.pubKeyCredParams.filter(c=>c.type==="public-key").length===0?new g('No entry in pubKeyCredParams was of type "public-key"',"NotSupportedError"):new g("No available authenticator supported any of the specified pubKeyCredParams algorithms","NotSupportedError");if(s.name==="SecurityError"){const i=window.location.hostname;if(he(i)){if(n.rp.id!==i)return new g(`The RP ID "${n.rp.id}" is invalid for this domain`,"SecurityError")}else return new g(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(s.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new g("User ID was not between 1 and 64 characters","TypeError")}else if(s.name==="UnknownError")return new g("The authenticator was unable to process the specified options, or could not create a new credential","UnknownError")}return s}class We{createNewAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}reset(){this.controller=void 0}}const M=new We;async function fe(s){if(!le())throw new Error("WebAuthn is not supported in this browser");const t={publicKey:{...s,challenge:B(s.challenge),user:{...s.user,id:qe(s.user.id)},excludeCredentials:s.excludeCredentials.map(de)}};t.signal=M.createNewAbortSignal();let r;try{r=await navigator.credentials.create(t)}catch(f){throw He({error:f,options:t})}finally{M.reset()}if(!r)throw new Error("Registration was not completed");const{id:n,rawId:i,response:c,type:h}=r,m={id:n,rawId:I(i),response:{attestationObject:I(c.attestationObject),clientDataJSON:I(c.clientDataJSON)},type:h,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:r.authenticatorAttachment};return typeof c.getTransports=="function"&&(m.transports=c.getTransports()),m}function Fe(s){return new TextDecoder("utf-8").decode(s)}async function $e(){if(navigator.credentials.conditionalMediationSupported)return!0;const s=window.PublicKeyCredential;return s.isConditionalMediationAvailable!==void 0&&s.isConditionalMediationAvailable()}function je({error:s,options:e}){var t;const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal===new AbortController().signal)return new g("Authentication ceremony was sent an abort signal","AbortError")}else{if(s.name==="NotAllowedError")return!((t=r.allowCredentials)===null||t===void 0)&&t.length?new g("No available authenticator recognized any of the allowed credentials","NotAllowedError"):new g("User clicked cancel, or the authentication ceremony timed out","NotAllowedError");if(s.name==="SecurityError"){const n=window.location.hostname;if(he(n)){if(r.rpId!==n)return new g(`The RP ID "${r.rpId}" is invalid for this domain`,"SecurityError")}else return new g(`${window.location.hostname} is an invalid domain`,"SecurityError")}else if(s.name==="UnknownError")return new g("The authenticator was unable to process the specified options, or could not create a new assertion signature","UnknownError")}return s}async function Ye(s,e=!1){var t,r;if(!le())throw new Error("WebAuthn is not supported in this browser");let n;((t=s.allowCredentials)===null||t===void 0?void 0:t.length)!==0&&(n=(r=s.allowCredentials)===null||r===void 0?void 0:r.map(de));const i={...s,challenge:B(s.challenge),allowCredentials:n},c={};if(e){if(!await $e())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');c.mediation="conditional",i.allowCredentials=[]}c.publicKey=i,c.signal=M.createNewAbortSignal();let h;try{h=await navigator.credentials.get(c)}catch(d){throw je({error:d,options:c})}finally{M.reset()}if(!h)throw new Error("Authentication was not completed");const{id:m,rawId:f,response:o,type:a}=h;let u;return o.userHandle&&(u=Fe(o.userHandle)),{id:m,rawId:I(f),response:{authenticatorData:I(o.authenticatorData),clientDataJSON:I(o.clientDataJSON),signature:I(o.signature),userHandle:u},type:a,clientExtensionResults:h.getClientExtensionResults(),authenticatorAttachment:h.authenticatorAttachment}}const K=typeof window<"u",C=new Map,Be=s=>K&&typeof localStorage<"u"?localStorage.getItem(s):C.get(s)??null,Qe=(s,e)=>{K&&typeof localStorage<"u"?e?localStorage.setItem(s,e):localStorage.removeItem(s):e?C.set(s,e):C.has(s)&&C.delete(s)},me=(s,e)=>{if(s==="localStorage"||s==="web")return Be;if(s==="cookie")return t=>K?V.get(t)??null:null;if(!e)throw Error(`clientStorageType is set to '${s}' but no clientStorage has been given`);if(s==="react-native")return t=>{var r;return(r=e.getItem)==null?void 0:r.call(e,t)};if(s==="capacitor")return t=>{var r;return(r=e.get)==null?void 0:r.call(e,{key:t})};if(s==="expo-secure-storage")return t=>{var r;return(r=e.getItemAsync)==null?void 0:r.call(e,t)};if(s==="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: ${s}`)},Ee=(s,e)=>{if(s==="localStorage"||s==="web")return Qe;if(s==="cookie")return(t,r)=>{K&&(r?V.set(t,r,{expires:30,sameSite:"lax",httpOnly:!1}):V.remove(t))};if(!e)throw Error(`clientStorageType is set to '${s}' but no clienStorage has been given`);if(s==="react-native")return(t,r)=>{var n,i;return r?(n=e.setItem)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};if(s==="capacitor")return(t,r)=>{var n,i;return r?(n=e.set)==null?void 0:n.call(e,{key:t,value:r}):(i=e.remove)==null?void 0:i.call(e,{key:t})};if(s==="expo-secure-storage")return async(t,r)=>{var n,i;return r?(n=e.setItemAsync)==null?void 0:n.call(e,t,r):(i=e.deleteItemAsync)==null?void 0:i.call(e,t)};if(s==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(t,r)=>{var n,i;return r?(n=e.setItem)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};if(e.setItemAsync)return async(t,r)=>{var n,i;return r?(n=e.setItemAsync)==null?void 0:n.call(e,t,r):(i=e.removeItem)==null?void 0:i.call(e,t)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${s}`)},O=s=>!s||!s.accessToken.value||!s.refreshToken.value||!s.accessToken.expiresAt||!s.user?null:{accessToken:s.accessToken.value,accessTokenExpiresIn:(s.accessToken.expiresAt.getTime()-Date.now())/1e3,refreshToken:s.refreshToken.value,user:s.user},R=({accessToken:s,isError:e,user:t,error:r})=>e?{session:null,error:r}:t&&s?{session:{accessToken:s,accessTokenExpiresIn:0,refreshToken:"",user:t},error:null}:{session:null,error:null},U=()=>typeof window<"u",ge=async(s,e,{token:t,body:r}={})=>{const n={"Content-Type":"application/json",Accept:"*/*"};t&&(n.Authorization=`Bearer ${t}`);const i={method:e,headers:n};r&&(i.body=JSON.stringify(r));try{const c=await Le(s,i);if(!c.ok){const h=await c.json();return Promise.reject({error:h})}try{return{data:await c.json(),error:null}}catch{return console.warn(`Unexpected response: can't parse the response of the server at ${s}`),{data:"OK",error:null}}}catch{const h={message:"Network Error",status:j,error:"network"};return Promise.reject({error:h})}},S=async(s,e,t)=>ge(s,"POST",{token:t,body:e}),pe=(s,e)=>ge(s,"GET",{token:e}),Q=(s,e)=>{const t=e&&Object.entries(e).map(([r,n])=>{const i=Array.isArray(n)?n.join(","):typeof n=="object"?JSON.stringify(n):n;return`${r}=${encodeURIComponent(i)}`}).join("&");return t?`${s}?${t}`:s},p=(s,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:t,...r}=e;if(!s)return t.startsWith("/")?r:e;const n=new URL(s),i=Object.fromEntries(new URLSearchParams(n.search)),c=new URL(t.startsWith("/")?n.origin+t:t),h=new URLSearchParams(c.search);let m=Object.fromEntries(h);t.startsWith("/")&&(m={...i,...m});let f=n.pathname;return c.pathname.length>1&&(f+=c.pathname.slice(1)),{...r,redirectTo:Q(c.origin+f,m)}};function P(s,e){var n;if(!e){if(typeof window>"u")return;e=((n=window.location)==null?void 0:n.href)||""}s=s.replace(/[\[\]]/g,"\\$&");const t=new RegExp("[?&#]"+s+"(=([^&#]*)|&|#|$)"),r=t.exec(e);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}function q(s){var t;if(typeof window>"u")return;const e=window==null?void 0:window.location;if(e&&e){const r=new URLSearchParams(e.search),n=new URLSearchParams((t=e.hash)==null?void 0:t.slice(1));r.delete(s),n.delete(s);let i=window.location.pathname;Array.from(r).length&&(i+=`?${r.toString()}`),Array.from(n).length&&(i+=`#${n.toString()}`),window.history.pushState({},"",i)}}const _=s=>!!s&&typeof s=="string"&&!!String(s).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,}))$/),x=s=>!!s&&typeof s=="string"&&s.length>=J,H=s=>!!s&&typeof s=="string",Te=s=>s&&typeof s=="string"&&s.match(/^mfaTotp:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),we=({backendUrl:s,clientUrl:e,clientStorageType:t="web",clientStorage:r,refreshIntervalTime:n,autoRefreshToken:i=!0,autoSignIn:c=!0})=>{const h=me(t,r),m=Ee(t,r),f=async(o,a,u)=>(await S(`${s}${o}`,a,u)).data;return l.createMachine({schema:{context:{},events:{},services:{}},tsTypes:{},context:b,predictableActionArguments:!0,id:"nhost",type:"parallel",states:{authentication:{initial:"starting",on:{SESSION_UPDATE:[{cond:"hasSession",actions:["saveSession","resetTimer","reportTokenChanged"],target:".signedIn"}]},states:{starting:{tags:["loading"],always:{cond:"isSignedIn",target:"signedIn"},invoke:{id:"importRefreshToken",src:"importRefreshToken",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"signedIn"},{target:"signedOut"}],onError:[{cond:"shouldRetryImportToken",actions:"incrementTokenImportAttempts",target:"retryTokenImport"},{actions:["saveAuthenticationError"],target:"signedOut"}]}},retryTokenImport:{tags:["loading"],after:{RETRY_IMPORT_TOKEN_DELAY:"starting"}},signedOut:{initial:"noErrors",entry:"reportSignedOut",states:{noErrors:{},success:{},needsSmsOtp:{},needsMfa:{},failed:{},signingOut:{entry:["clearContextExceptRefreshToken"],exit:["destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_MFA_TOTP:"authenticating.mfa.totp"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:l.send("SIGNED_IN"),reportSignedOut:l.send("SIGNED_OUT"),reportTokenChanged:l.send("TOKEN_CHANGED"),incrementTokenImportAttempts:l.assign({importTokenAttempts:({importTokenAttempts:o})=>o+1}),clearContext:l.assign(()=>(m(k,null),m(v,null),{...b})),clearContextExceptRefreshToken:l.assign(({refreshToken:{value:o}})=>(m(k,null),{...b,refreshToken:{value:o}})),saveSession:l.assign({user:(o,{data:a})=>{var u;return((u=a==null?void 0:a.session)==null?void 0:u.user)||null},accessToken:(o,{data:a})=>{if(a.session){const{accessTokenExpiresIn:u,accessToken:d}=a.session,E=new Date(Date.now()+u*1e3);return m(k,E.toISOString()),{value:d,expiresAt:E}}return m(k,null),{value:null,expiresAt:null}},refreshToken:(o,{data:a})=>{var d;const u=((d=a.session)==null?void 0:d.refreshToken)||null;return u&&m(v,u),{value:u}}}),saveMfaTicket:l.assign({mfa:(o,a)=>{var u;return(u=a.data)==null?void 0:u.mfa}}),resetTimer:l.assign({refreshTimer:o=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:l.assign({refreshTimer:(o,a)=>({startedAt:o.refreshTimer.startedAt,attempts:o.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:l.assign({errors:({errors:o},{data:{error:a}})=>({...o,authentication:a})}),resetErrors:l.assign({errors:o=>({}),importTokenAttempts:o=>0}),saveRegistrationError:l.assign({errors:({errors:o},{data:{error:a}})=>({...o,registration:a})}),destroyRefreshToken:l.assign({refreshToken:o=>(m(v,null),{value:null})}),cleanUrl:()=>{c&&P("refreshToken")&&(q("refreshToken"),q("type"))},broadcastToken:o=>{if(c)try{new BroadcastChannel("nhost").postMessage(o.refreshToken.value)}catch{}}},guards:{isAnonymous:(o,a)=>{var u;return!!((u=o.user)!=null&&u.isAnonymous)},isSignedIn:o=>!!o.user&&!!o.refreshToken.value&&!!o.accessToken.value,noToken:o=>!o.refreshToken.value,hasRefreshToken:o=>!!o.refreshToken.value,isAutoRefreshDisabled:()=>!i,refreshTimerShouldRefresh:o=>{const{expiresAt:a}=o.accessToken;return a?o.refreshTimer.lastAttempt?o.refreshTimer.attempts>L?!1:Date.now()-o.refreshTimer.lastAttempt.getTime()>Math.pow(2,o.refreshTimer.attempts-1)*5e3:n&&Date.now()-o.refreshTimer.startedAt.getTime()>n*1e3?!0:a.getTime()-Date.now()-1e3*Z<=0:!1},shouldRetryImportToken:(o,a)=>o.importTokenAttempts<L&&(a.data.error.status===j||a.data.error.status>=500),unverified:(o,{data:{error:a}})=>a.status===401&&(a.message==="Email is not verified"||a.error==="unverified-user"),hasSession:(o,a)=>{var u;return!!((u=a.data)!=null&&u.session)},hasMfaTicket:(o,a)=>{var u;return!!((u=a.data)!=null&&u.mfa)}},services:{signInPassword:(o,{email:a,password:u})=>_(a)?x(u)?f("/signin/email-password",{email:a,password:u}):Promise.reject({error:D}):Promise.reject({error:y}),passwordlessSms:(o,{phoneNumber:a,options:u})=>{var d;return H(a)?(d=o.user)!=null&&d.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),f("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:a,options:p(e,u)},o.accessToken.value)):f("/signin/passwordless/sms",{phoneNumber:a,options:p(e,u)}):Promise.reject({error:G})},passwordlessSmsOtp:(o,{phoneNumber:a,otp:u})=>H(a)?f("/signin/passwordless/sms/otp",{phoneNumber:a,otp:u}):Promise.reject({error:G}),passwordlessEmail:(o,{email:a,options:u})=>{var d;return _(a)?(d=o.user)!=null&&d.isAnonymous?f("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:a,options:p(e,u)},o.accessToken.value):f("/signin/passwordless/email",{email:a,options:p(e,u)}):Promise.reject({error:y})},signInAnonymous:o=>f("/signin/anonymous"),signInMfaTotp:(o,a)=>{var d;const u=a.ticket||((d=o.mfa)==null?void 0:d.ticket);return u?Te(u)?f("/signin/mfa/totp",{ticket:u,otp:a.otp}):Promise.reject({error:te}):Promise.reject({error:se})},signInSecurityKeyEmail:async(o,{email:a})=>{if(!_(a))throw new N(y);const u=await f("/signin/webauthn",{email:a});let d;try{d=await Ye(u)}catch(E){throw new N(E)}return f("/signin/webauthn/verify",{email:a,credential:d})},refreshToken:async(o,a)=>{const u=a.type==="TRY_TOKEN"?a.token:o.refreshToken.value;return{session:await f("/token",{refreshToken:u}),error:null}},signout:(o,a)=>f("/signout",{refreshToken:o.refreshToken.value,all:!!a.all}),signUpEmailPassword:async(o,{email:a,password:u,options:d})=>{var E;return _(a)?x(u)?(E=o.user)!=null&&E.isAnonymous?f("/user/deanonymize",{signInMethod:"email-password",email:a,password:u,options:p(e,d)},o.accessToken.value):f("/signup/email-password",{email:a,password:u,options:p(e,d)}):Promise.reject({error:D}):Promise.reject({error:y})},signUpSecurityKey:async(o,{email:a,options:u})=>{if(!_(a))return Promise.reject({error:y});const d=u==null?void 0:u.nickname;d&&delete u.nickname;const E=await f("/signup/webauthn",{email:a,options:u});let X;try{X=await fe(E)}catch(Ke){throw new N(Ke)}return f("/signup/webauthn/verify",{credential:X,options:{redirectTo:u==null?void 0:u.redirectTo,nickname:d}})},importRefreshToken:async o=>{if(o.user&&o.refreshToken.value&&o.accessToken.value&&o.accessToken.expiresAt)return{session:{accessToken:o.accessToken.value,accessTokenExpiresIn:o.accessToken.expiresAt.getTime()-Date.now(),refreshToken:o.refreshToken.value,user:o.user},error:null};let a=null;if(c){const d=P("refreshToken")||null;if(d)try{return{session:await f("/token",{refreshToken:d}),error:null}}catch(E){a=E.error}else{const E=P("error");if(E)return Promise.reject({session:null,error:{status:T,error:E,message:P("errorDescription")||E}})}}const u=await h(v);if(u)try{return{session:await f("/token",{refreshToken:u}),error:null}}catch(d){a=d.error}return a?Promise.reject({error:a,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:o})=>Math.pow(2,o-1)*5e3}})},ye=({backendUrl:s,clientUrl:e,interpreter:t})=>l.createMachine({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:l.assign({error:r=>y}),saveRequestError:l.assign({error:(r,{data:{error:n}})=>n}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!_(n)},services:{requestChange:async(r,{email:n,options:i})=>(await S(`${s}/user/email/change`,{newEmail:n,options:p(e,i)},t==null?void 0:t.getSnapshot().context.accessToken.value)).data}}),_e=({backendUrl:s,interpreter:e})=>l.createMachine({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:l.assign({error:t=>D}),saveRequestError:l.assign({error:(t,{data:{error:r}})=>r}),reportError:l.send(t=>({type:"ERROR",error:t.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidPassword:(t,{password:r})=>!x(r)},services:{requestChange:(t,{password:r,ticket:n})=>S(`${s}/user/password`,{newPassword:r,ticket:n},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ze=({backendUrl:s,interpreter:e})=>l.createMachine({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:l.assign({error:t=>ee}),saveInvalidMfaCodeError:l.assign({error:t=>re}),saveError:l.assign({error:(t,{data:{error:r}})=>r}),saveGeneration:l.assign({imageUrl:(t,{data:{imageUrl:r}})=>r,secret:(t,{data:{totpSecret:r}})=>r}),reportError:l.send((t,r)=>(console.log("REPORT",t,r),{type:"ERROR",error:t.error})),reportSuccess:l.send("SUCCESS"),reportGeneratedSuccess:l.send("GENERATED"),reportGeneratedError:l.send(t=>({type:"GENERATED_ERROR",error:t.error}))},guards:{invalidMfaCode:(t,{code:r})=>!r,invalidMfaType:(t,{activeMfaType:r})=>!r||r!=="totp"},services:{generate:async t=>{const{data:r}=await pe(`${s}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return r},activate:(t,{code:r,activeMfaType:n})=>S(`${s}/user/mfa`,{code:r,activeMfaType:n},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Se=({backendUrl:s,clientUrl:e})=>l.createMachine({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:l.assign({error:t=>y}),saveRequestError:l.assign({error:(t,{data:{error:r}})=>r}),reportError:l.send(t=>({type:"ERROR",error:t.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(t,{email:r})=>!_(r)},services:{requestChange:(t,{email:r,options:n})=>S(`${s}/user/password/reset`,{email:r,options:p(e,n)})}}),Re=({backendUrl:s,clientUrl:e})=>l.createMachine({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:l.assign({error:t=>y}),saveRequestError:l.assign({error:(t,{data:{error:r}})=>r}),reportError:l.send(t=>({type:"ERROR",error:t.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(t,{email:r})=>!_(r)},services:{request:async(t,{email:r,options:n})=>(await S(`${s}/user/email/send-verification-email`,{email:r,options:p(e,n)})).data}});class z{constructor({clientStorageType:e="web",autoSignIn:t=!0,autoRefreshToken:r=!0,start:n=!0,backendUrl:i,clientUrl:c,devTools:h,...m}){if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=i,this.clientUrl=c,this._machine=we({...m,backendUrl:i,clientUrl:c,clientStorageType:e,autoSignIn:t,autoRefreshToken:r}),n&&this.start({devTools:h}),typeof window<"u"&&t)try{this._channel=new BroadcastChannel("nhost"),this._channel.addEventListener("message",f=>{var a;const o=(a=this.interpreter)==null?void 0:a.getSnapshot().context.refreshToken.value;this.interpreter&&f.data!==o&&this.interpreter.send("TRY_TOKEN",{token:f.data})})}catch{}}start({devTools:e=!1,initialSession:t,interpreter:r}={}){const n={...this.machine.context};t&&(n.user=t.user,n.refreshToken.value=t.refreshToken??null,n.accessToken.value=t.accessToken??null,n.accessToken.expiresAt=new Date(Date.now()+t.accessTokenExpiresIn*1e3));const i=this.machine.withContext(n);this._interpreter||(this._interpreter=r||l.interpret(i,{devTools:e})),(!this._started||typeof window>"u")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(c=>c())),this._interpreter.start(i.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 t=e(this);return this._subscriptions.add(t),t}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class Ie extends z{constructor({...e}){super({...e,autoSignIn:U()&&e.autoSignIn,autoRefreshToken:U()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const Xe=Ie,Ae=async({backendUrl:s,interpreter:e},t)=>{try{const{data:r}=await S("/user/webauthn/add",{},e==null?void 0:e.getSnapshot().context.accessToken.value);let n;try{n=await fe(r)}catch(c){throw new N(c)}const{data:i}=await S(`${s}/user/webauthn/verify`,{credential:n,nickname:t},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:i,isError:!1,error:null,isSuccess:!0}}catch(r){const{error:n}=r;return{isError:!0,error:n,isSuccess:!1}}},ve=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,needsEmailVerification:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,needsEmailVerification:!0})})}),ke=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{password:e,ticket:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSuccess:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSuccess:!0})})}),Je=s=>new Promise(e=>{s.send("GENERATE"),s.onTransition(t=>{t.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:t.context.imageUrl||""}):t.matches({idle:"error"})&&e({error:t.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),Ze=(s,e)=>new Promise(t=>{s.send("ACTIVATE",{activeMfaType:"totp",code:e}),s.onTransition(r=>{r.matches({generated:"activated"})?t({error:null,isActivated:!0,isError:!1}):r.matches({generated:{idle:"error"}})&&t({error:r.context.error,isActivated:!1,isError:!0})})}),Oe=async(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSent:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),Pe=(s,e,t)=>new Promise(r=>{s.send("REQUEST",{email:e,options:t}),s.onTransition(n=>{n.matches({idle:"error"})?r({error:n.context.error,isError:!0,isSent:!1}):n.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),Ne=s=>new Promise(e=>{const{changed:t}=s.send("SIGNIN_ANONYMOUS");t||e({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null}),s.onTransition(r=>{r.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:r.context.user,accessToken:r.context.accessToken.value}),r.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:r.context.errors.authentication||null,user:null,accessToken:null})})}),be=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNIN_PASSWORD",{email:e,password:t});if(!n)return r({accessToken:i.accessToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:i.user});s.onTransition(c=>{c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):c.matches({authentication:{signedOut:"needsMfa"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:c.context.mfa,user:null}):c.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:c.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):c.matches({authentication:"signedIn"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:c.context.user})})}),W=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send("PASSWORDLESS_EMAIL",{email:e,options:t});if(!n)return r({error:w,isError:!0,isSuccess:!1});s.onTransition(i=>{i.matches("registration.incomplete.failed")?r({error:i.context.errors.registration||null,isError:!0,isSuccess:!1}):i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&r({error:null,isError:!1,isSuccess:!0})})}),Ce=(s,e)=>new Promise(t=>{const{changed:r,context:n}=s.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!r)return t({accessToken:n.accessToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:n.user});s.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?t({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?t({accessToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&t({accessToken:i.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),De=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNIN_MFA_TOTP",{otp:e,ticket:t});if(!n)return r({accessToken:i.accessToken.value,error:w,isError:!0,isSuccess:!1,user:i.user});s.onTransition(c=>{c.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,error:c.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):c.matches({authentication:"signedIn"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,user:c.context.user})})}),F=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send("PASSWORDLESS_SMS",{phoneNumber:e,options:t});if(!n)return r({error:w,isError:!0,isSuccess:!1,needsOtp:!1});s.onTransition(i=>{i.matches("registration.incomplete.needsOtp")?r({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):i.matches("registration.incomplete.failed")&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),Me=(s,e,t)=>new Promise(r=>{const{changed:n}=s.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:t});if(!n)return r({error:w,isError:!0,isSuccess:!1,user:null,accessToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?r({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value}):i.matches({registration:{incomplete:"failed"}})&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null})})}),Ue=async(s,e)=>new Promise(t=>{const{event:r}=s.send("SIGNOUT",{all:e});if(r.type!=="SIGNED_OUT")return t({isSuccess:!1,isError:!0,error:oe});s.onTransition(n=>{n.matches({authentication:{signedOut:"success"}})?t({isSuccess:!0,isError:!1,error:null}):n.matches("authentication.signedOut.failed")&&t({isSuccess:!1,isError:!0,error:n.context.errors.signout||null})})}),$=(s,e,t,r)=>new Promise(n=>{const{changed:i,context:c}=s.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:t,options:r});if(!i)return n({error:w,accessToken:c.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:c.user});s.onTransition(h=>{h.matches("registration.incomplete.failed")?n({accessToken:null,error:h.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):h.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):h.matches({authentication:"signedIn",registration:"complete"})&&n({accessToken:h.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:h.context.user})})}),xe=(s,e,t)=>new Promise(r=>{const{changed:n,context:i}=s.send("SIGNUP_SECURITY_KEY",{email:e,options:t});if(!n)return r({error:w,accessToken:i.accessToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});s.onTransition(c=>{c.matches("registration.incomplete.failed")?r({accessToken:null,error:c.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):c.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):c.matches({authentication:"signedIn",registration:"complete"})&&r({accessToken:c.context.accessToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:c.context.user})})});class er{constructor({url:e,autoRefreshToken:t=!0,autoSignIn:r=!0,clientStorage:n,clientStorageType:i,refreshIntervalTime:c,start:h=!0}){var m;this.url=e,this._client=new z({backendUrl:e,clientUrl:typeof window<"u"&&((m=window.location)==null?void 0:m.origin)||"",autoRefreshToken:t,autoSignIn:r,start:h,clientStorage:n,clientStorageType:i,refreshIntervalTime:c})}async signUp(e){const t=await this.waitUntilReady(),{email:r,options:n}=e;return"securityKey"in e?R(await xe(t,r,n)):R(await $(t,r,e.password,n))}async signIn(e){const t=await this.waitUntilReady();if(!e){const r=await Ne(t);return{...R(r),mfa:null}}if("provider"in e){const{provider:r,options:n}=e,i=Q(`${this._client.backendUrl}/signin/provider/${r}`,p(this._client.clientUrl,n));return U()&&(window.location.href=i),{providerUrl:i,provider:r,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const r=await be(t,e.email,e.password);return r.needsEmailVerification?{session:null,mfa:null,error:ae}:r.needsMfaOtp?{session:null,mfa:r.mfa,error:null}:{...R(r),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const r=await Ce(t,e.email);return{...R(r),mfa:null}}if("email"in e){const{email:r,options:n}=e,{error:i}=await W(t,r,n);return{session:null,mfa:null,error:i}}if("phoneNumber"in e&&"otp"in e){const r=await Me(t,e.phoneNumber,e.otp);return{...R(r),mfa:null}}if("phoneNumber"in e){const{error:r}=await F(t,e.phoneNumber,e.options);return{error:r,mfa:null,session:null}}if("otp"in e){const r=await De(t,e.otp,e.ticket);return{...R(r),mfa:null}}return{error:ue,mfa:null,session:null}}async signOut(e){const t=await this.waitUntilReady(),{error:r}=await Ue(t,e==null?void 0:e.all);return{error:r}}async resetPassword({email:e,options:t}){const r=l.interpret(Se(this._client)).start(),{error:n}=await Oe(r,e,t);return{error:n}}async changePassword({newPassword:e,ticket:t}){const r=l.interpret(_e(this._client)).start(),{error:n}=await ke(r,e,t);return{error:n}}async sendVerificationEmail({email:e,options:t}){const r=l.interpret(Re(this._client)).start(),{error:n}=await Pe(r,e,t);return{error:n}}async changeEmail({newEmail:e,options:t}){const r=l.interpret(ye(this._client)).start(),{error:n}=await ve(r,e,t);return{error:n}}async deanonymize(e){const t=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:r}=await W(t,e.email,e.options);return{error:r}}if(e.connection==="sms"){const{error:r}=await F(t,e.phoneNumber,e.options);return{error:r}}}if(e.signInMethod==="email-password"){const{error:r}=await $(t,e.email,e.password,e.options);return{error:r}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:t,key:r}=await Ae(this._client,e);return{error:t,key:r}}onTokenChanged(e){return this._client.subscribe(()=>{var r;const t=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:n,context:i})=>{n.type==="TOKEN_CHANGED"&&e(O(i))});return()=>t==null?void 0:t.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const t=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:n,context:i})=>{(n.type==="SIGNED_IN"||n.type==="SIGNED_OUT")&&e(n.type,O(i))});return()=>t==null?void 0:t.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 t;const e=((t=this.client.interpreter)==null?void 0:t.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:e}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:e}}getAccessToken(){var e;return((e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)??void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Ve(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var t;return((t=this.getHasuraClaims())==null?void 0:t[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const t=await this.waitUntilReady();return new Promise(r=>{const n=e||t.getSnapshot().context.refreshToken.value;if(!n)return r({session:null,error:ne});const{changed:i}=t.send("TRY_TOKEN",{token:n});if(!i)return r({session:null,error:ie});t.onTransition(c=>{c.matches({token:{idle:"error"}})?r({session:null,error:ce}):c.event.type==="TOKEN_CHANGED"&&r({session:O(c.context),error:null})})})}catch(t){return{session:null,error:t.message}}}getSession(){var e,t;return O((t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:t.context)}getUser(){var e,t,r;return((r=(t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:t.context)==null?void 0:r.user)||null}waitUntilReady(){const t=this._client.interpreter;if(!t)throw Error("Auth interpreter not set");return t.getSnapshot().hasTag("loading")?new Promise((r,n)=>{let i=setTimeout(()=>n(`The state machine is not yet ready after ${15} seconds.`),15e3);t.onTransition(c=>{if(!c.hasTag("loading"))return clearTimeout(i),r(t)})}):Promise.resolve(t)}isReady(){var e,t;return!((t=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&t.hasTag("loading"))}get client(){return this._client}}exports.AuthClient=z;exports.AuthClientSSR=Xe;exports.AuthCookieClient=Ie;exports.CodifiedError=N;exports.EMAIL_NEEDS_VERIFICATION=ae;exports.HasuraAuthClient=er;exports.INITIAL_MACHINE_CONTEXT=b;exports.INVALID_EMAIL_ERROR=y;exports.INVALID_MFA_CODE_ERROR=re;exports.INVALID_MFA_TICKET_ERROR=te;exports.INVALID_MFA_TYPE_ERROR=ee;exports.INVALID_PASSWORD_ERROR=D;exports.INVALID_PHONE_NUMBER_ERROR=G;exports.INVALID_REFRESH_TOKEN=ce;exports.INVALID_SIGN_IN_METHOD=ue;exports.MIN_PASSWORD_LENGTH=J;exports.NETWORK_ERROR_CODE=j;exports.NHOST_JWT_EXPIRES_AT_KEY=k;exports.NHOST_REFRESH_TOKEN_KEY=v;exports.NO_MFA_TICKET_ERROR=se;exports.NO_REFRESH_TOKEN=ne;exports.OTHER_ERROR_CODE=Y;exports.REFRESH_TOKEN_MAX_ATTEMPTS=L;exports.STATE_ERROR_CODE=A;exports.TOKEN_REFRESHER_RUNNING_ERROR=ie;exports.TOKEN_REFRESH_MARGIN=Z;exports.USER_ALREADY_SIGNED_IN=w;exports.USER_NOT_ANONYMOUS=Ge;exports.USER_UNAUTHENTICATED=oe;exports.VALIDATION_ERROR_CODE=T;exports.activateMfaPromise=Ze;exports.addSecurityKeyPromise=Ae;exports.changeEmailPromise=ve;exports.changePasswordPromise=ke;exports.createAuthMachine=we;exports.createChangeEmailMachine=ye;exports.createChangePasswordMachine=_e;exports.createEnableMfaMachine=ze;exports.createResetPasswordMachine=Se;exports.createSendVerificationEmailMachine=Re;exports.encodeQueryParameters=Q;exports.generateQrCodePromise=Je;exports.getAuthenticationResult=R;exports.getFetch=pe;exports.getParameterByName=P;exports.getSession=O;exports.isBrowser=U;exports.isValidEmail=_;exports.isValidPassword=x;exports.isValidPhoneNumber=H;exports.isValidTicket=Te;exports.localStorageGetter=me;exports.localStorageSetter=Ee;exports.postFetch=S;exports.removeParameterFromWindow=q;exports.resetPasswordPromise=Oe;exports.rewriteRedirectTo=p;exports.sendVerificationEmailPromise=Pe;exports.signInAnonymousPromise=Ne;exports.signInEmailPasswordPromise=be;exports.signInEmailPasswordlessPromise=W;exports.signInEmailSecurityKeyPromise=Ce;exports.signInMfaTotpPromise=De;exports.signInSmsPasswordlessOtpPromise=Me;exports.signInSmsPasswordlessPromise=F;exports.signOutPromise=Ue;exports.signUpEmailPasswordPromise=$;exports.signUpEmailSecurityKeyPromise=xe; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -48,3 +48,3 @@ import { InterpreterFrom } from 'xstate'; | ||
}; | ||
export declare const createAuthMachine: ({ backendUrl, clientUrl, clientStorageGetter, clientStorageSetter, clientStorageType, clientStorage, refreshIntervalTime, autoRefreshToken, autoSignIn }: AuthMachineOptions) => import("xstate").StateMachine<AuthContext, any, { | ||
export declare const createAuthMachine: ({ backendUrl, clientUrl, clientStorageType, clientStorage, refreshIntervalTime, autoRefreshToken, autoSignIn }: AuthMachineOptions) => import("xstate").StateMachine<AuthContext, any, { | ||
type: "SESSION_UPDATE"; | ||
@@ -51,0 +51,0 @@ data: { |
import { ErrorPayload, NhostSession } from './common'; | ||
interface NullableErrorResponse { | ||
export interface NullableErrorResponse { | ||
error: ErrorPayload | null; | ||
@@ -55,3 +55,2 @@ } | ||
export declare type SignInMfaTotpResponse = NhostSessionResponse; | ||
export {}; | ||
//# sourceMappingURL=responses.d.ts.map |
@@ -1,6 +0,6 @@ | ||
export * from './axios'; | ||
export * from './client-helpers'; | ||
export * from './environment'; | ||
export * from './fetch'; | ||
export * from './url'; | ||
export * from './validators'; | ||
//# sourceMappingURL=index.d.ts.map |
{ | ||
"name": "@nhost/hasura-auth-js", | ||
"version": "1.12.4", | ||
"version": "2.0.0", | ||
"description": "Hasura-auth client", | ||
@@ -46,3 +46,3 @@ "license": "MIT", | ||
"@simplewebauthn/browser": "^6.0.0", | ||
"axios": "^1.2.0", | ||
"cross-fetch": "^3.1.5", | ||
"js-cookie": "^3.0.1", | ||
@@ -49,0 +49,0 @@ "jwt-decode": "^3.1.2", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
1276659
6549
+ Addedcross-fetch@^3.1.5
+ Addedcross-fetch@3.2.0(transitive)
+ Addednode-fetch@2.7.0(transitive)
+ Addedtr46@0.0.3(transitive)
+ Addedwebidl-conversions@3.0.1(transitive)
+ Addedwhatwg-url@5.0.0(transitive)
- Removedaxios@^1.2.0
- Removedasynckit@0.4.0(transitive)
- Removedaxios@1.7.9(transitive)
- Removedcombined-stream@1.0.8(transitive)
- Removeddelayed-stream@1.0.0(transitive)
- Removedfollow-redirects@1.15.9(transitive)
- Removedform-data@4.0.1(transitive)
- Removedmime-db@1.52.0(transitive)
- Removedmime-types@2.1.35(transitive)
- Removedproxy-from-env@1.1.0(transitive)