You're Invited: Meet the Socket team at BSidesSF and RSAC - April 27 - May 1.RSVP
Socket
Sign inDemoInstall
Socket

@nhost/hasura-auth-js

Package Overview
Dependencies
Maintainers
0
Versions
117
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nhost/hasura-auth-js - npm Package Compare versions

Comparing version

to
2.10.2

4

dist/hasura-auth-client.d.ts
import { AuthClient } from './internal-client';
import { AuthChangedFunction, AuthErrorPayload, ChangeEmailParams, ChangeEmailResponse, ChangePasswordParams, ChangePasswordResponse, ConnectProviderParams, ConnectProviderResponse, DeanonymizeParams, DeanonymizeResponse, EmailOTPOptions, JWTClaims, JWTHasuraClaims, LinkIdTokenParams, NhostAuthConstructorParams, NhostSession, NhostSessionResponse, OnTokenChangedFunction, ResetPasswordParams, ResetPasswordResponse, SecurityKey, SendVerificationEmailParams, SendVerificationEmailResponse, SignInIdTokenParams, SignInParams, SignInPATResponse, SignInResponse, SignOutResponse, SignUpParams, SignUpResponse } from './types';
import { AuthChangedFunction, AuthErrorPayload, ChangeEmailParams, ChangeEmailResponse, ChangePasswordParams, ChangePasswordResponse, ConnectProviderParams, ConnectProviderResponse, DeanonymizeParams, DeanonymizeResponse, EmailOTPOptions, JWTClaims, JWTHasuraClaims, LinkIdTokenParams, NhostAuthConstructorParams, NhostSession, NhostSessionResponse, OnTokenChangedFunction, RequestOptions, ResetPasswordParams, ResetPasswordResponse, SecurityKey, SendVerificationEmailParams, SendVerificationEmailResponse, SignInIdTokenParams, SignInParams, SignInPATResponse, SignInResponse, SignOutResponse, SignUpParams, SignUpResponse } from './types';

@@ -33,3 +33,3 @@ /**

*/
signUp(params: SignUpParams): Promise<SignUpResponse>;
signUp(params: SignUpParams, requestOptions?: RequestOptions): Promise<SignUpResponse>;
/**

@@ -36,0 +36,0 @@ * Use `nhost.auth.connectProvider` to connect a social authentication provider to an existing user account

@@ -1,3 +0,3 @@

"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("jwt-decode"),l=require("xstate"),Y=require("js-cookie"),Ze=require("fetch-ponyfill"),v="nhostRefreshToken",b="nhostRefreshTokenId",P="nhostRefreshTokenExpiresAt",re=3,ne=60,W=5,X=0,Z=1,k=10,N=20;class O extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Z,message:e.message}):(this.name=e.error,this.error=e)}}const y={status:k,error:"invalid-email",message:"Email is incorrectly formatted"},se={status:k,error:"invalid-mfa-type",message:"MFA type is invalid"},te={status:k,error:"invalid-mfa-code",message:"MFA code is invalid"},K={status:k,error:"invalid-password",message:"Password is incorrectly formatted"},$={status:k,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},ie={status:k,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},oe={status:k,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},ae={status:k,error:"no-refresh-token",message:"No refresh token has been provided"},ce={status:N,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:N,error:"already-signed-in",message:"User is already signed in"},ue={status:N,error:"unauthenticated-user",message:"User is not authenticated"},Je={status:N,error:"user-not-anonymous",message:"User is not anonymous"},le={status:N,error:"unverified-user",message:"Email needs verification"},de={status:k,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},he={status:Z,error:"invalid-sign-in-method",message:"Invalid sign-in method"},M={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function er(s){return new TextEncoder().encode(s)}function A(s){const e=new Uint8Array(s);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function J(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4,r=e.padEnd(e.length+n,"="),t=atob(r),i=new ArrayBuffer(t.length),u=new Uint8Array(i);for(let m=0;m<t.length;m++)u[m]=t.charCodeAt(m);return i}function fe(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function Ee(s){const{id:e}=s;return{...s,id:J(e),transports:s.transports}}function me(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}class p extends Error{constructor({message:e,code:n,cause:r,name:t}){super(e,{cause:r}),this.name=t!=null?t:r.name,this.code=n}}function rr({error:s,options:e}){var r,t;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new p({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else if(s.name==="ConstraintError"){if(((r=n.authenticatorSelection)==null?void 0:r.requireResidentKey)===!0)return new p({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:s});if(((t=n.authenticatorSelection)==null?void 0:t.userVerification)==="required")return new p({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:s})}else{if(s.name==="InvalidStateError")return new p({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:s});if(s.name==="NotAllowedError")return new p({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="NotSupportedError")return n.pubKeyCredParams.filter(u=>u.type==="public-key").length===0?new p({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:s}):new p({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:s});if(s.name==="SecurityError"){const i=window.location.hostname;if(me(i)){if(n.rp.id!==i)return new p({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new p({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new p({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:s})}else if(s.name==="UnknownError")return new p({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return s}class nr{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ge=new nr,sr=["cross-platform","platform"];function Te(s){if(s&&!(sr.indexOf(s)<0))return s}async function pe(s){var o;if(!fe())throw new Error("WebAuthn is not supported in this browser");const n={publicKey:{...s,challenge:J(s.challenge),user:{...s.user,id:er(s.user.id)},excludeCredentials:(o=s.excludeCredentials)==null?void 0:o.map(Ee)}};n.signal=ge.createNewAbortSignal();let r;try{r=await navigator.credentials.create(n)}catch(c){throw rr({error:c,options:n})}if(!r)throw new Error("Registration was not completed");const{id:t,rawId:i,response:u,type:m}=r;let f;typeof u.getTransports=="function"&&(f=u.getTransports());let h;if(typeof u.getPublicKeyAlgorithm=="function")try{h=u.getPublicKeyAlgorithm()}catch(c){H("getPublicKeyAlgorithm()",c)}let E;if(typeof u.getPublicKey=="function")try{const c=u.getPublicKey();c!==null&&(E=A(c))}catch(c){H("getPublicKey()",c)}let a;if(typeof u.getAuthenticatorData=="function")try{a=A(u.getAuthenticatorData())}catch(c){H("getAuthenticatorData()",c)}return{id:t,rawId:A(i),response:{attestationObject:A(u.attestationObject),clientDataJSON:A(u.clientDataJSON),transports:f,publicKeyAlgorithm:h,publicKey:E,authenticatorData:a},type:m,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:Te(r.authenticatorAttachment)}}function H(s,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${s}. You should report this error to them.
`,e)}function tr(s){return new TextDecoder("utf-8").decode(s)}function ir(){const s=window.PublicKeyCredential;return s.isConditionalMediationAvailable===void 0?new Promise(e=>e(!1)):s.isConditionalMediationAvailable()}function or({error:s,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new p({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else{if(s.name==="NotAllowedError")return new p({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="SecurityError"){const r=window.location.hostname;if(me(r)){if(n.rpId!==r)return new p({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new p({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="UnknownError")return new p({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return s}async function F(s,e=!1){var a,o;if(!fe())throw new Error("WebAuthn is not supported in this browser");let n;((a=s.allowCredentials)==null?void 0:a.length)!==0&&(n=(o=s.allowCredentials)==null?void 0:o.map(Ee));const r={...s,challenge:J(s.challenge),allowCredentials:n},t={};if(e){if(!await ir())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');t.mediation="conditional",r.allowCredentials=[]}t.publicKey=r,t.signal=ge.createNewAbortSignal();let i;try{i=await navigator.credentials.get(t)}catch(c){throw or({error:c,options:t})}if(!i)throw new Error("Authentication was not completed");const{id:u,rawId:m,response:f,type:h}=i;let E;return f.userHandle&&(E=tr(f.userHandle)),{id:u,rawId:A(m),response:{authenticatorData:A(f.authenticatorData),clientDataJSON:A(f.clientDataJSON),signature:A(f.signature),userHandle:E},type:h,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:Te(i.authenticatorAttachment)}}const G=typeof window!="undefined",U=new Map,ar=s=>{var e;return G&&typeof localStorage!="undefined"?localStorage.getItem(s):(e=U.get(s))!=null?e:null},cr=(s,e)=>{G&&typeof localStorage!="undefined"?e?localStorage.setItem(s,e):localStorage.removeItem(s):e?U.set(s,e):U.has(s)&&U.delete(s)},we=(s,e)=>{if(s==="localStorage"||s==="web")return ar;if(s==="cookie")return n=>{var r;return G&&(r=Y.get(n))!=null?r:null};if(!e)throw Error(`clientStorageType is set to '${s}' but no clientStorage has been given`);if(s==="react-native")return n=>{var r;return(r=e.getItem)==null?void 0:r.call(e,n)};if(s==="capacitor")return n=>{var r;return(r=e.get)==null?void 0:r.call(e,{key:n})};if(s==="expo-secure-storage")return n=>{var r;return(r=e.getItemAsync)==null?void 0:r.call(e,n)};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}`)},Ie=(s,e)=>{if(s==="localStorage"||s==="web")return cr;if(s==="cookie")return(n,r)=>{G&&(r?Y.set(n,r,{expires:30,sameSite:"lax",httpOnly:!1}):Y.remove(n))};if(!e)throw Error(`clientStorageType is set to '${s}' but no clienStorage has been given`);if(s==="react-native")return(n,r)=>{var t,i;return r?(t=e.setItem)==null?void 0:t.call(e,n,r):(i=e.removeItem)==null?void 0:i.call(e,n)};if(s==="capacitor")return(n,r)=>{var t,i;return r?(t=e.set)==null?void 0:t.call(e,{key:n,value:r}):(i=e.remove)==null?void 0:i.call(e,{key:n})};if(s==="expo-secure-storage")return async(n,r)=>{var t,i;return r?(t=e.setItemAsync)==null?void 0:t.call(e,n,r):(i=e.deleteItemAsync)==null?void 0:i.call(e,n)};if(s==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(n,r)=>{var t,i;return r?(t=e.setItem)==null?void 0:t.call(e,n,r):(i=e.removeItem)==null?void 0:i.call(e,n)};if(e.setItemAsync)return async(n,r)=>{var t,i;return r?(t=e.setItemAsync)==null?void 0:t.call(e,n,r):(i=e.removeItem)==null?void 0:i.call(e,n)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${s}`)},C=s=>!s||!s.accessToken.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},_=({accessToken:s,refreshToken:e,isError:n,user:r,error:t})=>n?{session:null,error:t}:r&&s?{session:{accessToken:s,accessTokenExpiresIn:0,refreshToken:e,user:r},error:null}:{session:null,error:null},x=()=>typeof window!="undefined"&&typeof window.location!="undefined";let Re=globalThis.fetch;typeof EdgeRuntime!="string"&&(Re=Ze().fetch);const _e=async(s,e,{token:n,body:r,extraHeaders:t}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};n&&(i.Authorization=`Bearer ${n}`);const u={...i,...t},m={method:e,headers:u};r&&(m.body=JSON.stringify(r));try{const f=await Re(s,m);if(!f.ok){const h=await f.json();return Promise.reject({error:h})}try{return{data:await f.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:X,error:"network"};return Promise.reject({error:h})}},R=async(s,e,n,r)=>_e(s,"POST",{token:n,body:e,extraHeaders:r}),ye=(s,e)=>_e(s,"GET",{token:e}),V=(s,e)=>{const n=e&&Object.entries(e).map(([r,t])=>{const i=Array.isArray(t)?t.join(","):typeof t=="object"?JSON.stringify(t):t;return`${r}=${encodeURIComponent(i)}`}).join("&");return n?`${s}?${n}`:s},I=(s,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:n,...r}=e;if(!s)return n.startsWith("/")?r:e;const t=new URL(s),i=Object.fromEntries(new URLSearchParams(t.search)),u=new URL(n.startsWith("/")?t.origin+n:n),m=new URLSearchParams(u.search);let f=Object.fromEntries(m);n.startsWith("/")&&(f={...i,...f});let h=t.pathname;return u.pathname.length>1&&(h+=u.pathname.slice(1)),{...r,redirectTo:V(u.origin+h,f)}};function D(s,e){var t;if(!e){if(typeof window=="undefined")return;e=((t=window.location)==null?void 0:t.href)||""}s=s.replace(/[\[\]]/g,"\\$&");const n=new RegExp("[?&#]"+s+"(=([^&#]*)|&|#|$)"),r=n.exec(e);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}function j(s){var n;if(typeof window=="undefined")return;const e=window==null?void 0:window.location;if(e&&e){const r=new URLSearchParams(e.search),t=new URLSearchParams((n=e.hash)==null?void 0:n.slice(1));r.delete(s),t.delete(s);let i=window.location.pathname;Array.from(r).length&&(i+=`?${r.toString()}`),Array.from(t).length&&(i+=`#${t.toString()}`),window.history.pushState({},"",i)}}const S=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,q=s=>!!s&&typeof s=="string",Se=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),ke=({backendUrl:s,clientUrl:e,broadcastKey:n,clientStorageType:r="web",clientStorage:t,refreshIntervalTime:i,autoRefreshToken:u=!0,autoSignIn:m=!0})=>{const f=we(r,t),h=Ie(r,t),E=async(a,o,c,d)=>(await R(`${s}${a}`,o,c,d)).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:["clearContextExceptTokens"],exit:["destroyAccessToken","destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_SECURITY_KEY:"authenticating.securityKey",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat",SIGNIN_ID_TOKEN:"authenticating.idToken"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},idToken:{invoke:{src:"signInIdToken",id:"authenticateWithIdToken",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},securityKey:{invoke:{src:"signInSecurityKey",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{cond:"isUnauthorizedError",target:"#nhost.authentication.signedOut"},{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp",SIGNIN_EMAIL_OTP:"signInEmailOTP",VERIFY_EMAIL_OTP:"verifyEmailOTP"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},signInEmailOTP:{entry:["resetErrors"],invoke:{src:"signInEmailOTP",id:"signInEmailOTP",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},verifyEmailOTP:{entry:["resetErrors"],invoke:{src:"verifyEmailOTP",id:"verifyEmailOTP",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:l.send("SIGNED_IN"),reportSignedOut:l.send("SIGNED_OUT"),reportTokenChanged:l.send("TOKEN_CHANGED"),incrementTokenImportAttempts:l.assign({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:l.assign(()=>(h(P,null),h(v,null),h(b,null),{...M})),clearContextExceptTokens:l.assign(({accessToken:a,refreshToken:o})=>({...M,accessToken:a,refreshToken:o})),saveSession:l.assign({user:(a,{data:o})=>{var c;return((c=o==null?void 0:o.session)==null?void 0:c.user)||null},accessToken:(a,{data:o})=>{if(o.session){const{accessTokenExpiresIn:c,accessToken:d}=o.session,g=new Date(Date.now()+c*1e3);return h(P,g.toISOString()),{value:d,expiresAt:g,expiresInSeconds:c}}return h(P,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:o})=>{var g,T;const c=((g=o.session)==null?void 0:g.refreshToken)||null,d=((T=o.session)==null?void 0:T.refreshTokenId)||null;return c&&h(v,c),d&&h(b,d),{value:c}}}),savePATSession:l.assign({user:(a,{data:o})=>{var c;return((c=o==null?void 0:o.session)==null?void 0:c.user)||null},accessToken:(a,{data:o})=>{if(o.session){const{accessTokenExpiresIn:c,accessToken:d}=o.session,g=new Date(Date.now()+c*1e3);return h(P,g.toISOString()),{value:d,expiresAt:g,expiresInSeconds:c}}return h(P,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:o})=>{var g,T;const c=((g=o.session)==null?void 0:g.refreshToken)||null,d=((T=o.session)==null?void 0:T.refreshTokenId)||null;return c&&h(v,c),d&&h(b,d),{value:c,isPAT:!0}}}),saveMfaTicket:l.assign({mfa:(a,o)=>{var c;return(c=o.data)==null?void 0:c.mfa}}),resetTimer:l.assign({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:l.assign({refreshTimer:(a,o)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:l.assign({errors:({errors:a},{data:{error:o}})=>({...a,authentication:o})}),resetErrors:l.assign({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:l.assign({errors:({errors:a},{data:{error:o}})=>({...a,registration:o})}),destroyRefreshToken:l.assign({refreshToken:a=>(h(v,null),h(b,null),{value:null})}),destroyAccessToken:l.assign({accessToken:a=>(h(P,null),{value:null,expiresAt:null,expiresInSeconds:null})}),cleanUrl:()=>{m&&D("refreshToken")&&(j("refreshToken"),j("type"))},broadcastToken:a=>{if(m&&n)try{new BroadcastChannel(n).postMessage({type:"broadcast_token",payload:{token:a.refreshToken.value}})}catch{}}},guards:{isAnonymous:(a,o)=>{var c;return!!((c=a.user)!=null&&c.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var o;return!!((o=a.refreshToken)!=null&&o.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!u,refreshTimerShouldRefresh:a=>{const{expiresAt:o}=a.accessToken;if(!o)return!1;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>W?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(o.getTime()<Date.now()||i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const c=a.accessToken.expiresInSeconds;return c?o.getTime()-Date.now()-1e3*Math.min(ne,c*.5)<=0:!1},shouldRetryImportToken:(a,o)=>a.importTokenAttempts<W&&(o.data.error.status===X||o.data.error.status>=500),unverified:(a,{data:{error:o}})=>o.status===401&&(o.message==="Email is not verified"||o.error==="unverified-user"),hasSession:(a,o)=>{var c;return!!((c=o.data)!=null&&c.session)},hasMfaTicket:(a,o)=>{var c;return!!((c=o.data)!=null&&c.mfa)},isUnauthorizedError:(a,{data:{error:o}})=>o.status===401},services:{signInPassword:(a,{email:o,password:c})=>S(o)?L(c)?E("/signin/email-password",{email:o,password:c}):Promise.reject({error:K}):Promise.reject({error:y}),signInPAT:(a,{pat:o})=>E("/signin/pat",{personalAccessToken:o}),signInIdToken:(a,{provider:o,idToken:c,nonce:d})=>E("/signin/idtoken",{provider:o,idToken:c,...d&&{nonce:d}}),passwordlessSms:(a,{phoneNumber:o,options:c})=>{var d;return q(o)?(d=a.user)!=null&&d.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),E("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:o,options:I(e,c)},a.accessToken.value)):E("/signin/passwordless/sms",{phoneNumber:o,options:I(e,c)}):Promise.reject({error:$})},passwordlessSmsOtp:(a,{phoneNumber:o,otp:c})=>q(o)?E("/signin/passwordless/sms/otp",{phoneNumber:o,otp:c}):Promise.reject({error:$}),signInEmailOTP:(a,{email:o,options:c})=>S(o)?E("/signin/otp/email",{email:o,options:I(e,c)}):Promise.reject({error:y}),verifyEmailOTP:(a,{email:o,otp:c})=>S(o)?E("/signin/otp/email/verify",{email:o,otp:c}):Promise.reject({error:y}),passwordlessEmail:(a,{email:o,options:c})=>{var d;return S(o)?(d=a.user)!=null&&d.isAnonymous?E("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:o,options:I(e,c)},a.accessToken.value):E("/signin/passwordless/email",{email:o,options:I(e,c)}):Promise.reject({error:y})},signInAnonymous:a=>E("/signin/anonymous"),signInMfaTotp:(a,o)=>{var d;const c=o.ticket||((d=a.mfa)==null?void 0:d.ticket);return c?Se(c)?E("/signin/mfa/totp",{ticket:c,otp:o.otp}):Promise.reject({error:ie}):Promise.reject({error:oe})},signInSecurityKeyEmail:async(a,{email:o})=>{if(!S(o))throw new O(y);const c=await E("/signin/webauthn",{email:o});let d;try{d=await F(c)}catch(g){throw new O(g)}return E("/signin/webauthn/verify",{email:o,credential:d})},refreshToken:async(a,o)=>{const c=o.type==="TRY_TOKEN"?o.token:a.refreshToken.value;return{session:await E("/token",{refreshToken:c}),error:null}},signInSecurityKey:async()=>{try{const a=await E("/signin/webauthn",{});let o;try{o=await F(a)}catch(c){throw new O(c)}return E("/signin/webauthn/verify",{credential:o})}catch(a){throw new O(a)}},signout:async(a,o)=>{const c=await E("/signout",{refreshToken:a.refreshToken.value,all:!!o.all},o.all?a.accessToken.value:void 0);if(n)try{new BroadcastChannel(n).postMessage({type:"signout"})}catch{}return c},signUpEmailPassword:async(a,{email:o,password:c,options:d,requestOptions:g})=>{var T;return S(o)?L(c)?(T=a.user)!=null&&T.isAnonymous?E("/user/deanonymize",{signInMethod:"email-password",email:o,password:c,options:I(e,d)},a.accessToken.value,g==null?void 0:g.headers):E("/signup/email-password",{email:o,password:c,options:I(e,d)},null,g==null?void 0:g.headers):Promise.reject({error:K}):Promise.reject({error:y})},signUpSecurityKey:async(a,{email:o,options:c})=>{if(!S(o))return Promise.reject({error:y});const d=c==null?void 0:c.nickname;d&&delete c.nickname;const g=await E("/signup/webauthn",{email:o,options:c});let T;try{T=await pe(g)}catch(ze){throw new O(ze)}return E("/signup/webauthn/verify",{credential:T,options:{redirectTo:c==null?void 0:c.redirectTo,nickname:d}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let o=null;if(m){const d=D("refreshToken")||null;if(d)try{return{session:await E("/token",{refreshToken:d}),error:null}}catch(g){o=g.error}else{const g=D("error"),T=D("errorDescription");if(g&&T!=="social user already exists")return Promise.reject({session:null,error:{status:k,error:g,message:T||g}})}}const c=await f(v);if(c)try{return{session:await E("/token",{refreshToken:c}),error:null}}catch(d){o=d.error}return o?Promise.reject({error:o,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},Ae=({backendUrl:s,clientUrl:e,interpreter:n})=>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:t}})=>t}),reportError:l.send(r=>({type:"ERROR",error:r.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(r,{email:t})=>!S(t)},services:{requestChange:async(r,{email:t,options:i})=>(await R(`${s}/user/email/change`,{newEmail:t,options:I(e,i)},n==null?void 0:n.getSnapshot().context.accessToken.value)).data}}),Oe=({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:n=>K}),saveRequestError:l.assign({error:(n,{data:{error:r}})=>r}),reportError:l.send(n=>({type:"ERROR",error:n.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidPassword:(n,{password:r})=>!L(r)},services:{requestChange:(n,{password:r,ticket:t})=>R(`${s}/user/password`,{newPassword:r,ticket:t},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ur=({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:n=>se}),saveInvalidMfaCodeError:l.assign({error:n=>te}),saveError:l.assign({error:(n,{data:{error:r}})=>r}),saveGeneration:l.assign({imageUrl:(n,{data:{imageUrl:r}})=>r,secret:(n,{data:{totpSecret:r}})=>r}),reportError:l.send((n,r)=>(console.log("REPORT",n,r),{type:"ERROR",error:n.error})),reportSuccess:l.send("SUCCESS"),reportGeneratedSuccess:l.send("GENERATED"),reportGeneratedError:l.send(n=>({type:"GENERATED_ERROR",error:n.error}))},guards:{invalidMfaCode:(n,{code:r})=>!r,invalidMfaType:(n,{activeMfaType:r})=>!r||r!=="totp"},services:{generate:async n=>{const{data:r}=await ye(`${s}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return r},activate:(n,{code:r,activeMfaType:t})=>R(`${s}/user/mfa`,{code:r,activeMfaType:t},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),Pe=({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:n=>y}),saveRequestError:l.assign({error:(n,{data:{error:r}})=>r}),reportError:l.send(n=>({type:"ERROR",error:n.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(n,{email:r})=>!S(r)},services:{requestChange:(n,{email:r,options:t})=>R(`${s}/user/password/reset`,{email:r,options:I(e,t)})}}),ve=({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:n=>y}),saveRequestError:l.assign({error:(n,{data:{error:r}})=>r}),reportError:l.send(n=>({type:"ERROR",error:n.error})),reportSuccess:l.send("SUCCESS")},guards:{invalidEmail:(n,{email:r})=>!S(r)},services:{request:async(n,{email:r,options:t})=>(await R(`${s}/user/email/send-verification-email`,{email:r,options:I(e,t)})).data}});class ee{constructor({clientStorageType:e="web",autoSignIn:n=!0,autoRefreshToken:r=!0,start:t=!0,backendUrl:i,clientUrl:u,broadcastKey:m,devTools:f,...h}){var E;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=i,this.clientUrl=u,this._machine=ke({...h,backendUrl:i,clientUrl:u,broadcastKey:m,clientStorageType:e,autoSignIn:n,autoRefreshToken:r}),t&&this.start({devTools:f}),typeof window!="undefined"&&m)try{this._channel=new BroadcastChannel(m),n&&((E=this._channel)==null||E.addEventListener("message",a=>{var d;const{type:o,payload:c}=a.data;if(o==="broadcast_token"){const g=(d=this.interpreter)==null?void 0:d.getSnapshot().context.refreshToken.value;this.interpreter&&c.token&&c.token!==g&&this.interpreter.send("TRY_TOKEN",{token:c.token})}})),this._channel.addEventListener("message",a=>{const{type:o}=a.data;o==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:n,interpreter:r}={}){var u,m;const t={...this.machine.context,accessToken:{...this.machine.context.accessToken},refreshToken:{...this.machine.context.refreshToken}};n&&(t.user=n.user,t.refreshToken.value=(u=n.refreshToken)!=null?u:null,t.accessToken.value=(m=n.accessToken)!=null?m:null,t.accessToken.expiresAt=new Date(Date.now()+n.accessTokenExpiresIn*1e3));const i=this.machine.withContext(t);this._interpreter||(this._interpreter=r||l.interpret(i,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(f=>f())),this._interpreter.start(i.initialState),this._subscriptionsQueue.forEach(f=>f(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 n=e(this);return this._subscriptions.add(n),n}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class Ne extends ee{constructor({...e}){super({...e,autoSignIn:x()&&e.autoSignIn,autoRefreshToken:x()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const lr=Ne,be=async({backendUrl:s,interpreter:e},n)=>{try{const{data:r}=await R(`${s}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let t;try{t=await pe(r)}catch(u){throw new O(u)}const{data:i}=await R(`${s}/user/webauthn/verify`,{credential:t,nickname:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:i,isError:!1,error:null,isSuccess:!0}}catch(r){const{error:t}=r;return{isError:!0,error:t,isSuccess:!1}}},Ce=async(s,e,n)=>new Promise(r=>{s.send("REQUEST",{email:e,options:n}),s.onTransition(t=>{t.matches({idle:"error"})?r({error:t.context.error,isError:!0,needsEmailVerification:!1}):t.matches({idle:"success"})&&r({error:null,isError:!1,needsEmailVerification:!0})})}),De=async(s,e,n)=>new Promise(r=>{s.send("REQUEST",{password:e,ticket:n}),s.onTransition(t=>{t.matches({idle:"error"})?r({error:t.context.error,isError:!0,isSuccess:!1}):t.matches({idle:"success"})&&r({error:null,isError:!1,isSuccess:!0})})}),dr=s=>new Promise(e=>{s.send("GENERATE"),s.onTransition(n=>{n.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:n.context.imageUrl||""}):n.matches({idle:"error"})&&e({error:n.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),hr=(s,e)=>new Promise(n=>{s.send("ACTIVATE",{activeMfaType:"totp",code:e}),s.onTransition(r=>{r.matches({generated:"activated"})?n({error:null,isActivated:!0,isError:!1}):r.matches({generated:{idle:"error"}})&&n({error:r.context.error,isActivated:!1,isError:!0})})}),xe=async(s,e,n)=>new Promise(r=>{s.send("REQUEST",{email:e,options:n}),s.onTransition(t=>{t.matches({idle:"error"})?r({error:t.context.error,isError:!0,isSent:!1}):t.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),Me=(s,e,n)=>new Promise(r=>{s.send("REQUEST",{email:e,options:n}),s.onTransition(t=>{t.matches({idle:"error"})?r({error:t.context.error,isError:!0,isSent:!1}):t.matches({idle:"success"})&&r({error:null,isError:!1,isSent:!0})})}),Ue=s=>new Promise(e=>{const{changed:n}=s.send("SIGNIN_ANONYMOUS");n||e({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(r=>{r.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:r.context.user,accessToken:r.context.accessToken.value,refreshToken:r.context.refreshToken.value}),r.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:r.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),Ke=(s,e,n)=>new Promise(r=>{const{changed:t,context:i}=s.send("SIGNIN_PASSWORD",{email:e,password:n});if(!t)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:i.user});s.onTransition(u=>{u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):u.matches({authentication:{signedOut:"needsMfa"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:u.context.mfa,user:null}):u.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:u.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):u.matches({authentication:"signedIn"})&&r({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:u.context.user})})}),B=(s,e,n)=>new Promise(r=>{const{changed:t}=s.send("PASSWORDLESS_EMAIL",{email:e,options:n});if(!t)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})})}),Ve=(s,e)=>new Promise(n=>{const{changed:r,context:t}=s.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!r)return n({accessToken:t.accessToken.value,refreshToken:t.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:t.user});s.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&n({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),Le=(s,e)=>new Promise(async n=>{var m,f;const r=(m=s.interpreter)==null?void 0:m.getSnapshot(),t=r==null?void 0:r.context.accessToken.value,{data:i}=await R(`${s.backendUrl}/elevate/webauthn`,{email:e},t);let u;try{u=await F(i)}catch(h){throw new O(h)}try{const{data:{session:h},error:E}=await R(`${s.backendUrl}/elevate/webauthn/verify`,{email:e,credential:u},t);h&&!E&&((f=s.interpreter)==null||f.send({type:"SESSION_UPDATE",data:{session:h}}),n({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(h){const{error:E}=h;n({error:E,isError:!0,isSuccess:!1,elevated:!1})}}),Ge=(s,e,n)=>new Promise(r=>{const{changed:t,context:i}=s.send("SIGNIN_MFA_TOTP",{otp:e,ticket:n});if(!t)return r({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:w,isError:!0,isSuccess:!1,user:i.user});s.onTransition(u=>{u.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:u.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):u.matches({authentication:"signedIn"})&&r({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:u.context.user})})}),He=(s,e)=>new Promise(n=>{const{changed:r}=s.send("SIGNIN_PAT",{pat:e});r||n({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(t=>{if(t.matches({authentication:{signedOut:"failed"}}))return n({accessToken:null,refreshToken:null,user:null,error:t.context.errors.authentication||null,isError:!0,isSuccess:!1});if(t.matches({authentication:"signedIn"}))return n({accessToken:t.context.accessToken.value,refreshToken:t.context.refreshToken.value,user:t.context.user,error:null,isError:!1,isSuccess:!0})})}),Q=(s,e,n)=>new Promise(r=>{const{changed:t}=s.send("PASSWORDLESS_SMS",{phoneNumber:e,options:n});if(!t)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})})}),Ye=(s,e,n)=>new Promise(r=>{const{changed:t}=s.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:n});if(!t)return r({error:w,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?r({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value}):i.matches({registration:{incomplete:"failed"}})&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),We=async(s,e)=>new Promise(n=>{const{event:r}=s.send("SIGNOUT",{all:e});if(r.type!=="SIGNED_OUT")return n({isSuccess:!1,isError:!0,error:ue});s.onTransition(t=>{t.matches({authentication:{signedOut:"success"}})?n({isSuccess:!0,isError:!1,error:null}):t.matches("authentication.signedOut.failed")&&n({isSuccess:!1,isError:!0,error:t.context.errors.signout||null})})}),z=(s,e,n,r,t)=>new Promise(i=>{const{changed:u,context:m}=s.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:n,options:r,requestOptions:t});if(!u)return i({error:w,accessToken:m.accessToken.value,refreshToken:m.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:m.user});s.onTransition(f=>{f.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:f.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):f.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):f.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:f.context.accessToken.value,refreshToken:f.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:f.context.user})})}),$e=(s,e,n)=>new Promise(r=>{const{changed:t,context:i}=s.send("SIGNUP_SECURITY_KEY",{email:e,options:n});if(!t)return r({error:w,accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:i.user});s.onTransition(u=>{u.matches("registration.incomplete.failed")?r({accessToken:null,refreshToken:null,error:u.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):u.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):u.matches({authentication:"signedIn",registration:"complete"})&&r({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:u.context.user})})}),Fe=(s,e,n)=>new Promise(r=>{const{changed:t}=s.send("SIGNIN_EMAIL_OTP",{email:e,options:n});if(!t)return r({error:w,isError:!0,isSuccess:!1,needsOtp:!1});s.onTransition(i=>{i.matches("registration.incomplete.needsOtp")?r({error:null,isError:!1,isSuccess:!0,needsOtp:!0}):i.matches("registration.incomplete.failed")&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),je=(s,e,n)=>new Promise(r=>{const{changed:t}=s.send({type:"VERIFY_EMAIL_OTP",email:e,otp:n});if(!t)return r({error:w,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?r({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value}):i.matches({registration:{incomplete:"failed"}})&&r({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),qe=(s,{provider:e,idToken:n,nonce:r})=>new Promise(t=>{const{changed:i}=s.send("SIGNIN_ID_TOKEN",{provider:e,idToken:n,...r&&{nonce:r}});i||t({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(u=>{if(u.matches({authentication:{signedOut:"failed"}}))return t({accessToken:null,refreshToken:null,user:null,error:u.context.errors.authentication||null,isError:!0,isSuccess:!1});if(u.matches({authentication:"signedIn"}))return t({accessToken:u.context.accessToken.value,refreshToken:u.context.refreshToken.value,user:u.context.user,error:null,isError:!1,isSuccess:!0})})}),Be=async({backendUrl:s,interpreter:e},{provider:n,idToken:r,nonce:t})=>{try{return await R(`${s}/link/idtoken`,{provider:n,idToken:r,...t&&{nonce:t}},e==null?void 0:e.getSnapshot().context.accessToken.value),{isError:!1,error:null,isSuccess:!0}}catch(i){const{error:u}=i;return{isError:!0,error:u,isSuccess:!1}}},Qe=s=>new Promise(e=>{const{changed:n,context:r}=s.send({type:"SIGNIN_SECURITY_KEY"});if(!n)return e({accessToken:r.accessToken.value,refreshToken:r.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:r.user});s.onTransition(t=>{t.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?e({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):t.matches({authentication:{signedOut:"failed"}})?e({accessToken:null,refreshToken:null,error:t.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):t.matches({authentication:"signedIn"})&&e({accessToken:t.context.accessToken.value,refreshToken:t.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:t.context.user})})}),fr=async({backendUrl:s,interpreter:e},{expiresAt:n,metadata:r})=>{try{const{data:t}=await R(`${s}/pat`,{expiresAt:n.toISOString(),metadata:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:t?{id:t.id||null,personalAccessToken:t.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(t){const{error:i}=t;return{isError:!0,error:i,isSuccess:!1,data:null}}};class Er{constructor({url:e,broadcastKey:n,autoRefreshToken:r=!0,autoSignIn:t=!0,clientStorage:i,clientStorageType:u,refreshIntervalTime:m,start:f=!0}){var h;this.url=e,this._client=new ee({backendUrl:e,clientUrl:typeof window!="undefined"&&((h=window.location)==null?void 0:h.origin)||"",broadcastKey:n,autoRefreshToken:r,autoSignIn:t,start:f,clientStorage:i,clientStorageType:u,refreshIntervalTime:m})}async signUp(e){const n=await this.waitUntilReady(),{email:r,options:t}=e;return"securityKey"in e?_(await $e(n,r,t)):_(await z(n,r,e.password,t))}async connectProvider(e){const r=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:t,options:i}=e,u=V(`${this._client.backendUrl}/signin/provider/${t}`,I(this._client.clientUrl,{...i,connect:r}));return x()&&(window.location.href=u),{providerUrl:u}}async signInIdToken(e){const n=await this.waitUntilReady(),r=await qe(n,e);return{..._(r),mfa:null}}async linkIdToken(e){return Be(this._client,e)}async signIn(e){const n=await this.waitUntilReady();if(!e){const r=await Ue(n);return{..._(r),mfa:null}}if("provider"in e){const{provider:r,options:t}=e,i=V(`${this._client.backendUrl}/signin/provider/${r}`,I(this._client.clientUrl,t));return x()&&(window.location.href=i),{providerUrl:i,provider:r,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const r=await Ke(n,e.email,e.password);return r.needsEmailVerification?{session:null,mfa:null,error:le}:r.needsMfaOtp?{session:null,mfa:r.mfa,error:null}:{..._(r),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const r=await Ve(n,e.email);return{..._(r),mfa:null}}if("email"in e){const{email:r,options:t}=e,{error:i}=await B(n,r,t);return{session:null,mfa:null,error:i}}if("phoneNumber"in e&&"otp"in e){const r=await Ye(n,e.phoneNumber,e.otp);return{..._(r),mfa:null}}if("phoneNumber"in e){const{error:r}=await Q(n,e.phoneNumber,e.options);return{error:r,mfa:null,session:null}}if("otp"in e){const r=await Ge(n,e.otp,e.ticket);return{..._(r),mfa:null}}return{error:he,mfa:null,session:null}}async signInPAT(e){const n=await this.waitUntilReady(),r=await He(n,e);return _(r)}async signInEmailOTP(e,n){const r=await this.waitUntilReady(),{error:t}=await Fe(r,e,n);return{error:t,session:null,mfa:null}}async verifyEmailOTP(e,n){const r=await this.waitUntilReady(),t=await je(r,e,n);return{..._(t),mfa:null}}async signInSecurityKey(){const e=await this.waitUntilReady(),n=await Qe(e);return{..._(n),mfa:null}}async signOut(e){const n=await this.waitUntilReady(),{error:r}=await We(n,e==null?void 0:e.all);return{error:r}}async resetPassword({email:e,options:n}){const r=l.interpret(Pe(this._client)).start(),{error:t}=await xe(r,e,n);return{error:t}}async changePassword({newPassword:e,ticket:n}){const r=l.interpret(Oe(this._client)).start(),{error:t}=await De(r,e,n);return{error:t}}async sendVerificationEmail({email:e,options:n}){const r=l.interpret(ve(this._client)).start(),{error:t}=await Me(r,e,n);return{error:t}}async changeEmail({newEmail:e,options:n}){const r=l.interpret(Ae(this._client)).start(),{error:t}=await Ce(r,e,n);return{error:t}}async deanonymize(e){const n=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:r}=await B(n,e.email,e.options);return{error:r}}if(e.connection==="sms"){const{error:r}=await Q(n,e.phoneNumber,e.options);return{error:r}}}if(e.signInMethod==="email-password"){const{error:r}=await z(n,e.email,e.password,e.options);return{error:r}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:n,key:r}=await be(this._client,e);return{error:n,key:r}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Le(this._client,e),mfa:null}}async createPAT(e,n){return fr(this._client,{expiresAt:e,metadata:n})}onTokenChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:t,context:i})=>{t.type==="TOKEN_CHANGED"&&e(C(i))});return()=>n==null?void 0:n.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var r;const n=(r=this._client.interpreter)==null?void 0:r.onTransition(({event:t,context:i})=>{(t.type==="SIGNED_IN"||t.type==="SIGNED_OUT")&&e(t.type,C(i))});return()=>n==null?void 0:n.stop()})}isAuthenticated(){var e;return!!((e=this._client.interpreter)!=null&&e.getSnapshot().matches({authentication:"signedIn"}))}async isAuthenticatedAsync(){return(await this.waitUntilReady()).getSnapshot().matches({authentication:"signedIn"})}getAuthenticationStatus(){var n;const e=((n=this.client.interpreter)==null?void 0:n.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:e}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:e}}getAccessToken(){var e,n;return(n=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?n:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Xe.jwtDecode(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var n;return((n=this.getHasuraClaims())==null?void 0:n[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const n=await this.waitUntilReady();return new Promise(r=>{const t=e||n.getSnapshot().context.refreshToken.value;if(!t)return r({session:null,error:ae});const{changed:i}=n.send("TRY_TOKEN",{token:t});if(!i)return r({session:null,error:ce});n.onTransition(u=>{u.matches({token:{idle:"error"}})?r({session:null,error:de}):u.event.type==="TOKEN_CHANGED"&&r({session:C(u.context),error:null})})})}catch(n){return{session:null,error:n.message}}}getSession(){var e,n;return C((n=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:n.context)}async initWithSession({session:e}){this.client.start({initialSession:e}),await this.waitUntilReady()}getUser(){var e,n,r;return((r=(n=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:n.context)==null?void 0:r.user)||null}waitUntilReady(){const n=this._client.interpreter;if(!n)throw Error("Auth interpreter not set");return n.getSnapshot().hasTag("loading")?new Promise((r,t)=>{let i=setTimeout(()=>t("The state machine is not yet ready after 15 seconds."),15e3);n.onTransition(u=>{if(!u.hasTag("loading"))return clearTimeout(i),r(n)})}):Promise.resolve(n)}isReady(){var e,n;return!((n=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&n.hasTag("loading"))}get client(){return this._client}}exports.AuthClient=ee;exports.AuthClientSSR=lr;exports.AuthCookieClient=Ne;exports.CodifiedError=O;exports.EMAIL_NEEDS_VERIFICATION=le;exports.HasuraAuthClient=Er;exports.INITIAL_MACHINE_CONTEXT=M;exports.INVALID_EMAIL_ERROR=y;exports.INVALID_MFA_CODE_ERROR=te;exports.INVALID_MFA_TICKET_ERROR=ie;exports.INVALID_MFA_TYPE_ERROR=se;exports.INVALID_PASSWORD_ERROR=K;exports.INVALID_PHONE_NUMBER_ERROR=$;exports.INVALID_REFRESH_TOKEN=de;exports.INVALID_SIGN_IN_METHOD=he;exports.MIN_PASSWORD_LENGTH=re;exports.NETWORK_ERROR_CODE=X;exports.NHOST_JWT_EXPIRES_AT_KEY=P;exports.NHOST_REFRESH_TOKEN_ID_KEY=b;exports.NHOST_REFRESH_TOKEN_KEY=v;exports.NO_MFA_TICKET_ERROR=oe;exports.NO_REFRESH_TOKEN=ae;exports.OTHER_ERROR_CODE=Z;exports.REFRESH_TOKEN_MAX_ATTEMPTS=W;exports.STATE_ERROR_CODE=N;exports.TOKEN_REFRESHER_RUNNING_ERROR=ce;exports.TOKEN_REFRESH_MARGIN_SECONDS=ne;exports.USER_ALREADY_SIGNED_IN=w;exports.USER_NOT_ANONYMOUS=Je;exports.USER_UNAUTHENTICATED=ue;exports.VALIDATION_ERROR_CODE=k;exports.activateMfaPromise=hr;exports.addSecurityKeyPromise=be;exports.changeEmailPromise=Ce;exports.changePasswordPromise=De;exports.createAuthMachine=ke;exports.createChangeEmailMachine=Ae;exports.createChangePasswordMachine=Oe;exports.createEnableMfaMachine=ur;exports.createResetPasswordMachine=Pe;exports.createSendVerificationEmailMachine=ve;exports.elevateEmailSecurityKeyPromise=Le;exports.encodeQueryParameters=V;exports.generateQrCodePromise=dr;exports.getAuthenticationResult=_;exports.getFetch=ye;exports.getParameterByName=D;exports.getSession=C;exports.isBrowser=x;exports.isValidEmail=S;exports.isValidPassword=L;exports.isValidPhoneNumber=q;exports.isValidTicket=Se;exports.linkIdTokenPromise=Be;exports.localStorageGetter=we;exports.localStorageSetter=Ie;exports.postFetch=R;exports.removeParameterFromWindow=j;exports.resetPasswordPromise=xe;exports.rewriteRedirectTo=I;exports.sendVerificationEmailPromise=Me;exports.signInAnonymousPromise=Ue;exports.signInEmailOTPPromise=Fe;exports.signInEmailPasswordPromise=Ke;exports.signInEmailPasswordlessPromise=B;exports.signInEmailSecurityKeyPromise=Ve;exports.signInIdTokenPromise=qe;exports.signInMfaTotpPromise=Ge;exports.signInPATPromise=He;exports.signInSecurityKeyPromise=Qe;exports.signInSmsPasswordlessOtpPromise=Ye;exports.signInSmsPasswordlessPromise=Q;exports.signOutPromise=We;exports.signUpEmailPasswordPromise=z;exports.signUpEmailSecurityKeyPromise=$e;exports.verifyEmailOTPPromise=je;
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ze=require("jwt-decode"),u=require("xstate"),Y=require("js-cookie"),Je=require("fetch-ponyfill"),v="nhostRefreshToken",b="nhostRefreshTokenId",P="nhostRefreshTokenExpiresAt",ne=3,se=60,W=5,X=0,Z=1,k=10,N=20;class O extends Error{constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),e instanceof Error?(this.name=e.name,this.error={error:e.name,status:Z,message:e.message}):(this.name=e.error,this.error=e)}}const y={status:k,error:"invalid-email",message:"Email is incorrectly formatted"},te={status:k,error:"invalid-mfa-type",message:"MFA type is invalid"},ie={status:k,error:"invalid-mfa-code",message:"MFA code is invalid"},K={status:k,error:"invalid-password",message:"Password is incorrectly formatted"},$={status:k,error:"invalid-phone-number",message:"Phone number is incorrectly formatted"},oe={status:k,error:"invalid-mfa-ticket",message:"MFA ticket is invalid"},ae={status:k,error:"no-mfa-ticket",message:"No MFA ticket has been provided"},ce={status:k,error:"no-refresh-token",message:"No refresh token has been provided"},le={status:N,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:N,error:"already-signed-in",message:"User is already signed in"},ue={status:N,error:"unauthenticated-user",message:"User is not authenticated"},er={status:N,error:"user-not-anonymous",message:"User is not anonymous"},de={status:N,error:"unverified-user",message:"Email needs verification"},he={status:k,error:"invalid-refresh-token",message:"Invalid or expired refresh token"},fe={status:Z,error:"invalid-sign-in-method",message:"Invalid sign-in method"},M={user:null,mfa:null,accessToken:{value:null,expiresAt:null,expiresInSeconds:15},refreshTimer:{startedAt:null,attempts:0,lastAttempt:null},refreshToken:{value:null},importTokenAttempts:0,errors:{}};function rr(s){return new TextEncoder().encode(s)}function A(s){const e=new Uint8Array(s);let r="";for(const t of e)r+=String.fromCharCode(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function J(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4,n=e.padEnd(e.length+r,"="),t=atob(n),i=new ArrayBuffer(t.length),l=new Uint8Array(i);for(let h=0;h<t.length;h++)l[h]=t.charCodeAt(h);return i}function Ee(){return(window==null?void 0:window.PublicKeyCredential)!==void 0&&typeof window.PublicKeyCredential=="function"}function me(s){const{id:e}=s;return{...s,id:J(e),transports:s.transports}}function ge(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}class T extends Error{constructor({message:e,code:r,cause:n,name:t}){super(e,{cause:n}),this.name=t!=null?t:n.name,this.code=r}}function nr({error:s,options:e}){var n,t;const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new T({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else if(s.name==="ConstraintError"){if(((n=r.authenticatorSelection)==null?void 0:n.requireResidentKey)===!0)return new T({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:s});if(((t=r.authenticatorSelection)==null?void 0:t.userVerification)==="required")return new T({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:s})}else{if(s.name==="InvalidStateError")return new T({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:s});if(s.name==="NotAllowedError")return new T({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="NotSupportedError")return r.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new T({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:s}):new T({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:s});if(s.name==="SecurityError"){const i=window.location.hostname;if(ge(i)){if(r.rp.id!==i)return new T({message:`The RP ID "${r.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new T({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="TypeError"){if(r.user.id.byteLength<1||r.user.id.byteLength>64)return new T({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:s})}else if(s.name==="UnknownError")return new T({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return s}class sr{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Te=new sr,tr=["cross-platform","platform"];function pe(s){if(s&&!(tr.indexOf(s)<0))return s}async function we(s){var o;if(!Ee())throw new Error("WebAuthn is not supported in this browser");const r={publicKey:{...s,challenge:J(s.challenge),user:{...s.user,id:rr(s.user.id)},excludeCredentials:(o=s.excludeCredentials)==null?void 0:o.map(me)}};r.signal=Te.createNewAbortSignal();let n;try{n=await navigator.credentials.create(r)}catch(c){throw nr({error:c,options:r})}if(!n)throw new Error("Registration was not completed");const{id:t,rawId:i,response:l,type:h}=n;let f;typeof l.getTransports=="function"&&(f=l.getTransports());let E;if(typeof l.getPublicKeyAlgorithm=="function")try{E=l.getPublicKeyAlgorithm()}catch(c){H("getPublicKeyAlgorithm()",c)}let m;if(typeof l.getPublicKey=="function")try{const c=l.getPublicKey();c!==null&&(m=A(c))}catch(c){H("getPublicKey()",c)}let a;if(typeof l.getAuthenticatorData=="function")try{a=A(l.getAuthenticatorData())}catch(c){H("getAuthenticatorData()",c)}return{id:t,rawId:A(i),response:{attestationObject:A(l.attestationObject),clientDataJSON:A(l.clientDataJSON),transports:f,publicKeyAlgorithm:E,publicKey:m,authenticatorData:a},type:h,clientExtensionResults:n.getClientExtensionResults(),authenticatorAttachment:pe(n.authenticatorAttachment)}}function H(s,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${s}. You should report this error to them.
`,e)}function ir(s){return new TextDecoder("utf-8").decode(s)}function or(){const s=window.PublicKeyCredential;return s.isConditionalMediationAvailable===void 0?new Promise(e=>e(!1)):s.isConditionalMediationAvailable()}function ar({error:s,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new T({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else{if(s.name==="NotAllowedError")return new T({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="SecurityError"){const n=window.location.hostname;if(ge(n)){if(r.rpId!==n)return new T({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new T({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="UnknownError")return new T({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return s}async function F(s,e=!1){var a,o;if(!Ee())throw new Error("WebAuthn is not supported in this browser");let r;((a=s.allowCredentials)==null?void 0:a.length)!==0&&(r=(o=s.allowCredentials)==null?void 0:o.map(me));const n={...s,challenge:J(s.challenge),allowCredentials:r},t={};if(e){if(!await or())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');t.mediation="conditional",n.allowCredentials=[]}t.publicKey=n,t.signal=Te.createNewAbortSignal();let i;try{i=await navigator.credentials.get(t)}catch(c){throw ar({error:c,options:t})}if(!i)throw new Error("Authentication was not completed");const{id:l,rawId:h,response:f,type:E}=i;let m;return f.userHandle&&(m=ir(f.userHandle)),{id:l,rawId:A(h),response:{authenticatorData:A(f.authenticatorData),clientDataJSON:A(f.clientDataJSON),signature:A(f.signature),userHandle:m},type:E,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:pe(i.authenticatorAttachment)}}const G=typeof window!="undefined",U=new Map,cr=s=>{var e;return G&&typeof localStorage!="undefined"?localStorage.getItem(s):(e=U.get(s))!=null?e:null},lr=(s,e)=>{G&&typeof localStorage!="undefined"?e?localStorage.setItem(s,e):localStorage.removeItem(s):e?U.set(s,e):U.has(s)&&U.delete(s)},Ie=(s,e)=>{if(s==="localStorage"||s==="web")return cr;if(s==="cookie")return r=>{var n;return G&&(n=Y.get(r))!=null?n:null};if(!e)throw Error(`clientStorageType is set to '${s}' but no clientStorage has been given`);if(s==="react-native")return r=>{var n;return(n=e.getItem)==null?void 0:n.call(e,r)};if(s==="capacitor")return r=>{var n;return(n=e.get)==null?void 0:n.call(e,{key:r})};if(s==="expo-secure-storage")return r=>{var n;return(n=e.getItemAsync)==null?void 0:n.call(e,r)};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}`)},Re=(s,e)=>{if(s==="localStorage"||s==="web")return lr;if(s==="cookie")return(r,n)=>{G&&(n?Y.set(r,n,{expires:30,sameSite:"lax",httpOnly:!1}):Y.remove(r))};if(!e)throw Error(`clientStorageType is set to '${s}' but no clienStorage has been given`);if(s==="react-native")return(r,n)=>{var t,i;return n?(t=e.setItem)==null?void 0:t.call(e,r,n):(i=e.removeItem)==null?void 0:i.call(e,r)};if(s==="capacitor")return(r,n)=>{var t,i;return n?(t=e.set)==null?void 0:t.call(e,{key:r,value:n}):(i=e.remove)==null?void 0:i.call(e,{key:r})};if(s==="expo-secure-storage")return async(r,n)=>{var t,i;return n?(t=e.setItemAsync)==null?void 0:t.call(e,r,n):(i=e.deleteItemAsync)==null?void 0:i.call(e,r)};if(s==="custom"){if(!e.removeItem)throw Error("clientStorageType is set to 'custom' but clientStorage is missing a removeItem property");if(e.setItem)return(r,n)=>{var t,i;return n?(t=e.setItem)==null?void 0:t.call(e,r,n):(i=e.removeItem)==null?void 0:i.call(e,r)};if(e.setItemAsync)return async(r,n)=>{var t,i;return n?(t=e.setItemAsync)==null?void 0:t.call(e,r,n):(i=e.removeItem)==null?void 0:i.call(e,r)};throw Error("clientStorageType is set to 'custom' but clientStorage is missing setItem or setItemAsync property")}throw Error(`Unknown storage type: ${s}`)},C=s=>!s||!s.accessToken.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},_=({accessToken:s,refreshToken:e,isError:r,user:n,error:t})=>r?{session:null,error:t}:n&&s?{session:{accessToken:s,accessTokenExpiresIn:0,refreshToken:e,user:n},error:null}:{session:null,error:null},x=()=>typeof window!="undefined"&&typeof window.location!="undefined";let _e=globalThis.fetch;typeof EdgeRuntime!="string"&&(_e=Je().fetch);const ye=async(s,e,{token:r,body:n,extraHeaders:t}={})=>{const i={"Content-Type":"application/json",Accept:"*/*"};r&&(i.Authorization=`Bearer ${r}`);const l={...i,...t},h={method:e,headers:l};n&&(h.body=JSON.stringify(n));try{const f=await _e(s,h);if(!f.ok){const E=await f.json();return Promise.reject({error:E})}try{return{data:await f.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 E={message:"Network Error",status:X,error:"network"};return Promise.reject({error:E})}},R=async(s,e,r,n)=>ye(s,"POST",{token:r,body:e,extraHeaders:n}),Se=(s,e)=>ye(s,"GET",{token:e}),V=(s,e)=>{const r=e&&Object.entries(e).map(([n,t])=>{const i=Array.isArray(t)?t.join(","):typeof t=="object"?JSON.stringify(t):t;return`${n}=${encodeURIComponent(i)}`}).join("&");return r?`${s}?${r}`:s},I=(s,e)=>{if(!(e!=null&&e.redirectTo))return e;const{redirectTo:r,...n}=e;if(!s)return r.startsWith("/")?n:e;const t=new URL(s),i=Object.fromEntries(new URLSearchParams(t.search)),l=new URL(r.startsWith("/")?t.origin+r:r),h=new URLSearchParams(l.search);let f=Object.fromEntries(h);r.startsWith("/")&&(f={...i,...f});let E=t.pathname;return l.pathname.length>1&&(E+=l.pathname.slice(1)),{...n,redirectTo:V(l.origin+E,f)}};function D(s,e){var t;if(!e){if(typeof window=="undefined")return;e=((t=window.location)==null?void 0:t.href)||""}s=s.replace(/[\[\]]/g,"\\$&");const r=new RegExp("[?&#]"+s+"(=([^&#]*)|&|#|$)"),n=r.exec(e);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}function j(s){var r;if(typeof window=="undefined")return;const e=window==null?void 0:window.location;if(e&&e){const n=new URLSearchParams(e.search),t=new URLSearchParams((r=e.hash)==null?void 0:r.slice(1));n.delete(s),t.delete(s);let i=window.location.pathname;Array.from(n).length&&(i+=`?${n.toString()}`),Array.from(t).length&&(i+=`#${t.toString()}`),window.history.pushState({},"",i)}}const S=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>=ne,q=s=>!!s&&typeof s=="string",ke=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),Ae=({backendUrl:s,clientUrl:e,broadcastKey:r,clientStorageType:n="web",clientStorage:t,refreshIntervalTime:i,autoRefreshToken:l=!0,autoSignIn:h=!0})=>{const f=Ie(n,t),E=Re(n,t),m=async(a,o,c,d)=>(await R(`${s}${a}`,o,c,d)).data;return u.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:["clearContextExceptTokens"],exit:["destroyAccessToken","destroyRefreshToken","reportTokenChanged"],invoke:{src:"signout",id:"signingOut",onDone:{target:"success"},onError:{target:"failed",actions:["saveAuthenticationError"]}}}},on:{SIGNIN_PASSWORD:"authenticating.password",SIGNIN_ANONYMOUS:"authenticating.anonymous",SIGNIN_SECURITY_KEY_EMAIL:"authenticating.securityKeyEmail",SIGNIN_SECURITY_KEY:"authenticating.securityKey",SIGNIN_MFA_TOTP:"authenticating.mfa.totp",SIGNIN_PAT:"authenticating.pat",SIGNIN_ID_TOKEN:"authenticating.idToken"}},authenticating:{entry:"resetErrors",states:{password:{invoke:{src:"signInPassword",id:"authenticateUserWithPassword",onDone:[{cond:"hasMfaTicket",actions:["saveMfaTicket"],target:"#nhost.authentication.signedOut.needsMfa"},{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"}],onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},pat:{invoke:{src:"signInPAT",id:"authenticateWithPAT",onDone:{actions:["savePATSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},idToken:{invoke:{src:"signInIdToken",id:"authenticateWithIdToken",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},anonymous:{invoke:{src:"signInAnonymous",id:"authenticateAnonymously",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}}},mfa:{states:{totp:{invoke:{src:"signInMfaTotp",id:"signInMfaTotp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:["saveAuthenticationError"],target:"#nhost.authentication.signedOut.failed"}}}}},securityKeyEmail:{invoke:{src:"signInSecurityKeyEmail",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}},securityKey:{invoke:{src:"signInSecurityKey",id:"authenticateUserWithSecurityKey",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:[{cond:"unverified",target:["#nhost.authentication.signedOut","#nhost.registration.incomplete.needsEmailVerification"]},{actions:"saveAuthenticationError",target:"#nhost.authentication.signedOut.failed"}]}}}},signedIn:{type:"parallel",entry:["reportSignedIn","cleanUrl","broadcastToken","resetErrors"],on:{SIGNOUT:"signedOut.signingOut"},states:{refreshTimer:{id:"timer",initial:"idle",states:{disabled:{type:"final"},stopped:{always:{cond:"noToken",target:"idle"}},idle:{always:[{cond:"isAutoRefreshDisabled",target:"disabled"},{cond:"isRefreshTokenPAT",target:"disabled"},{cond:"hasRefreshToken",target:"running"}]},running:{initial:"pending",entry:"resetTimer",states:{pending:{after:{1e3:{internal:!1,target:"pending"}},always:{cond:"refreshTimerShouldRefresh",target:"refreshing"}},refreshing:{invoke:{src:"refreshToken",id:"refreshToken",onDone:{actions:["saveSession","resetTimer","reportTokenChanged"],target:"pending"},onError:[{cond:"isUnauthorizedError",target:"#nhost.authentication.signedOut"},{actions:"saveRefreshAttempt",target:"pending"}]}}}}}}}}}},token:{initial:"idle",states:{idle:{on:{TRY_TOKEN:"running"},initial:"noErrors",states:{noErrors:{},error:{}}},running:{invoke:{src:"refreshToken",id:"authenticateWithToken",onDone:{actions:["saveSession","reportTokenChanged"],target:["#nhost.authentication.signedIn","idle.noErrors"]},onError:[{cond:"isSignedIn",target:"idle.error"},{actions:"saveAuthenticationError",target:["#nhost.authentication.signedOut.failed","idle.error"]}]}}}},registration:{initial:"incomplete",on:{SIGNED_IN:[{cond:"isAnonymous",target:".incomplete"},".complete"]},states:{incomplete:{on:{SIGNUP_EMAIL_PASSWORD:"emailPassword",SIGNUP_SECURITY_KEY:"securityKey",PASSWORDLESS_EMAIL:"passwordlessEmail",PASSWORDLESS_SMS:"passwordlessSms",PASSWORDLESS_SMS_OTP:"passwordlessSmsOtp",SIGNIN_EMAIL_OTP:"signInEmailOTP",VERIFY_EMAIL_OTP:"verifyEmailOTP"},initial:"noErrors",states:{noErrors:{},needsEmailVerification:{},needsOtp:{},failed:{}}},emailPassword:{entry:["resetErrors"],invoke:{src:"signUpEmailPassword",id:"signUpEmailPassword",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},securityKey:{entry:["resetErrors"],invoke:{src:"signUpSecurityKey",id:"signUpSecurityKey",onDone:[{cond:"hasSession",actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]}],onError:[{cond:"unverified",target:"incomplete.needsEmailVerification"},{actions:"saveRegistrationError",target:"incomplete.failed"}]}},passwordlessEmail:{entry:["resetErrors"],invoke:{src:"passwordlessEmail",id:"passwordlessEmail",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsEmailVerification"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSms:{entry:["resetErrors"],invoke:{src:"passwordlessSms",id:"passwordlessSms",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},passwordlessSmsOtp:{entry:["resetErrors"],invoke:{src:"passwordlessSmsOtp",id:"passwordlessSmsOtp",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},signInEmailOTP:{entry:["resetErrors"],invoke:{src:"signInEmailOTP",id:"signInEmailOTP",onDone:{actions:"clearContext",target:["#nhost.authentication.signedOut","incomplete.needsOtp"]},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},verifyEmailOTP:{entry:["resetErrors"],invoke:{src:"verifyEmailOTP",id:"verifyEmailOTP",onDone:{actions:["saveSession","reportTokenChanged"],target:"#nhost.authentication.signedIn"},onError:{actions:"saveRegistrationError",target:"incomplete.failed"}}},complete:{on:{SIGNED_OUT:"incomplete"}}}}}},{actions:{reportSignedIn:u.send("SIGNED_IN"),reportSignedOut:u.send("SIGNED_OUT"),reportTokenChanged:u.send("TOKEN_CHANGED"),incrementTokenImportAttempts:u.assign({importTokenAttempts:({importTokenAttempts:a})=>a+1}),clearContext:u.assign(()=>(E(P,null),E(v,null),E(b,null),{...M})),clearContextExceptTokens:u.assign(({accessToken:a,refreshToken:o})=>({...M,accessToken:a,refreshToken:o})),saveSession:u.assign({user:(a,{data:o})=>{var c;return((c=o==null?void 0:o.session)==null?void 0:c.user)||null},accessToken:(a,{data:o})=>{if(o.session){const{accessTokenExpiresIn:c,accessToken:d}=o.session,g=new Date(Date.now()+c*1e3);return E(P,g.toISOString()),{value:d,expiresAt:g,expiresInSeconds:c}}return E(P,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:o})=>{var g,p;const c=((g=o.session)==null?void 0:g.refreshToken)||null,d=((p=o.session)==null?void 0:p.refreshTokenId)||null;return c&&E(v,c),d&&E(b,d),{value:c}}}),savePATSession:u.assign({user:(a,{data:o})=>{var c;return((c=o==null?void 0:o.session)==null?void 0:c.user)||null},accessToken:(a,{data:o})=>{if(o.session){const{accessTokenExpiresIn:c,accessToken:d}=o.session,g=new Date(Date.now()+c*1e3);return E(P,g.toISOString()),{value:d,expiresAt:g,expiresInSeconds:c}}return E(P,null),{value:null,expiresAt:null,expiresInSeconds:null}},refreshToken:(a,{data:o})=>{var g,p;const c=((g=o.session)==null?void 0:g.refreshToken)||null,d=((p=o.session)==null?void 0:p.refreshTokenId)||null;return c&&E(v,c),d&&E(b,d),{value:c,isPAT:!0}}}),saveMfaTicket:u.assign({mfa:(a,o)=>{var c;return(c=o.data)==null?void 0:c.mfa}}),resetTimer:u.assign({refreshTimer:a=>({startedAt:new Date,attempts:0,lastAttempt:null})}),saveRefreshAttempt:u.assign({refreshTimer:(a,o)=>({startedAt:a.refreshTimer.startedAt,attempts:a.refreshTimer.attempts+1,lastAttempt:new Date})}),saveAuthenticationError:u.assign({errors:({errors:a},{data:{error:o}})=>({...a,authentication:o})}),resetErrors:u.assign({errors:a=>({}),importTokenAttempts:a=>0}),saveRegistrationError:u.assign({errors:({errors:a},{data:{error:o}})=>({...a,registration:o})}),destroyRefreshToken:u.assign({refreshToken:a=>(E(v,null),E(b,null),{value:null})}),destroyAccessToken:u.assign({accessToken:a=>(E(P,null),{value:null,expiresAt:null,expiresInSeconds:null})}),cleanUrl:()=>{h&&D("refreshToken")&&(j("refreshToken"),j("type"))},broadcastToken:a=>{if(h&&r)try{new BroadcastChannel(r).postMessage({type:"broadcast_token",payload:{token:a.refreshToken.value}})}catch{}}},guards:{isAnonymous:(a,o)=>{var c;return!!((c=a.user)!=null&&c.isAnonymous)},isSignedIn:a=>!!a.user&&!!a.accessToken.value,noToken:a=>!a.refreshToken.value,isRefreshTokenPAT:a=>{var o;return!!((o=a.refreshToken)!=null&&o.isPAT)},hasRefreshToken:a=>!!a.refreshToken.value,isAutoRefreshDisabled:()=>!l,refreshTimerShouldRefresh:a=>{const{expiresAt:o}=a.accessToken;if(!o)return!1;if(a.refreshTimer.lastAttempt)return a.refreshTimer.attempts>W?!1:Date.now()-a.refreshTimer.lastAttempt.getTime()>Math.pow(2,a.refreshTimer.attempts-1)*5e3;if(o.getTime()<Date.now()||i&&Date.now()-a.refreshTimer.startedAt.getTime()>i*1e3)return!0;const c=a.accessToken.expiresInSeconds;return c?o.getTime()-Date.now()-1e3*Math.min(se,c*.5)<=0:!1},shouldRetryImportToken:(a,o)=>a.importTokenAttempts<W&&(o.data.error.status===X||o.data.error.status>=500),unverified:(a,{data:{error:o}})=>o.status===401&&(o.message==="Email is not verified"||o.error==="unverified-user"),hasSession:(a,o)=>{var c;return!!((c=o.data)!=null&&c.session)},hasMfaTicket:(a,o)=>{var c;return!!((c=o.data)!=null&&c.mfa)},isUnauthorizedError:(a,{data:{error:o}})=>o.status===401},services:{signInPassword:(a,{email:o,password:c})=>S(o)?L(c)?m("/signin/email-password",{email:o,password:c}):Promise.reject({error:K}):Promise.reject({error:y}),signInPAT:(a,{pat:o})=>m("/signin/pat",{personalAccessToken:o}),signInIdToken:(a,{provider:o,idToken:c,nonce:d})=>m("/signin/idtoken",{provider:o,idToken:c,...d&&{nonce:d}}),passwordlessSms:(a,{phoneNumber:o,options:c})=>{var d;return q(o)?(d=a.user)!=null&&d.isAnonymous?(console.warn("Deanonymisation from a phone number is not yet implemented in hasura-auth"),m("/user/deanonymize",{signInMethod:"passwordless",connection:"sms",phoneNumber:o,options:I(e,c)},a.accessToken.value)):m("/signin/passwordless/sms",{phoneNumber:o,options:I(e,c)}):Promise.reject({error:$})},passwordlessSmsOtp:(a,{phoneNumber:o,otp:c})=>q(o)?m("/signin/passwordless/sms/otp",{phoneNumber:o,otp:c}):Promise.reject({error:$}),signInEmailOTP:(a,{email:o,options:c})=>S(o)?m("/signin/otp/email",{email:o,options:I(e,c)}):Promise.reject({error:y}),verifyEmailOTP:(a,{email:o,otp:c})=>S(o)?m("/signin/otp/email/verify",{email:o,otp:c}):Promise.reject({error:y}),passwordlessEmail:(a,{email:o,options:c})=>{var d;return S(o)?(d=a.user)!=null&&d.isAnonymous?m("/user/deanonymize",{signInMethod:"passwordless",connection:"email",email:o,options:I(e,c)},a.accessToken.value):m("/signin/passwordless/email",{email:o,options:I(e,c)}):Promise.reject({error:y})},signInAnonymous:a=>m("/signin/anonymous"),signInMfaTotp:(a,o)=>{var d;const c=o.ticket||((d=a.mfa)==null?void 0:d.ticket);return c?ke(c)?m("/signin/mfa/totp",{ticket:c,otp:o.otp}):Promise.reject({error:oe}):Promise.reject({error:ae})},signInSecurityKeyEmail:async(a,{email:o})=>{if(!S(o))throw new O(y);const c=await m("/signin/webauthn",{email:o});let d;try{d=await F(c)}catch(g){throw new O(g)}return m("/signin/webauthn/verify",{email:o,credential:d})},refreshToken:async(a,o)=>{const c=o.type==="TRY_TOKEN"?o.token:a.refreshToken.value;return{session:await m("/token",{refreshToken:c}),error:null}},signInSecurityKey:async()=>{try{const a=await m("/signin/webauthn",{});let o;try{o=await F(a)}catch(c){throw new O(c)}return m("/signin/webauthn/verify",{credential:o})}catch(a){throw new O(a)}},signout:async(a,o)=>{const c=await m("/signout",{refreshToken:a.refreshToken.value,all:!!o.all},o.all?a.accessToken.value:void 0);if(r)try{new BroadcastChannel(r).postMessage({type:"signout"})}catch{}return c},signUpEmailPassword:async(a,{email:o,password:c,options:d,requestOptions:g})=>{var p;return S(o)?L(c)?(p=a.user)!=null&&p.isAnonymous?m("/user/deanonymize",{signInMethod:"email-password",email:o,password:c,options:I(e,d)},a.accessToken.value,g==null?void 0:g.headers):m("/signup/email-password",{email:o,password:c,options:I(e,d)},null,g==null?void 0:g.headers):Promise.reject({error:K}):Promise.reject({error:y})},signUpSecurityKey:async(a,{email:o,options:c,requestOptions:d})=>{if(!S(o))return Promise.reject({error:y});const g=c==null?void 0:c.nickname;g&&delete c.nickname;const p=await m("/signup/webauthn",{email:o,options:c},null,d==null?void 0:d.headers);let re;try{re=await we(p)}catch(Xe){throw new O(Xe)}return m("/signup/webauthn/verify",{credential:re,options:{redirectTo:c==null?void 0:c.redirectTo,nickname:g}})},importRefreshToken:async a=>{if(a.user&&a.refreshToken.value&&a.accessToken.value&&a.accessToken.expiresAt)return{session:{accessToken:a.accessToken.value,accessTokenExpiresIn:a.accessToken.expiresAt.getTime()-Date.now(),refreshToken:a.refreshToken.value,user:a.user},error:null};let o=null;if(h){const d=D("refreshToken")||null;if(d)try{return{session:await m("/token",{refreshToken:d}),error:null}}catch(g){o=g.error}else{const g=D("error"),p=D("errorDescription");if(g&&p!=="social user already exists")return Promise.reject({session:null,error:{status:k,error:g,message:p||g}})}}const c=await f(v);if(c)try{return{session:await m("/token",{refreshToken:c}),error:null}}catch(d){o=d.error}return o?Promise.reject({error:o,session:null}):{error:null,session:null}}},delays:{RETRY_IMPORT_TOKEN_DELAY:({importTokenAttempts:a})=>Math.pow(2,a-1)*5e3}})},Oe=({backendUrl:s,clientUrl:e,interpreter:r})=>u.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:u.assign({error:n=>y}),saveRequestError:u.assign({error:(n,{data:{error:t}})=>t}),reportError:u.send(n=>({type:"ERROR",error:n.error})),reportSuccess:u.send("SUCCESS")},guards:{invalidEmail:(n,{email:t})=>!S(t)},services:{requestChange:async(n,{email:t,options:i})=>(await R(`${s}/user/email/change`,{newEmail:t,options:I(e,i)},r==null?void 0:r.getSnapshot().context.accessToken.value)).data}}),Pe=({backendUrl:s,interpreter:e})=>u.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:u.assign({error:r=>K}),saveRequestError:u.assign({error:(r,{data:{error:n}})=>n}),reportError:u.send(r=>({type:"ERROR",error:r.error})),reportSuccess:u.send("SUCCESS")},guards:{invalidPassword:(r,{password:n})=>!L(n)},services:{requestChange:(r,{password:n,ticket:t})=>R(`${s}/user/password`,{newPassword:n,ticket:t},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ur=({backendUrl:s,interpreter:e})=>u.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:u.assign({error:r=>te}),saveInvalidMfaCodeError:u.assign({error:r=>ie}),saveError:u.assign({error:(r,{data:{error:n}})=>n}),saveGeneration:u.assign({imageUrl:(r,{data:{imageUrl:n}})=>n,secret:(r,{data:{totpSecret:n}})=>n}),reportError:u.send((r,n)=>(console.log("REPORT",r,n),{type:"ERROR",error:r.error})),reportSuccess:u.send("SUCCESS"),reportGeneratedSuccess:u.send("GENERATED"),reportGeneratedError:u.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 Se(`${s}/mfa/totp/generate`,e==null?void 0:e.getSnapshot().context.accessToken.value);return n},activate:(r,{code:n,activeMfaType:t})=>R(`${s}/user/mfa`,{code:n,activeMfaType:t},e==null?void 0:e.getSnapshot().context.accessToken.value)}}),ve=({backendUrl:s,clientUrl:e})=>u.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:u.assign({error:r=>y}),saveRequestError:u.assign({error:(r,{data:{error:n}})=>n}),reportError:u.send(r=>({type:"ERROR",error:r.error})),reportSuccess:u.send("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!S(n)},services:{requestChange:(r,{email:n,options:t})=>R(`${s}/user/password/reset`,{email:n,options:I(e,t)})}}),Ne=({backendUrl:s,clientUrl:e})=>u.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:u.assign({error:r=>y}),saveRequestError:u.assign({error:(r,{data:{error:n}})=>n}),reportError:u.send(r=>({type:"ERROR",error:r.error})),reportSuccess:u.send("SUCCESS")},guards:{invalidEmail:(r,{email:n})=>!S(n)},services:{request:async(r,{email:n,options:t})=>(await R(`${s}/user/email/send-verification-email`,{email:n,options:I(e,t)})).data}});class ee{constructor({clientStorageType:e="web",autoSignIn:r=!0,autoRefreshToken:n=!0,start:t=!0,backendUrl:i,clientUrl:l,broadcastKey:h,devTools:f,...E}){var m;if(this._started=!1,this._subscriptionsQueue=new Set,this._subscriptions=new Set,this.backendUrl=i,this.clientUrl=l,this._machine=Ae({...E,backendUrl:i,clientUrl:l,broadcastKey:h,clientStorageType:e,autoSignIn:r,autoRefreshToken:n}),t&&this.start({devTools:f}),typeof window!="undefined"&&h)try{this._channel=new BroadcastChannel(h),r&&((m=this._channel)==null||m.addEventListener("message",a=>{var d;const{type:o,payload:c}=a.data;if(o==="broadcast_token"){const g=(d=this.interpreter)==null?void 0:d.getSnapshot().context.refreshToken.value;this.interpreter&&c.token&&c.token!==g&&this.interpreter.send("TRY_TOKEN",{token:c.token})}})),this._channel.addEventListener("message",a=>{const{type:o}=a.data;o==="signout"&&this.interpreter&&this.interpreter.send("SIGNOUT")})}catch{}}start({devTools:e=!1,initialSession:r,interpreter:n}={}){var l,h;const t={...this.machine.context,accessToken:{...this.machine.context.accessToken},refreshToken:{...this.machine.context.refreshToken}};r&&(t.user=r.user,t.refreshToken.value=(l=r.refreshToken)!=null?l:null,t.accessToken.value=(h=r.accessToken)!=null?h:null,t.accessToken.expiresAt=new Date(Date.now()+r.accessTokenExpiresIn*1e3));const i=this.machine.withContext(t);this._interpreter||(this._interpreter=n||u.interpret(i,{devTools:e})),(!this._started||typeof window=="undefined")&&(this._interpreter.initialized&&(this._interpreter.stop(),this._subscriptions.forEach(f=>f())),this._interpreter.start(i.initialState),this._subscriptionsQueue.forEach(f=>f(this))),this._started=!0}get machine(){return this._machine}get interpreter(){return this._interpreter}get started(){return this._started}subscribe(e){if(this.started){const r=e(this);return this._subscriptions.add(r),r}else return this._subscriptionsQueue.add(e),()=>{console.log("onTokenChanged was added before the interpreter started. Cannot unsubscribe listener.")}}}class be extends ee{constructor({...e}){super({...e,autoSignIn:x()&&e.autoSignIn,autoRefreshToken:x()&&e.autoRefreshToken,clientStorageType:"cookie"})}}const dr=be,Ce=async({backendUrl:s,interpreter:e},r)=>{try{const{data:n}=await R(`${s}/user/webauthn/add`,{},e==null?void 0:e.getSnapshot().context.accessToken.value);let t;try{t=await we(n)}catch(l){throw new O(l)}const{data:i}=await R(`${s}/user/webauthn/verify`,{credential:t,nickname:r},e==null?void 0:e.getSnapshot().context.accessToken.value);return{key:i,isError:!1,error:null,isSuccess:!0}}catch(n){const{error:t}=n;return{isError:!0,error:t,isSuccess:!1}}},De=async(s,e,r)=>new Promise(n=>{s.send("REQUEST",{email:e,options:r}),s.onTransition(t=>{t.matches({idle:"error"})?n({error:t.context.error,isError:!0,needsEmailVerification:!1}):t.matches({idle:"success"})&&n({error:null,isError:!1,needsEmailVerification:!0})})}),xe=async(s,e,r)=>new Promise(n=>{s.send("REQUEST",{password:e,ticket:r}),s.onTransition(t=>{t.matches({idle:"error"})?n({error:t.context.error,isError:!0,isSuccess:!1}):t.matches({idle:"success"})&&n({error:null,isError:!1,isSuccess:!0})})}),hr=s=>new Promise(e=>{s.send("GENERATE"),s.onTransition(r=>{r.matches("generated")?e({error:null,isError:!1,isGenerated:!0,qrCodeDataUrl:r.context.imageUrl||""}):r.matches({idle:"error"})&&e({error:r.context.error||null,isError:!0,isGenerated:!1,qrCodeDataUrl:""})})}),fr=(s,e)=>new Promise(r=>{s.send("ACTIVATE",{activeMfaType:"totp",code:e}),s.onTransition(n=>{n.matches({generated:"activated"})?r({error:null,isActivated:!0,isError:!1}):n.matches({generated:{idle:"error"}})&&r({error:n.context.error,isActivated:!1,isError:!0})})}),Me=async(s,e,r)=>new Promise(n=>{s.send("REQUEST",{email:e,options:r}),s.onTransition(t=>{t.matches({idle:"error"})?n({error:t.context.error,isError:!0,isSent:!1}):t.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Ue=(s,e,r)=>new Promise(n=>{s.send("REQUEST",{email:e,options:r}),s.onTransition(t=>{t.matches({idle:"error"})?n({error:t.context.error,isError:!0,isSent:!1}):t.matches({idle:"success"})&&n({error:null,isError:!1,isSent:!0})})}),Ke=s=>new Promise(e=>{const{changed:r}=s.send("SIGNIN_ANONYMOUS");r||e({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(n=>{n.matches({authentication:"signedIn"})&&e({isSuccess:!0,isError:!1,error:null,user:n.context.user,accessToken:n.context.accessToken.value,refreshToken:n.context.refreshToken.value}),n.matches({authentication:{signedOut:"failed"}})&&e({isSuccess:!1,isError:!0,error:n.context.errors.authentication||null,user:null,accessToken:null,refreshToken:null})})}),Ve=(s,e,r)=>new Promise(n=>{const{changed:t,context:i}=s.send("SIGNIN_PASSWORD",{email:e,password:r});if(!t)return n({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:i.user});s.onTransition(l=>{l.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,needsMfaOtp:!1,mfa:null,user:null}):l.matches({authentication:{signedOut:"needsMfa"}})?n({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!0,mfa:l.context.mfa,user:null}):l.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:l.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:null}):l.matches({authentication:"signedIn"})&&n({accessToken:l.context.accessToken.value,refreshToken:l.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,needsMfaOtp:!1,mfa:null,user:l.context.user})})}),B=(s,e,r)=>new Promise(n=>{const{changed:t}=s.send("PASSWORDLESS_EMAIL",{email:e,options:r});if(!t)return n({error:w,isError:!0,isSuccess:!1});s.onTransition(i=>{i.matches("registration.incomplete.failed")?n({error:i.context.errors.registration||null,isError:!0,isSuccess:!1}):i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})&&n({error:null,isError:!1,isSuccess:!0})})}),Le=(s,e)=>new Promise(r=>{const{changed:n,context:t}=s.send({type:"SIGNIN_SECURITY_KEY_EMAIL",email:e});if(!n)return r({accessToken:t.accessToken.value,refreshToken:t.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:t.user});s.onTransition(i=>{i.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?r({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):i.matches({authentication:{signedOut:"failed"}})?r({accessToken:null,refreshToken:null,error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):i.matches({authentication:"signedIn"})&&r({accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:i.context.user})})}),Ge=(s,e)=>new Promise(async r=>{var h,f;const n=(h=s.interpreter)==null?void 0:h.getSnapshot(),t=n==null?void 0:n.context.accessToken.value,{data:i}=await R(`${s.backendUrl}/elevate/webauthn`,{email:e},t);let l;try{l=await F(i)}catch(E){throw new O(E)}try{const{data:{session:E},error:m}=await R(`${s.backendUrl}/elevate/webauthn/verify`,{email:e,credential:l},t);E&&!m&&((f=s.interpreter)==null||f.send({type:"SESSION_UPDATE",data:{session:E}}),r({error:null,isError:!1,isSuccess:!0,elevated:!0}))}catch(E){const{error:m}=E;r({error:m,isError:!0,isSuccess:!1,elevated:!1})}}),He=(s,e,r)=>new Promise(n=>{const{changed:t,context:i}=s.send("SIGNIN_MFA_TOTP",{otp:e,ticket:r});if(!t)return n({accessToken:i.accessToken.value,refreshToken:i.refreshToken.value,error:w,isError:!0,isSuccess:!1,user:i.user});s.onTransition(l=>{l.matches({authentication:{signedOut:"failed"}})?n({accessToken:null,refreshToken:null,error:l.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null}):l.matches({authentication:"signedIn"})&&n({accessToken:l.context.accessToken.value,refreshToken:l.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,user:l.context.user})})}),Ye=(s,e)=>new Promise(r=>{const{changed:n}=s.send("SIGNIN_PAT",{pat:e});n||r({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(t=>{if(t.matches({authentication:{signedOut:"failed"}}))return r({accessToken:null,refreshToken:null,user:null,error:t.context.errors.authentication||null,isError:!0,isSuccess:!1});if(t.matches({authentication:"signedIn"}))return r({accessToken:t.context.accessToken.value,refreshToken:t.context.refreshToken.value,user:t.context.user,error:null,isError:!1,isSuccess:!0})})}),Q=(s,e,r)=>new Promise(n=>{const{changed:t}=s.send("PASSWORDLESS_SMS",{phoneNumber:e,options:r});if(!t)return n({error:w,isError:!0,isSuccess:!1,needsOtp:!1});s.onTransition(i=>{i.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!1,needsOtp:!0}):i.matches("registration.incomplete.failed")&&n({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),We=(s,e,r)=>new Promise(n=>{const{changed:t}=s.send({type:"PASSWORDLESS_SMS_OTP",phoneNumber:e,otp:r});if(!t)return n({error:w,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value}):i.matches({registration:{incomplete:"failed"}})&&n({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),$e=async(s,e)=>new Promise(r=>{const{event:n}=s.send("SIGNOUT",{all:e});if(n.type!=="SIGNED_OUT")return r({isSuccess:!1,isError:!0,error:ue});s.onTransition(t=>{t.matches({authentication:{signedOut:"success"}})?r({isSuccess:!0,isError:!1,error:null}):t.matches("authentication.signedOut.failed")&&r({isSuccess:!1,isError:!0,error:t.context.errors.signout||null})})}),z=(s,e,r,n,t)=>new Promise(i=>{const{changed:l,context:h}=s.send("SIGNUP_EMAIL_PASSWORD",{email:e,password:r,options:n,requestOptions:t});if(!l)return i({error:w,accessToken:h.accessToken.value,refreshToken:h.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:h.user});s.onTransition(f=>{f.matches("registration.incomplete.failed")?i({accessToken:null,refreshToken:null,error:f.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):f.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?i({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):f.matches({authentication:"signedIn",registration:"complete"})&&i({accessToken:f.context.accessToken.value,refreshToken:f.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:f.context.user})})}),Fe=(s,e,r,n)=>new Promise(t=>{const{changed:i,context:l}=s.send("SIGNUP_SECURITY_KEY",{email:e,options:r,requestOptions:n});if(!i)return t({error:w,accessToken:l.accessToken.value,refreshToken:l.refreshToken.value,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:l.user});s.onTransition(h=>{h.matches("registration.incomplete.failed")?t({accessToken:null,refreshToken:null,error:h.context.errors.registration||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):h.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?t({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):h.matches({authentication:"signedIn",registration:"complete"})&&t({accessToken:h.context.accessToken.value,refreshToken:h.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:h.context.user})})}),je=(s,e,r)=>new Promise(n=>{const{changed:t}=s.send("SIGNIN_EMAIL_OTP",{email:e,options:r});if(!t)return n({error:w,isError:!0,isSuccess:!1,needsOtp:!1});s.onTransition(i=>{i.matches("registration.incomplete.needsOtp")?n({error:null,isError:!1,isSuccess:!0,needsOtp:!0}):i.matches("registration.incomplete.failed")&&n({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,needsOtp:!1})})}),qe=(s,e,r)=>new Promise(n=>{const{changed:t}=s.send({type:"VERIFY_EMAIL_OTP",email:e,otp:r});if(!t)return n({error:w,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null});s.onTransition(i=>{i.matches({authentication:"signedIn"})?n({error:null,isError:!1,isSuccess:!0,user:i.context.user,accessToken:i.context.accessToken.value,refreshToken:i.context.refreshToken.value}):i.matches({registration:{incomplete:"failed"}})&&n({error:i.context.errors.authentication||null,isError:!0,isSuccess:!1,user:null,accessToken:null,refreshToken:null})})}),Be=(s,{provider:e,idToken:r,nonce:n})=>new Promise(t=>{const{changed:i}=s.send("SIGNIN_ID_TOKEN",{provider:e,idToken:r,...n&&{nonce:n}});i||t({isSuccess:!1,isError:!0,error:w,user:null,accessToken:null,refreshToken:null}),s.onTransition(l=>{if(l.matches({authentication:{signedOut:"failed"}}))return t({accessToken:null,refreshToken:null,user:null,error:l.context.errors.authentication||null,isError:!0,isSuccess:!1});if(l.matches({authentication:"signedIn"}))return t({accessToken:l.context.accessToken.value,refreshToken:l.context.refreshToken.value,user:l.context.user,error:null,isError:!1,isSuccess:!0})})}),Qe=async({backendUrl:s,interpreter:e},{provider:r,idToken:n,nonce:t})=>{try{return await R(`${s}/link/idtoken`,{provider:r,idToken:n,...t&&{nonce:t}},e==null?void 0:e.getSnapshot().context.accessToken.value),{isError:!1,error:null,isSuccess:!0}}catch(i){const{error:l}=i;return{isError:!0,error:l,isSuccess:!1}}},ze=s=>new Promise(e=>{const{changed:r,context:n}=s.send({type:"SIGNIN_SECURITY_KEY"});if(!r)return e({accessToken:n.accessToken.value,refreshToken:n.refreshToken.value,error:w,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:n.user});s.onTransition(t=>{t.matches({authentication:{signedOut:"noErrors"},registration:{incomplete:"needsEmailVerification"}})?e({accessToken:null,refreshToken:null,error:null,isError:!1,isSuccess:!1,needsEmailVerification:!0,user:null}):t.matches({authentication:{signedOut:"failed"}})?e({accessToken:null,refreshToken:null,error:t.context.errors.authentication||null,isError:!0,isSuccess:!1,needsEmailVerification:!1,user:null}):t.matches({authentication:"signedIn"})&&e({accessToken:t.context.accessToken.value,refreshToken:t.context.refreshToken.value,error:null,isError:!1,isSuccess:!0,needsEmailVerification:!1,user:t.context.user})})}),Er=async({backendUrl:s,interpreter:e},{expiresAt:r,metadata:n})=>{try{const{data:t}=await R(`${s}/pat`,{expiresAt:r.toISOString(),metadata:n},e==null?void 0:e.getSnapshot().context.accessToken.value);return{data:t?{id:t.id||null,personalAccessToken:t.personalAccessToken||null}:null,isError:!1,error:null,isSuccess:!0}}catch(t){const{error:i}=t;return{isError:!0,error:i,isSuccess:!1,data:null}}};class mr{constructor({url:e,broadcastKey:r,autoRefreshToken:n=!0,autoSignIn:t=!0,clientStorage:i,clientStorageType:l,refreshIntervalTime:h,start:f=!0}){var E;this.url=e,this._client=new ee({backendUrl:e,clientUrl:typeof window!="undefined"&&((E=window.location)==null?void 0:E.origin)||"",broadcastKey:r,autoRefreshToken:n,autoSignIn:t,start:f,clientStorage:i,clientStorageType:l,refreshIntervalTime:h})}async signUp(e,r){const n=await this.waitUntilReady();if("securityKey"in e){const{email:h,options:f}=e;return _(await Fe(n,h,f,r))}const{email:t,password:i,options:l}=e;return _(await z(n,t,i,l,r))}async connectProvider(e){const n=(await this.waitUntilReady()).getSnapshot().context.accessToken.value,{provider:t,options:i}=e,l=V(`${this._client.backendUrl}/signin/provider/${t}`,I(this._client.clientUrl,{...i,connect:n}));return x()&&(window.location.href=l),{providerUrl:l}}async signInIdToken(e){const r=await this.waitUntilReady(),n=await Be(r,e);return{..._(n),mfa:null}}async linkIdToken(e){return Qe(this._client,e)}async signIn(e){const r=await this.waitUntilReady();if(!e){const n=await Ke(r);return{..._(n),mfa:null}}if("provider"in e){const{provider:n,options:t}=e,i=V(`${this._client.backendUrl}/signin/provider/${n}`,I(this._client.clientUrl,t));return x()&&(window.location.href=i),{providerUrl:i,provider:n,session:null,mfa:null,error:null}}if("email"in e&&"password"in e){const n=await Ve(r,e.email,e.password);return n.needsEmailVerification?{session:null,mfa:null,error:de}:n.needsMfaOtp?{session:null,mfa:n.mfa,error:null}:{..._(n),mfa:null}}if("email"in e&&"securityKey"in e){if(e.securityKey!==!0)throw Error("securityKey must be true");const n=await Le(r,e.email);return{..._(n),mfa:null}}if("email"in e){const{email:n,options:t}=e,{error:i}=await B(r,n,t);return{session:null,mfa:null,error:i}}if("phoneNumber"in e&&"otp"in e){const n=await We(r,e.phoneNumber,e.otp);return{..._(n),mfa:null}}if("phoneNumber"in e){const{error:n}=await Q(r,e.phoneNumber,e.options);return{error:n,mfa:null,session:null}}if("otp"in e){const n=await He(r,e.otp,e.ticket);return{..._(n),mfa:null}}return{error:fe,mfa:null,session:null}}async signInPAT(e){const r=await this.waitUntilReady(),n=await Ye(r,e);return _(n)}async signInEmailOTP(e,r){const n=await this.waitUntilReady(),{error:t}=await je(n,e,r);return{error:t,session:null,mfa:null}}async verifyEmailOTP(e,r){const n=await this.waitUntilReady(),t=await qe(n,e,r);return{..._(t),mfa:null}}async signInSecurityKey(){const e=await this.waitUntilReady(),r=await ze(e);return{..._(r),mfa:null}}async signOut(e){const r=await this.waitUntilReady(),{error:n}=await $e(r,e==null?void 0:e.all);return{error:n}}async resetPassword({email:e,options:r}){const n=u.interpret(ve(this._client)).start(),{error:t}=await Me(n,e,r);return{error:t}}async changePassword({newPassword:e,ticket:r}){const n=u.interpret(Pe(this._client)).start(),{error:t}=await xe(n,e,r);return{error:t}}async sendVerificationEmail({email:e,options:r}){const n=u.interpret(Ne(this._client)).start(),{error:t}=await Ue(n,e,r);return{error:t}}async changeEmail({newEmail:e,options:r}){const n=u.interpret(Oe(this._client)).start(),{error:t}=await De(n,e,r);return{error:t}}async deanonymize(e){const r=await this.waitUntilReady();if(e.signInMethod==="passwordless"){if(e.connection==="email"){const{error:n}=await B(r,e.email,e.options);return{error:n}}if(e.connection==="sms"){const{error:n}=await Q(r,e.phoneNumber,e.options);return{error:n}}}if(e.signInMethod==="email-password"){const{error:n}=await z(r,e.email,e.password,e.options);return{error:n}}throw Error("Unknown deanonymization method")}async addSecurityKey(e){const{error:r,key:n}=await Ce(this._client,e);return{error:r,key:n}}async elevateEmailSecurityKey(e){if(!e)throw Error("A user email is required");return{...await Ge(this._client,e),mfa:null}}async createPAT(e,r){return Er(this._client,{expiresAt:e,metadata:r})}onTokenChanged(e){return this._client.subscribe(()=>{var n;const r=(n=this._client.interpreter)==null?void 0:n.onTransition(({event:t,context:i})=>{t.type==="TOKEN_CHANGED"&&e(C(i))});return()=>r==null?void 0:r.stop()})}onAuthStateChanged(e){return this._client.subscribe(()=>{var n;const r=(n=this._client.interpreter)==null?void 0:n.onTransition(({event:t,context:i})=>{(t.type==="SIGNED_IN"||t.type==="SIGNED_OUT")&&e(t.type,C(i))});return()=>r==null?void 0:r.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 r;const e=((r=this.client.interpreter)==null?void 0:r.getSnapshot().context.importTokenAttempts)||0;return this.isReady()?{isAuthenticated:this.isAuthenticated(),isLoading:!1,connectionAttempts:e}:{isAuthenticated:!1,isLoading:!0,connectionAttempts:e}}getAccessToken(){var e,r;return(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot().context.accessToken.value)!=null?r:void 0}getDecodedAccessToken(){const e=this.getAccessToken();return e?Ze.jwtDecode(e):null}getHasuraClaims(){var e;return((e=this.getDecodedAccessToken())==null?void 0:e["https://hasura.io/jwt/claims"])||null}getHasuraClaim(e){var r;return((r=this.getHasuraClaims())==null?void 0:r[e.startsWith("x-hasura-")?e:`x-hasura-${e}`])||null}async refreshSession(e){try{const r=await this.waitUntilReady();return new Promise(n=>{const t=e||r.getSnapshot().context.refreshToken.value;if(!t)return n({session:null,error:ce});const{changed:i}=r.send("TRY_TOKEN",{token:t});if(!i)return n({session:null,error:le});r.onTransition(l=>{l.matches({token:{idle:"error"}})?n({session:null,error:he}):l.event.type==="TOKEN_CHANGED"&&n({session:C(l.context),error:null})})})}catch(r){return{session:null,error:r.message}}}getSession(){var e,r;return C((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)}async initWithSession({session:e}){this.client.start({initialSession:e}),await this.waitUntilReady()}getUser(){var e,r,n;return((n=(r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())==null?void 0:r.context)==null?void 0:n.user)||null}waitUntilReady(){const r=this._client.interpreter;if(!r)throw Error("Auth interpreter not set");return r.getSnapshot().hasTag("loading")?new Promise((n,t)=>{let i=setTimeout(()=>t("The state machine is not yet ready after 15 seconds."),15e3);r.onTransition(l=>{if(!l.hasTag("loading"))return clearTimeout(i),n(r)})}):Promise.resolve(r)}isReady(){var e,r;return!((r=(e=this._client.interpreter)==null?void 0:e.getSnapshot())!=null&&r.hasTag("loading"))}get client(){return this._client}}exports.AuthClient=ee;exports.AuthClientSSR=dr;exports.AuthCookieClient=be;exports.CodifiedError=O;exports.EMAIL_NEEDS_VERIFICATION=de;exports.HasuraAuthClient=mr;exports.INITIAL_MACHINE_CONTEXT=M;exports.INVALID_EMAIL_ERROR=y;exports.INVALID_MFA_CODE_ERROR=ie;exports.INVALID_MFA_TICKET_ERROR=oe;exports.INVALID_MFA_TYPE_ERROR=te;exports.INVALID_PASSWORD_ERROR=K;exports.INVALID_PHONE_NUMBER_ERROR=$;exports.INVALID_REFRESH_TOKEN=he;exports.INVALID_SIGN_IN_METHOD=fe;exports.MIN_PASSWORD_LENGTH=ne;exports.NETWORK_ERROR_CODE=X;exports.NHOST_JWT_EXPIRES_AT_KEY=P;exports.NHOST_REFRESH_TOKEN_ID_KEY=b;exports.NHOST_REFRESH_TOKEN_KEY=v;exports.NO_MFA_TICKET_ERROR=ae;exports.NO_REFRESH_TOKEN=ce;exports.OTHER_ERROR_CODE=Z;exports.REFRESH_TOKEN_MAX_ATTEMPTS=W;exports.STATE_ERROR_CODE=N;exports.TOKEN_REFRESHER_RUNNING_ERROR=le;exports.TOKEN_REFRESH_MARGIN_SECONDS=se;exports.USER_ALREADY_SIGNED_IN=w;exports.USER_NOT_ANONYMOUS=er;exports.USER_UNAUTHENTICATED=ue;exports.VALIDATION_ERROR_CODE=k;exports.activateMfaPromise=fr;exports.addSecurityKeyPromise=Ce;exports.changeEmailPromise=De;exports.changePasswordPromise=xe;exports.createAuthMachine=Ae;exports.createChangeEmailMachine=Oe;exports.createChangePasswordMachine=Pe;exports.createEnableMfaMachine=ur;exports.createResetPasswordMachine=ve;exports.createSendVerificationEmailMachine=Ne;exports.elevateEmailSecurityKeyPromise=Ge;exports.encodeQueryParameters=V;exports.generateQrCodePromise=hr;exports.getAuthenticationResult=_;exports.getFetch=Se;exports.getParameterByName=D;exports.getSession=C;exports.isBrowser=x;exports.isValidEmail=S;exports.isValidPassword=L;exports.isValidPhoneNumber=q;exports.isValidTicket=ke;exports.linkIdTokenPromise=Qe;exports.localStorageGetter=Ie;exports.localStorageSetter=Re;exports.postFetch=R;exports.removeParameterFromWindow=j;exports.resetPasswordPromise=Me;exports.rewriteRedirectTo=I;exports.sendVerificationEmailPromise=Ue;exports.signInAnonymousPromise=Ke;exports.signInEmailOTPPromise=je;exports.signInEmailPasswordPromise=Ve;exports.signInEmailPasswordlessPromise=B;exports.signInEmailSecurityKeyPromise=Le;exports.signInIdTokenPromise=Be;exports.signInMfaTotpPromise=He;exports.signInPATPromise=Ye;exports.signInSecurityKeyPromise=ze;exports.signInSmsPasswordlessOtpPromise=We;exports.signInSmsPasswordlessPromise=Q;exports.signOutPromise=$e;exports.signUpEmailPasswordPromise=z;exports.signUpEmailSecurityKeyPromise=Fe;exports.verifyEmailOTPPromise=qe;
//# sourceMappingURL=index.cjs.js.map

@@ -79,2 +79,3 @@ import { AuthContext, AuthInterpreter, AuthMachineOptions } from './machines';

options?: import('./types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('./types').RequestOptions | undefined;
} | {

@@ -207,2 +208,3 @@ type: "SIGNOUT";

options?: import('./types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('./types').RequestOptions | undefined;
} | {

@@ -209,0 +211,0 @@ type: "SIGNOUT";

@@ -55,2 +55,3 @@ import { EmailOTPOptions, NhostSession, PasswordlessOptions, RequestOptions, SignUpOptions, SignUpSecurityKeyOptions } from '../../types';

options?: SignUpSecurityKeyOptions;
requestOptions?: RequestOptions;
} | {

@@ -57,0 +58,0 @@ type: 'SIGNOUT';

@@ -116,2 +116,3 @@ import { InterpreterFrom } from 'xstate';

options?: import('../../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../../types').RequestOptions | undefined;
} | {

@@ -192,2 +193,3 @@ type: "SIGNOUT";

options?: import('../../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../../types').RequestOptions | undefined;
} | {

@@ -194,0 +196,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -66,2 +66,3 @@ import { EmailOTPOptions } from '../types';

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -142,2 +143,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -268,2 +270,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -344,2 +347,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -346,0 +350,0 @@ type: "SIGNOUT";

@@ -63,2 +63,3 @@ import { AuthActionLoadingState, NeedsEmailVerificationState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -139,2 +140,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -141,0 +143,0 @@ type: "SIGNOUT";

@@ -60,2 +60,3 @@ import { PasswordlessOptions } from '../types';

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -136,2 +137,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -138,0 +140,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, NeedsEmailVerificationState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -65,2 +65,3 @@ import { Provider } from '../types';

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -141,2 +142,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -143,0 +145,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, NeedsEmailVerificationState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -64,2 +64,3 @@ import { PasswordlessOptions } from '../types';

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -140,2 +141,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
} | {

@@ -142,0 +144,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionLoadingState, SessionActionHandlerResult } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -59,2 +59,3 @@ import { AuthActionErrorState, AuthActionLoadingState, AuthActionSuccessState } from './types';

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -135,2 +136,3 @@ type: "SIGNOUT";

options?: import('..').SignUpSecurityKeyOptions | undefined;
requestOptions?: import('..').RequestOptions | undefined;
} | {

@@ -137,0 +139,0 @@ type: "SIGNOUT";

@@ -60,2 +60,3 @@ import { RequestOptions, SignUpOptions } from '../types';

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -136,2 +137,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpSecurityKeyOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -138,0 +140,0 @@ type: "SIGNOUT";

@@ -1,2 +0,2 @@

import { SignUpSecurityKeyOptions } from '../types';
import { RequestOptions, SignUpSecurityKeyOptions } from '../types';
import { AuthActionLoadingState, NeedsEmailVerificationState, SessionActionHandlerResult } from './types';

@@ -55,3 +55,3 @@

options?: import('../types').SignUpOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -61,2 +61,3 @@ type: "SIGNUP_SECURITY_KEY";

options?: SignUpSecurityKeyOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -132,3 +133,3 @@ type: "SIGNOUT";

options?: import('../types').SignUpOptions | undefined;
requestOptions?: import('../types').RequestOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -138,2 +139,3 @@ type: "SIGNUP_SECURITY_KEY";

options?: SignUpSecurityKeyOptions | undefined;
requestOptions?: RequestOptions | undefined;
} | {

@@ -211,3 +213,3 @@ type: "SIGNOUT";

};
}>>, email: string, options?: SignUpSecurityKeyOptions) => Promise<SignUpSecurityKeyHandlerResult>;
}>>, email: string, options?: SignUpSecurityKeyOptions, requestOptions?: RequestOptions) => Promise<SignUpSecurityKeyHandlerResult>;
//# sourceMappingURL=signUpEmailSecurityKey.d.ts.map
import { NullableErrorResponse } from '../types';
interface FetcResponse<T> extends NullableErrorResponse {
interface FetchResponse<T> extends NullableErrorResponse {
data: T;
}
export declare const postFetch: <T>(url: string, body: any, token?: string | null, extraHeaders?: HeadersInit) => Promise<FetcResponse<T>>;
export declare const getFetch: <T>(url: string, token?: string | null) => Promise<FetcResponse<T>>;
export declare const postFetch: <T>(url: string, body: any, token?: string | null, extraHeaders?: HeadersInit) => Promise<FetchResponse<T>>;
export declare const getFetch: <T>(url: string, token?: string | null) => Promise<FetchResponse<T>>;
export {};
//# sourceMappingURL=fetch.d.ts.map
{
"name": "@nhost/hasura-auth-js",
"version": "2.10.1",
"version": "2.10.2",
"description": "Hasura-auth client",

@@ -5,0 +5,0 @@ "license": "MIT",

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 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