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CACvF,CAAC,CACF,CACH,GAn5EexI,EAAA,eAAiB,ECpHlC,IAAMyI,GAAeC,EAErBC,GAAeF,GCFf,IAAMG,GAAaC,EAEnBC,GAAeF","names":["version","GOTRUE_URL","STORAGE_KEY","DEFAULT_HEADERS","version","EXPIRY_MARGIN","API_VERSION_HEADER_NAME","API_VERSIONS","expiresAt","expiresIn","uuid","c","r","isBrowser","localStorageWriteTests","supportsLocalStorage","randomKey","parseParametersFromURL","href","result","url","value","key","resolveFetch","customFetch","_fetch","args","fetch","looksLikeFetchResponse","maybeResponse","setItemAsync","storage","data","getItemAsync","removeItemAsync","decodeBase64URL","base64","chr1","chr2","chr3","enc1","enc2","enc3","enc4","i","Deferred","_Deferred","res","rej","decodeJWTPayload","token","base64UrlRegex","parts","base64Url","sleep","time","accept","retryable","fn","isRetryable","reject","attempt","e","dec2hex","dec","generatePKCEVerifier","array","charSet","charSetLen","verifier","sha256","randomString","encodedData","hash","bytes","base64urlencode","str","generatePKCEChallenge","hashed","getCodeChallengeAndMethod","storageKey","isPasswordRecovery","codeVerifier","storedCodeVerifier","codeChallenge","API_VERSION_REGEX","parseResponseAPIVersion","response","apiVersion","API_VERSION_HEADER_NAME","AuthError","message","status","code","isAuthError","error","AuthApiError","isAuthApiError","AuthUnknownError","originalError","CustomAuthError","name","AuthSessionMissingError","isAuthSessionMissingError","AuthInvalidTokenResponseError","AuthInvalidCredentialsError","AuthImplicitGrantRedirectError","details","AuthPKCEGrantCodeExchangeError","AuthRetryableFetchError","isAuthRetryableFetchError","AuthWeakPasswordError","reasons","isAuthWeakPasswordError","_getErrorMessage","err","NETWORK_ERROR_CODES","handleError","error","looksLikeFetchResponse","AuthRetryableFetchError","data","e","AuthUnknownError","errorCode","responseAPIVersion","parseResponseAPIVersion","API_VERSIONS","AuthWeakPasswordError","_a","AuthSessionMissingError","a","i","AuthApiError","_getRequestParams","method","options","parameters","body","params","_request","fetcher","url","headers","API_VERSION_HEADER_NAME","qs","queryString","_handleRequest","requestParams","result","_sessionResponse","session","hasSession","expiresAt","user","_sessionResponsePassword","response","_userResponse","_ssoResponse","_generateLinkResponse","action_link","email_otp","hashed_token","redirect_to","verification_type","rest","__rest","properties","_noResolveJsonResponse","GoTrueAdminApi","url","headers","fetch","resolveFetch","jwt","scope","_request","error","isAuthError","email","options","_userResponse","params","rest","__rest","body","_generateLinkResponse","attributes","pagination","response","_b","_a","_d","_c","_noResolveJsonResponse","users","total","_e","links","_g","_f","link","page","rel","uid","id","shouldSoftDelete","data","factors","localStorageAdapter","key","supportsLocalStorage","value","memoryLocalStorageAdapter","store","polyfillGlobalThis","internals","supportsLocalStorage","LockAcquireTimeoutError","message","NavigatorLockAcquireTimeoutError","navigatorLock","name","acquireTimeout","fn","abortController","lock","result","e","polyfillGlobalThis","DEFAULT_OPTIONS","GOTRUE_URL","STORAGE_KEY","DEFAULT_HEADERS","AUTO_REFRESH_TICK_DURATION","AUTO_REFRESH_TICK_THRESHOLD","lockNoOp","name","acquireTimeout","fn","GoTrueClient","_GoTrueClient","options","isBrowser","settings","GoTrueAdminApi","resolveFetch","_a","navigatorLock","supportsLocalStorage","localStorageAdapter","memoryLocalStorageAdapter","e","_b","event","args","version","isPKCEFlow","data","error","session","redirectType","isAuthError","AuthUnknownError","credentials","res","_request","_c","_sessionResponse","user","email","password","codeChallenge","codeChallengeMethod","getCodeChallengeAndMethod","phone","AuthInvalidCredentialsError","_sessionResponsePassword","AuthInvalidTokenResponseError","_d","authCode","storageItem","getItemAsync","codeVerifier","removeItemAsync","provider","token","access_token","nonce","_e","params","redirectTo","captchaToken","_ssoResponse","result","sessionError","AuthSessionMissingError","endpoint","type","last","waitOn","currentSession","maybeSession","hasExpired","suppressWarning","target","prop","receiver","jwt","_userResponse","isAuthSessionMissingError","attributes","sessionData","userError","decodeJWTPayload","timeNow","expiresAt","payload","refreshedSession","AuthImplicitGrantRedirectError","AuthPKCEGrantCodeExchangeError","parseParametersFromURL","url","provider_token","provider_refresh_token","refresh_token","expires_in","expires_at","token_type","expiresIn","actuallyExpiresIn","issuedAt","currentStorageContent","scope","accessToken","isAuthApiError","callback","id","uuid","subscription","err","identity","refreshToken","debugName","startedAt","retryable","attempt","sleep","nextBackOffInterval","isAuthRetryableFetchError","expiresWithMargin","EXPIRY_MARGIN","Deferred","broadcast","errors","promises","x","i","setItemAsync","ticker","now","expiresInTicks","LockAcquireTimeoutError","calledFromInitialize","methodName","urlParams","flowParams","query","body","challengeData","challengeError","factors","totp","factor","currentLevel","nextLevel","currentAuthenticationMethods","AuthAdminApi","GoTrueAdminApi","AuthAdminApi_default","AuthClient","GoTrueClient","AuthClient_default"],"sources":["../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/version.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/constants.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/helpers.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/errors.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/fetch.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/GoTrueAdminApi.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/local-storage.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/polyfills.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/lib/locks.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/GoTrueClient.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/AuthAdminApi.ts","../esm/npm/@supabase/auth-js@2.65.0/node_modules/@supabase/auth-js/src/AuthClient.ts"],"sourcesContent":["export const version = '2.65.0'\n","import { version } from './version'\nexport const GOTRUE_URL = 'http://localhost:9999'\nexport const STORAGE_KEY = 'supabase.auth.token'\nexport const AUDIENCE = ''\nexport const DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version}` }\nexport const EXPIRY_MARGIN = 10 // in seconds\nexport const NETWORK_FAILURE = {\n  MAX_RETRIES: 10,\n  RETRY_INTERVAL: 2, // in deciseconds\n}\n\nexport const API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'\nexport const API_VERSIONS = {\n  '2024-01-01': {\n    timestamp: Date.parse('2024-01-01T00:00:00.0Z'),\n    name: '2024-01-01',\n  },\n}\n","import { API_VERSION_HEADER_NAME } from './constants'\nimport { SupportedStorage } from './types'\n\nexport function expiresAt(expiresIn: number) {\n  const timeNow = Math.round(Date.now() / 1000)\n  return timeNow + expiresIn\n}\n\nexport function uuid() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0,\n      v = c == 'x' ? r : (r \u0026 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n\nexport const isBrowser = () =\u003e typeof document !== 'undefined'\n\nconst localStorageWriteTests = {\n  tested: false,\n  writable: false,\n}\n\n/**\n * Checks whether localStorage is supported on this browser.\n */\nexport const supportsLocalStorage = () =\u003e {\n  if (!isBrowser()) {\n    return false\n  }\n\n  try {\n    if (typeof globalThis.localStorage !== 'object') {\n      return false\n    }\n  } catch (e) {\n    // DOM exception when accessing `localStorage`\n    return false\n  }\n\n  if (localStorageWriteTests.tested) {\n    return localStorageWriteTests.writable\n  }\n\n  const randomKey = `lswt-${Math.random()}${Math.random()}`\n\n  try {\n    globalThis.localStorage.setItem(randomKey, randomKey)\n    globalThis.localStorage.removeItem(randomKey)\n\n    localStorageWriteTests.tested = true\n    localStorageWriteTests.writable = true\n  } catch (e) {\n    // localStorage can't be written to\n    // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document\n\n    localStorageWriteTests.tested = true\n    localStorageWriteTests.writable = false\n  }\n\n  return localStorageWriteTests.writable\n}\n\n/**\n * Extracts parameters encoded in the URL both in the query and fragment.\n */\nexport function parseParametersFromURL(href: string) {\n  const result: { [parameter: string]: string } = {}\n\n  const url = new URL(href)\n\n  if (url.hash \u0026\u0026 url.hash[0] === '#') {\n    try {\n      const hashSearchParams = new URLSearchParams(url.hash.substring(1))\n      hashSearchParams.forEach((value, key) =\u003e {\n        result[key] = value\n      })\n    } catch (e: any) {\n      // hash is not a query string\n    }\n  }\n\n  // search parameters take precedence over hash parameters\n  url.searchParams.forEach((value, key) =\u003e {\n    result[key] = value\n  })\n\n  return result\n}\n\ntype Fetch = typeof fetch\n\nexport const resolveFetch = (customFetch?: Fetch): Fetch =\u003e {\n  let _fetch: Fetch\n  if (customFetch) {\n    _fetch = customFetch\n  } else if (typeof fetch === 'undefined') {\n    _fetch = (...args) =\u003e\n      import('@supabase/node-fetch' as any).then(({ default: fetch }) =\u003e fetch(...args))\n  } else {\n    _fetch = fetch\n  }\n  return (...args) =\u003e _fetch(...args)\n}\n\nexport const looksLikeFetchResponse = (maybeResponse: unknown): maybeResponse is Response =\u003e {\n  return (\n    typeof maybeResponse === 'object' \u0026\u0026\n    maybeResponse !== null \u0026\u0026\n    'status' in maybeResponse \u0026\u0026\n    'ok' in maybeResponse \u0026\u0026\n    'json' in maybeResponse \u0026\u0026\n    typeof (maybeResponse as any).json === 'function'\n  )\n}\n\n// Storage helpers\nexport const setItemAsync = async (\n  storage: SupportedStorage,\n  key: string,\n  data: any\n): Promise\u003cvoid\u003e =\u003e {\n  await storage.setItem(key, JSON.stringify(data))\n}\n\nexport const getItemAsync = async (storage: SupportedStorage, key: string): Promise\u003cunknown\u003e =\u003e {\n  const value = await storage.getItem(key)\n\n  if (!value) {\n    return null\n  }\n\n  try {\n    return JSON.parse(value)\n  } catch {\n    return value\n  }\n}\n\nexport const removeItemAsync = async (storage: SupportedStorage, key: string): Promise\u003cvoid\u003e =\u003e {\n  await storage.removeItem(key)\n}\n\nexport function decodeBase64URL(value: string): string {\n  const key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='\n  let base64 = ''\n  let chr1, chr2, chr3\n  let enc1, enc2, enc3, enc4\n  let i = 0\n  value = value.replace('-', '+').replace('_', '/')\n\n  while (i \u003c value.length) {\n    enc1 = key.indexOf(value.charAt(i++))\n    enc2 = key.indexOf(value.charAt(i++))\n    enc3 = key.indexOf(value.charAt(i++))\n    enc4 = key.indexOf(value.charAt(i++))\n    chr1 = (enc1 \u003c\u003c 2) | (enc2 \u003e\u003e 4)\n    chr2 = ((enc2 \u0026 15) \u003c\u003c 4) | (enc3 \u003e\u003e 2)\n    chr3 = ((enc3 \u0026 3) \u003c\u003c 6) | enc4\n    base64 = base64 + String.fromCharCode(chr1)\n\n    if (enc3 != 64 \u0026\u0026 chr2 != 0) {\n      base64 = base64 + String.fromCharCode(chr2)\n    }\n    if (enc4 != 64 \u0026\u0026 chr3 != 0) {\n      base64 = base64 + String.fromCharCode(chr3)\n    }\n  }\n  return base64\n}\n\n/**\n * A deferred represents some asynchronous work that is not yet finished, which\n * may or may not culminate in a value.\n * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts\n */\nexport class Deferred\u003cT = any\u003e {\n  public static promiseConstructor: PromiseConstructor = Promise\n\n  public readonly promise!: PromiseLike\u003cT\u003e\n\n  public readonly resolve!: (value?: T | PromiseLike\u003cT\u003e) =\u003e void\n\n  public readonly reject!: (reason?: any) =\u003e any\n\n  public constructor() {\n    // eslint-disable-next-line @typescript-eslint/no-extra-semi\n    ;(this as any).promise = new Deferred.promiseConstructor((res, rej) =\u003e {\n      // eslint-disable-next-line @typescript-eslint/no-extra-semi\n      ;(this as any).resolve = res\n      // eslint-disable-next-line @typescript-eslint/no-extra-semi\n      ;(this as any).reject = rej\n    })\n  }\n}\n\n// Taken from: https://stackoverflow.com/questions/38552003/how-to-decode-jwt-token-in-javascript-without-using-a-library\nexport function decodeJWTPayload(token: string) {\n  // Regex checks for base64url format\n  const base64UrlRegex = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i\n\n  const parts = token.split('.')\n\n  if (parts.length !== 3) {\n    throw new Error('JWT is not valid: not a JWT structure')\n  }\n\n  if (!base64UrlRegex.test(parts[1])) {\n    throw new Error('JWT is not valid: payload is not in base64url format')\n  }\n\n  const base64Url = parts[1]\n  return JSON.parse(decodeBase64URL(base64Url))\n}\n\n/**\n * Creates a promise that resolves to null after some time.\n */\nexport async function sleep(time: number): Promise\u003cnull\u003e {\n  return await new Promise((accept) =\u003e {\n    setTimeout(() =\u003e accept(null), time)\n  })\n}\n\n/**\n * Converts the provided async function into a retryable function. Each result\n * or thrown error is sent to the isRetryable function which should return true\n * if the function should run again.\n */\nexport function retryable\u003cT\u003e(\n  fn: (attempt: number) =\u003e Promise\u003cT\u003e,\n  isRetryable: (attempt: number, error: any | null, result?: T) =\u003e boolean\n): Promise\u003cT\u003e {\n  const promise = new Promise\u003cT\u003e((accept, reject) =\u003e {\n    // eslint-disable-next-line @typescript-eslint/no-extra-semi\n    ;(async () =\u003e {\n      for (let attempt = 0; attempt \u003c Infinity; attempt++) {\n        try {\n          const result = await fn(attempt)\n\n          if (!isRetryable(attempt, null, result)) {\n            accept(result)\n            return\n          }\n        } catch (e: any) {\n          if (!isRetryable(attempt, e)) {\n            reject(e)\n            return\n          }\n        }\n      }\n    })()\n  })\n\n  return promise\n}\n\nfunction dec2hex(dec: number) {\n  return ('0' + dec.toString(16)).substr(-2)\n}\n\n// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs\nexport function generatePKCEVerifier() {\n  const verifierLength = 56\n  const array = new Uint32Array(verifierLength)\n  if (typeof crypto === 'undefined') {\n    const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'\n    const charSetLen = charSet.length\n    let verifier = ''\n    for (let i = 0; i \u003c verifierLength; i++) {\n      verifier += charSet.charAt(Math.floor(Math.random() * charSetLen))\n    }\n    return verifier\n  }\n  crypto.getRandomValues(array)\n  return Array.from(array, dec2hex).join('')\n}\n\nasync function sha256(randomString: string) {\n  const encoder = new TextEncoder()\n  const encodedData = encoder.encode(randomString)\n  const hash = await crypto.subtle.digest('SHA-256', encodedData)\n  const bytes = new Uint8Array(hash)\n\n  return Array.from(bytes)\n    .map((c) =\u003e String.fromCharCode(c))\n    .join('')\n}\n\nfunction base64urlencode(str: string) {\n  return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nexport async function generatePKCEChallenge(verifier: string) {\n  const hasCryptoSupport =\n    typeof crypto !== 'undefined' \u0026\u0026\n    typeof crypto.subtle !== 'undefined' \u0026\u0026\n    typeof TextEncoder !== 'undefined'\n\n  if (!hasCryptoSupport) {\n    console.warn(\n      'WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'\n    )\n    return verifier\n  }\n  const hashed = await sha256(verifier)\n  return base64urlencode(hashed)\n}\n\nexport async function getCodeChallengeAndMethod(\n  storage: SupportedStorage,\n  storageKey: string,\n  isPasswordRecovery = false\n) {\n  const codeVerifier = generatePKCEVerifier()\n  let storedCodeVerifier = codeVerifier\n  if (isPasswordRecovery) {\n    storedCodeVerifier += '/PASSWORD_RECOVERY'\n  }\n  await setItemAsync(storage, `${storageKey}-code-verifier`, storedCodeVerifier)\n  const codeChallenge = await generatePKCEChallenge(codeVerifier)\n  const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'\n  return [codeChallenge, codeChallengeMethod]\n}\n\n/** Parses the API version which is 2YYY-MM-DD. */\nconst API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i\n\nexport function parseResponseAPIVersion(response: Response) {\n  const apiVersion = response.headers.get(API_VERSION_HEADER_NAME)\n\n  if (!apiVersion) {\n    return null\n  }\n\n  if (!apiVersion.match(API_VERSION_REGEX)) {\n    return null\n  }\n\n  try {\n    const date = new Date(`${apiVersion}T00:00:00.0Z`)\n    return date\n  } catch (e: any) {\n    return null\n  }\n}\n","import { WeakPasswordReasons } from './types'\nimport { ErrorCode } from './error-codes'\n\nexport class AuthError extends Error {\n  /**\n   * Error code associated with the error. Most errors coming from\n   * HTTP responses will have a code, though some errors that occur\n   * before a response is received will not have one present. In that\n   * case {@link #status} will also be undefined.\n   */\n  code: ErrorCode | string | undefined\n\n  /** HTTP status code that caused the error. */\n  status: number | undefined\n\n  protected __isAuthError = true\n\n  constructor(message: string, status?: number, code?: string) {\n    super(message)\n    this.name = 'AuthError'\n    this.status = status\n    this.code = code\n  }\n}\n\nexport function isAuthError(error: unknown): error is AuthError {\n  return typeof error === 'object' \u0026\u0026 error !== null \u0026\u0026 '__isAuthError' in error\n}\n\nexport class AuthApiError extends AuthError {\n  status: number\n\n  constructor(message: string, status: number, code: string | undefined) {\n    super(message, status, code)\n    this.name = 'AuthApiError'\n    this.status = status\n    this.code = code\n  }\n}\n\nexport function isAuthApiError(error: unknown): error is AuthApiError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthApiError'\n}\n\nexport class AuthUnknownError extends AuthError {\n  originalError: unknown\n\n  constructor(message: string, originalError: unknown) {\n    super(message)\n    this.name = 'AuthUnknownError'\n    this.originalError = originalError\n  }\n}\n\nexport class CustomAuthError extends AuthError {\n  name: string\n  status: number\n\n  constructor(message: string, name: string, status: number, code: string | undefined) {\n    super(message, status, code)\n    this.name = name\n    this.status = status\n  }\n}\n\nexport class AuthSessionMissingError extends CustomAuthError {\n  constructor() {\n    super('Auth session missing!', 'AuthSessionMissingError', 400, undefined)\n  }\n}\n\nexport function isAuthSessionMissingError(error: any): error is AuthSessionMissingError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthSessionMissingError'\n}\n\nexport class AuthInvalidTokenResponseError extends CustomAuthError {\n  constructor() {\n    super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined)\n  }\n}\n\nexport class AuthInvalidCredentialsError extends CustomAuthError {\n  constructor(message: string) {\n    super(message, 'AuthInvalidCredentialsError', 400, undefined)\n  }\n}\n\nexport class AuthImplicitGrantRedirectError extends CustomAuthError {\n  details: { error: string; code: string } | null = null\n  constructor(message: string, details: { error: string; code: string } | null = null) {\n    super(message, 'AuthImplicitGrantRedirectError', 500, undefined)\n    this.details = details\n  }\n\n  toJSON() {\n    return {\n      name: this.name,\n      message: this.message,\n      status: this.status,\n      details: this.details,\n    }\n  }\n}\n\nexport class AuthPKCEGrantCodeExchangeError extends CustomAuthError {\n  details: { error: string; code: string } | null = null\n\n  constructor(message: string, details: { error: string; code: string } | null = null) {\n    super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined)\n    this.details = details\n  }\n\n  toJSON() {\n    return {\n      name: this.name,\n      message: this.message,\n      status: this.status,\n      details: this.details,\n    }\n  }\n}\n\nexport class AuthRetryableFetchError extends CustomAuthError {\n  constructor(message: string, status: number) {\n    super(message, 'AuthRetryableFetchError', status, undefined)\n  }\n}\n\nexport function isAuthRetryableFetchError(error: unknown): error is AuthRetryableFetchError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthRetryableFetchError'\n}\n\n/**\n * This error is thrown on certain methods when the password used is deemed\n * weak. Inspect the reasons to identify what password strength rules are\n * inadequate.\n */\nexport class AuthWeakPasswordError extends CustomAuthError {\n  /**\n   * Reasons why the password is deemed weak.\n   */\n  reasons: WeakPasswordReasons[]\n\n  constructor(message: string, status: number, reasons: string[]) {\n    super(message, 'AuthWeakPasswordError', status, 'weak_password')\n\n    this.reasons = reasons\n  }\n}\n\nexport function isAuthWeakPasswordError(error: unknown): error is AuthWeakPasswordError {\n  return isAuthError(error) \u0026\u0026 error.name === 'AuthWeakPasswordError'\n}\n","import { API_VERSIONS, API_VERSION_HEADER_NAME } from './constants'\nimport { expiresAt, looksLikeFetchResponse, parseResponseAPIVersion } from './helpers'\nimport {\n  AuthResponse,\n  AuthResponsePassword,\n  SSOResponse,\n  GenerateLinkProperties,\n  GenerateLinkResponse,\n  User,\n  UserResponse,\n} from './types'\nimport {\n  AuthApiError,\n  AuthRetryableFetchError,\n  AuthWeakPasswordError,\n  AuthUnknownError,\n  AuthSessionMissingError,\n} from './errors'\n\nexport type Fetch = typeof fetch\n\nexport interface FetchOptions {\n  headers?: {\n    [key: string]: string\n  }\n  noResolveJson?: boolean\n}\n\nexport interface FetchParameters {\n  signal?: AbortSignal\n}\n\nexport type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'\n\nconst _getErrorMessage = (err: any): string =\u003e\n  err.msg || err.message || err.error_description || err.error || JSON.stringify(err)\n\nconst NETWORK_ERROR_CODES = [502, 503, 504]\n\nexport async function handleError(error: unknown) {\n  if (!looksLikeFetchResponse(error)) {\n    throw new AuthRetryableFetchError(_getErrorMessage(error), 0)\n  }\n\n  if (NETWORK_ERROR_CODES.includes(error.status)) {\n    // status in 500...599 range - server had an error, request might be retryed.\n    throw new AuthRetryableFetchError(_getErrorMessage(error), error.status)\n  }\n\n  let data: any\n  try {\n    data = await error.json()\n  } catch (e: any) {\n    throw new AuthUnknownError(_getErrorMessage(e), e)\n  }\n\n  let errorCode: string | undefined = undefined\n\n  const responseAPIVersion = parseResponseAPIVersion(error)\n  if (\n    responseAPIVersion \u0026\u0026\n    responseAPIVersion.getTime() \u003e= API_VERSIONS['2024-01-01'].timestamp \u0026\u0026\n    typeof data === 'object' \u0026\u0026\n    data \u0026\u0026\n    typeof data.code === 'string'\n  ) {\n    errorCode = data.code\n  } else if (typeof data === 'object' \u0026\u0026 data \u0026\u0026 typeof data.error_code === 'string') {\n    errorCode = data.error_code\n  }\n\n  if (!errorCode) {\n    // Legacy support for weak password errors, when there were no error codes\n    if (\n      typeof data === 'object' \u0026\u0026\n      data \u0026\u0026\n      typeof data.weak_password === 'object' \u0026\u0026\n      data.weak_password \u0026\u0026\n      Array.isArray(data.weak_password.reasons) \u0026\u0026\n      data.weak_password.reasons.length \u0026\u0026\n      data.weak_password.reasons.reduce((a: boolean, i: any) =\u003e a \u0026\u0026 typeof i === 'string', true)\n    ) {\n      throw new AuthWeakPasswordError(\n        _getErrorMessage(data),\n        error.status,\n        data.weak_password.reasons\n      )\n    }\n  } else if (errorCode === 'weak_password') {\n    throw new AuthWeakPasswordError(\n      _getErrorMessage(data),\n      error.status,\n      data.weak_password?.reasons || []\n    )\n  } else if (errorCode === 'session_not_found') {\n    // The `session_id` inside the JWT does not correspond to a row in the\n    // `sessions` table. This usually means the user has signed out, has been\n    // deleted, or their session has somehow been terminated.\n    throw new AuthSessionMissingError()\n  }\n\n  throw new AuthApiError(_getErrorMessage(data), error.status || 500, errorCode)\n}\n\nconst _getRequestParams = (\n  method: RequestMethodType,\n  options?: FetchOptions,\n  parameters?: FetchParameters,\n  body?: object\n) =\u003e {\n  const params: { [k: string]: any } = { method, headers: options?.headers || {} }\n\n  if (method === 'GET') {\n    return params\n  }\n\n  params.headers = { 'Content-Type': 'application/json;charset=UTF-8', ...options?.headers }\n  params.body = JSON.stringify(body)\n  return { ...params, ...parameters }\n}\n\ninterface GotrueRequestOptions extends FetchOptions {\n  jwt?: string\n  redirectTo?: string\n  body?: object\n  query?: { [key: string]: string }\n  /**\n   * Function that transforms api response from gotrue into a desirable / standardised format\n   */\n  xform?: (data: any) =\u003e any\n}\n\nexport async function _request(\n  fetcher: Fetch,\n  method: RequestMethodType,\n  url: string,\n  options?: GotrueRequestOptions\n) {\n  const headers = {\n    ...options?.headers,\n  }\n\n  if (!headers[API_VERSION_HEADER_NAME]) {\n    headers[API_VERSION_HEADER_NAME] = API_VERSIONS['2024-01-01'].name\n  }\n\n  if (options?.jwt) {\n    headers['Authorization'] = `Bearer ${options.jwt}`\n  }\n\n  const qs = options?.query ?? {}\n  if (options?.redirectTo) {\n    qs['redirect_to'] = options.redirectTo\n  }\n\n  const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''\n  const data = await _handleRequest(\n    fetcher,\n    method,\n    url + queryString,\n    {\n      headers,\n      noResolveJson: options?.noResolveJson,\n    },\n    {},\n    options?.body\n  )\n  return options?.xform ? options?.xform(data) : { data: { ...data }, error: null }\n}\n\nasync function _handleRequest(\n  fetcher: Fetch,\n  method: RequestMethodType,\n  url: string,\n  options?: FetchOptions,\n  parameters?: FetchParameters,\n  body?: object\n): Promise\u003cany\u003e {\n  const requestParams = _getRequestParams(method, options, parameters, body)\n\n  let result: any\n\n  try {\n    result = await fetcher(url, {\n      ...requestParams,\n    })\n  } catch (e) {\n    console.error(e)\n\n    // fetch failed, likely due to a network or CORS error\n    throw new AuthRetryableFetchError(_getErrorMessage(e), 0)\n  }\n\n  if (!result.ok) {\n    await handleError(result)\n  }\n\n  if (options?.noResolveJson) {\n    return result\n  }\n\n  try {\n    return await result.json()\n  } catch (e: any) {\n    await handleError(e)\n  }\n}\n\nexport function _sessionResponse(data: any): AuthResponse {\n  let session = null\n  if (hasSession(data)) {\n    session = { ...data }\n\n    if (!data.expires_at) {\n      session.expires_at = expiresAt(data.expires_in)\n    }\n  }\n\n  const user: User = data.user ?? (data as User)\n  return { data: { session, user }, error: null }\n}\n\nexport function _sessionResponsePassword(data: any): AuthResponsePassword {\n  const response = _sessionResponse(data) as AuthResponsePassword\n\n  if (\n    !response.error \u0026\u0026\n    data.weak_password \u0026\u0026\n    typeof data.weak_password === 'object' \u0026\u0026\n    Array.isArray(data.weak_password.reasons) \u0026\u0026\n    data.weak_password.reasons.length \u0026\u0026\n    data.weak_password.message \u0026\u0026\n    typeof data.weak_password.message === 'string' \u0026\u0026\n    data.weak_password.reasons.reduce((a: boolean, i: any) =\u003e a \u0026\u0026 typeof i === 'string', true)\n  ) {\n    response.data.weak_password = data.weak_password\n  }\n\n  return response\n}\n\nexport function _userResponse(data: any): UserResponse {\n  const user: User = data.user ?? (data as User)\n  return { data: { user }, error: null }\n}\n\nexport function _ssoResponse(data: any): SSOResponse {\n  return { data, error: null }\n}\n\nexport function _generateLinkResponse(data: any): GenerateLinkResponse {\n  const { action_link, email_otp, hashed_token, redirect_to, verification_type, ...rest } = data\n\n  const properties: GenerateLinkProperties = {\n    action_link,\n    email_otp,\n    hashed_token,\n    redirect_to,\n    verification_type,\n  }\n\n  const user: User = { ...rest }\n  return {\n    data: {\n      properties,\n      user,\n    },\n    error: null,\n  }\n}\n\nexport function _noResolveJsonResponse(data: any): Response {\n  return data\n}\n\n/**\n * hasSession checks if the response object contains a valid session\n * @param data A response object\n * @returns true if a session is in the response\n */\nfunction hasSession(data: any): boolean {\n  return data.access_token \u0026\u0026 data.refresh_token \u0026\u0026 data.expires_in\n}\n","import {\n  Fetch,\n  _generateLinkResponse,\n  _noResolveJsonResponse,\n  _request,\n  _userResponse,\n} from './lib/fetch'\nimport { resolveFetch } from './lib/helpers'\nimport {\n  AdminUserAttributes,\n  GenerateLinkParams,\n  GenerateLinkResponse,\n  Pagination,\n  User,\n  UserResponse,\n  GoTrueAdminMFAApi,\n  AuthMFAAdminDeleteFactorParams,\n  AuthMFAAdminDeleteFactorResponse,\n  AuthMFAAdminListFactorsParams,\n  AuthMFAAdminListFactorsResponse,\n  PageParams,\n} from './lib/types'\nimport { AuthError, isAuthError } from './lib/errors'\n\nexport default class GoTrueAdminApi {\n  /** Contains all MFA administration methods. */\n  mfa: GoTrueAdminMFAApi\n\n  protected url: string\n  protected headers: {\n    [key: string]: string\n  }\n  protected fetch: Fetch\n\n  constructor({\n    url = '',\n    headers = {},\n    fetch,\n  }: {\n    url: string\n    headers?: {\n      [key: string]: string\n    }\n    fetch?: Fetch\n  }) {\n    this.url = url\n    this.headers = headers\n    this.fetch = resolveFetch(fetch)\n    this.mfa = {\n      listFactors: this._listFactors.bind(this),\n      deleteFactor: this._deleteFactor.bind(this),\n    }\n  }\n\n  /**\n   * Removes a logged-in session.\n   * @param jwt A valid, logged-in JWT.\n   * @param scope The logout sope.\n   */\n  async signOut(\n    jwt: string,\n    scope: 'global' | 'local' | 'others' = 'global'\n  ): Promise\u003c{ data: null; error: AuthError | null }\u003e {\n    try {\n      await _request(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, {\n        headers: this.headers,\n        jwt,\n        noResolveJson: true,\n      })\n      return { data: null, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Sends an invite link to an email address.\n   * @param email The email address of the user.\n   * @param options Additional options to be included when inviting.\n   */\n  async inviteUserByEmail(\n    email: string,\n    options: {\n      /** A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column. */\n      data?: object\n\n      /** The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL. */\n      redirectTo?: string\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/invite`, {\n        body: { email, data: options.data },\n        headers: this.headers,\n        redirectTo: options.redirectTo,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Generates email links and OTPs to be sent via a custom email provider.\n   * @param email The user's email.\n   * @param options.password User password. For signup only.\n   * @param options.data Optional user metadata. For signup only.\n   * @param options.redirectTo The redirect url which should be appended to the generated link\n   */\n  async generateLink(params: GenerateLinkParams): Promise\u003cGenerateLinkResponse\u003e {\n    try {\n      const { options, ...rest } = params\n      const body: any = { ...rest, ...options }\n      if ('newEmail' in rest) {\n        // replace newEmail with new_email in request body\n        body.new_email = rest?.newEmail\n        delete body['newEmail']\n      }\n      return await _request(this.fetch, 'POST', `${this.url}/admin/generate_link`, {\n        body: body,\n        headers: this.headers,\n        xform: _generateLinkResponse,\n        redirectTo: options?.redirectTo,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return {\n          data: {\n            properties: null,\n            user: null,\n          },\n          error,\n        }\n      }\n      throw error\n    }\n  }\n\n  // User Admin API\n  /**\n   * Creates a new user.\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  async createUser(attributes: AdminUserAttributes): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/admin/users`, {\n        body: attributes,\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Get a list of users.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.\n   */\n  async listUsers(\n    params?: PageParams\n  ): Promise\u003c\n    | { data: { users: User[]; aud: string } \u0026 Pagination; error: null }\n    | { data: { users: [] }; error: AuthError }\n  \u003e {\n    try {\n      const pagination: Pagination = { nextPage: null, lastPage: 0, total: 0 }\n      const response = await _request(this.fetch, 'GET', `${this.url}/admin/users`, {\n        headers: this.headers,\n        noResolveJson: true,\n        query: {\n          page: params?.page?.toString() ?? '',\n          per_page: params?.perPage?.toString() ?? '',\n        },\n        xform: _noResolveJsonResponse,\n      })\n      if (response.error) throw response.error\n\n      const users = await response.json()\n      const total = response.headers.get('x-total-count') ?? 0\n      const links = response.headers.get('link')?.split(',') ?? []\n      if (links.length \u003e 0) {\n        links.forEach((link: string) =\u003e {\n          const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1))\n          const rel = JSON.parse(link.split(';')[1].split('=')[1])\n          pagination[`${rel}Page`] = page\n        })\n\n        pagination.total = parseInt(total)\n      }\n      return { data: { ...users, ...pagination }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { users: [] }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Get user by id.\n   *\n   * @param uid The user's unique identifier\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  async getUserById(uid: string): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, {\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Updates the user data.\n   *\n   * @param attributes The data you want to update.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  async updateUserById(uid: string, attributes: AdminUserAttributes): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, {\n        body: attributes,\n        headers: this.headers,\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Delete a user. Requires a `service_role` key.\n   *\n   * @param id The user id you want to remove.\n   * @param shouldSoftDelete If true, then the user will be soft-deleted (setting `deleted_at` to the current timestamp and disabling their account while preserving their data) from the auth schema.\n   * Defaults to false for backward compatibility.\n   *\n   * This function should only be called on a server. Never expose your `service_role` key in the browser.\n   */\n  async deleteUser(id: string, shouldSoftDelete = false): Promise\u003cUserResponse\u003e {\n    try {\n      return await _request(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, {\n        headers: this.headers,\n        body: {\n          should_soft_delete: shouldSoftDelete,\n        },\n        xform: _userResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  private async _listFactors(\n    params: AuthMFAAdminListFactorsParams\n  ): Promise\u003cAuthMFAAdminListFactorsResponse\u003e {\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'GET',\n        `${this.url}/admin/users/${params.userId}/factors`,\n        {\n          headers: this.headers,\n          xform: (factors: any) =\u003e {\n            return { data: { factors }, error: null }\n          },\n        }\n      )\n      return { data, error }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  private async _deleteFactor(\n    params: AuthMFAAdminDeleteFactorParams\n  ): Promise\u003cAuthMFAAdminDeleteFactorResponse\u003e {\n    try {\n      const data = await _request(\n        this.fetch,\n        'DELETE',\n        `${this.url}/admin/users/${params.userId}/factors/${params.id}`,\n        {\n          headers: this.headers,\n        }\n      )\n\n      return { data, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n}\n","import { supportsLocalStorage } from './helpers'\nimport { SupportedStorage } from './types'\n\n/**\n * Provides safe access to the globalThis.localStorage property.\n */\nexport const localStorageAdapter: SupportedStorage = {\n  getItem: (key) =\u003e {\n    if (!supportsLocalStorage()) {\n      return null\n    }\n\n    return globalThis.localStorage.getItem(key)\n  },\n  setItem: (key, value) =\u003e {\n    if (!supportsLocalStorage()) {\n      return\n    }\n\n    globalThis.localStorage.setItem(key, value)\n  },\n  removeItem: (key) =\u003e {\n    if (!supportsLocalStorage()) {\n      return\n    }\n\n    globalThis.localStorage.removeItem(key)\n  },\n}\n\n/**\n * Returns a localStorage-like object that stores the key-value pairs in\n * memory.\n */\nexport function memoryLocalStorageAdapter(store: { [key: string]: string } = {}): SupportedStorage {\n  return {\n    getItem: (key) =\u003e {\n      return store[key] || null\n    },\n\n    setItem: (key, value) =\u003e {\n      store[key] = value\n    },\n\n    removeItem: (key) =\u003e {\n      delete store[key]\n    },\n  }\n}\n","/**\n * https://mathiasbynens.be/notes/globalthis\n */\nexport function polyfillGlobalThis() {\n  if (typeof globalThis === 'object') return\n  try {\n    Object.defineProperty(Object.prototype, '__magic__', {\n      get: function () {\n        return this\n      },\n      configurable: true,\n    })\n    // @ts-expect-error 'Allow access to magic'\n    __magic__.globalThis = __magic__\n    // @ts-expect-error 'Allow access to magic'\n    delete Object.prototype.__magic__\n  } catch (e) {\n    if (typeof self !== 'undefined') {\n      // @ts-expect-error 'Allow access to globals'\n      self.globalThis = self\n    }\n  }\n}\n","import { supportsLocalStorage } from './helpers'\n\n/**\n * @experimental\n */\nexport const internals = {\n  /**\n   * @experimental\n   */\n  debug: !!(\n    globalThis \u0026\u0026\n    supportsLocalStorage() \u0026\u0026\n    globalThis.localStorage \u0026\u0026\n    globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'\n  ),\n}\n\n/**\n * An error thrown when a lock cannot be acquired after some amount of time.\n *\n * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`.\n */\nexport abstract class LockAcquireTimeoutError extends Error {\n  public readonly isAcquireTimeout = true\n\n  constructor(message: string) {\n    super(message)\n  }\n}\n\nexport class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError {}\n\n/**\n * Implements a global exclusive lock using the Navigator LockManager API. It\n * is available on all browsers released after 2022-03-15 with Safari being the\n * last one to release support. If the API is not available, this function will\n * throw. Make sure you check availablility before configuring {@link\n * GoTrueClient}.\n *\n * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug`\n * local storage item to `true`.\n *\n * Internals:\n *\n * Since the LockManager API does not preserve stack traces for the async\n * function passed in the `request` method, a trick is used where acquiring the\n * lock releases a previously started promise to run the operation in the `fn`\n * function. The lock waits for that promise to finish (with or without error),\n * while the function will finally wait for the result anyway.\n *\n * @param name Name of the lock to be acquired.\n * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if\n *                       the lock can't be acquired without waiting. If positive, the lock acquire\n *                       will time out after so many milliseconds. An error is\n *                       a timeout if it has `isAcquireTimeout` set to true.\n * @param fn The operation to run once the lock is acquired.\n */\nexport async function navigatorLock\u003cR\u003e(\n  name: string,\n  acquireTimeout: number,\n  fn: () =\u003e Promise\u003cR\u003e\n): Promise\u003cR\u003e {\n  if (internals.debug) {\n    console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout)\n  }\n\n  const abortController = new globalThis.AbortController()\n\n  if (acquireTimeout \u003e 0) {\n    setTimeout(() =\u003e {\n      abortController.abort()\n      if (internals.debug) {\n        console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name)\n      }\n    }, acquireTimeout)\n  }\n\n  // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request\n\n  return await globalThis.navigator.locks.request(\n    name,\n    acquireTimeout === 0\n      ? {\n          mode: 'exclusive',\n          ifAvailable: true,\n        }\n      : {\n          mode: 'exclusive',\n          signal: abortController.signal,\n        },\n    async (lock) =\u003e {\n      if (lock) {\n        if (internals.debug) {\n          console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name)\n        }\n\n        try {\n          return await fn()\n        } finally {\n          if (internals.debug) {\n            console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name)\n          }\n        }\n      } else {\n        if (acquireTimeout === 0) {\n          if (internals.debug) {\n            console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name)\n          }\n\n          throw new NavigatorLockAcquireTimeoutError(\n            `Acquiring an exclusive Navigator LockManager lock \"${name}\" immediately failed`\n          )\n        } else {\n          if (internals.debug) {\n            try {\n              const result = await globalThis.navigator.locks.query()\n\n              console.log(\n                '@supabase/gotrue-js: Navigator LockManager state',\n                JSON.stringify(result, null, '  ')\n              )\n            } catch (e: any) {\n              console.warn(\n                '@supabase/gotrue-js: Error when querying Navigator LockManager state',\n                e\n              )\n            }\n          }\n\n          // Browser is not following the Navigator LockManager spec, it\n          // returned a null lock when we didn't use ifAvailable. So we can\n          // pretend the lock is acquired in the name of backward compatibility\n          // and user experience and just run the function.\n          console.warn(\n            '@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'\n          )\n\n          return await fn()\n        }\n      }\n    }\n  )\n}\n","import GoTrueAdminApi from './GoTrueAdminApi'\nimport { DEFAULT_HEADERS, EXPIRY_MARGIN, GOTRUE_URL, STORAGE_KEY } from './lib/constants'\nimport {\n  AuthError,\n  AuthImplicitGrantRedirectError,\n  AuthPKCEGrantCodeExchangeError,\n  AuthInvalidCredentialsError,\n  AuthSessionMissingError,\n  AuthInvalidTokenResponseError,\n  AuthUnknownError,\n  isAuthApiError,\n  isAuthError,\n  isAuthRetryableFetchError,\n  isAuthSessionMissingError,\n} from './lib/errors'\nimport {\n  Fetch,\n  _request,\n  _sessionResponse,\n  _sessionResponsePassword,\n  _userResponse,\n  _ssoResponse,\n} from './lib/fetch'\nimport {\n  decodeJWTPayload,\n  Deferred,\n  getItemAsync,\n  isBrowser,\n  removeItemAsync,\n  resolveFetch,\n  setItemAsync,\n  uuid,\n  retryable,\n  sleep,\n  supportsLocalStorage,\n  parseParametersFromURL,\n  getCodeChallengeAndMethod,\n} from './lib/helpers'\nimport { localStorageAdapter, memoryLocalStorageAdapter } from './lib/local-storage'\nimport { polyfillGlobalThis } from './lib/polyfills'\nimport { version } from './lib/version'\nimport { LockAcquireTimeoutError, navigatorLock } from './lib/locks'\n\nimport type {\n  AuthChangeEvent,\n  AuthResponse,\n  AuthResponsePassword,\n  AuthTokenResponse,\n  AuthTokenResponsePassword,\n  AuthOtpResponse,\n  CallRefreshTokenResult,\n  GoTrueClientOptions,\n  InitializeResult,\n  OAuthResponse,\n  SSOResponse,\n  Provider,\n  Session,\n  SignInWithIdTokenCredentials,\n  SignInWithOAuthCredentials,\n  SignInWithPasswordCredentials,\n  SignInWithPasswordlessCredentials,\n  SignUpWithPasswordCredentials,\n  SignInWithSSO,\n  SignOut,\n  Subscription,\n  SupportedStorage,\n  User,\n  UserAttributes,\n  UserResponse,\n  VerifyOtpParams,\n  GoTrueMFAApi,\n  MFAEnrollParams,\n  AuthMFAEnrollResponse,\n  MFAChallengeParams,\n  AuthMFAChallengeResponse,\n  MFAUnenrollParams,\n  AuthMFAUnenrollResponse,\n  MFAVerifyParams,\n  AuthMFAVerifyResponse,\n  AuthMFAListFactorsResponse,\n  AMREntry,\n  AuthMFAGetAuthenticatorAssuranceLevelResponse,\n  AuthenticatorAssuranceLevels,\n  Factor,\n  MFAChallengeAndVerifyParams,\n  ResendParams,\n  AuthFlowType,\n  LockFunc,\n  UserIdentity,\n  SignInAnonymouslyCredentials,\n} from './lib/types'\n\npolyfillGlobalThis() // Make \"globalThis\" available\n\nconst DEFAULT_OPTIONS: Omit\u003cRequired\u003cGoTrueClientOptions\u003e, 'fetch' | 'storage' | 'lock'\u003e = {\n  url: GOTRUE_URL,\n  storageKey: STORAGE_KEY,\n  autoRefreshToken: true,\n  persistSession: true,\n  detectSessionInUrl: true,\n  headers: DEFAULT_HEADERS,\n  flowType: 'implicit',\n  debug: false,\n  hasCustomAuthorizationHeader: false,\n}\n\n/** Current session will be checked for refresh at this interval. */\nconst AUTO_REFRESH_TICK_DURATION = 30 * 1000\n\n/**\n * A token refresh will be attempted this many ticks before the current session expires. */\nconst AUTO_REFRESH_TICK_THRESHOLD = 3\n\nasync function lockNoOp\u003cR\u003e(name: string, acquireTimeout: number, fn: () =\u003e Promise\u003cR\u003e): Promise\u003cR\u003e {\n  return await fn()\n}\n\nexport default class GoTrueClient {\n  private static nextInstanceID = 0\n\n  private instanceID: number\n\n  /**\n   * Namespace for the GoTrue admin methods.\n   * These methods should only be used in a trusted server-side environment.\n   */\n  admin: GoTrueAdminApi\n  /**\n   * Namespace for the MFA methods.\n   */\n  mfa: GoTrueMFAApi\n  /**\n   * The storage key used to identify the values saved in localStorage\n   */\n  protected storageKey: string\n\n  protected flowType: AuthFlowType\n\n  protected autoRefreshToken: boolean\n  protected persistSession: boolean\n  protected storage: SupportedStorage\n  protected memoryStorage: { [key: string]: string } | null = null\n  protected stateChangeEmitters: Map\u003cstring, Subscription\u003e = new Map()\n  protected autoRefreshTicker: ReturnType\u003ctypeof setInterval\u003e | null = null\n  protected visibilityChangedCallback: (() =\u003e Promise\u003cany\u003e) | null = null\n  protected refreshingDeferred: Deferred\u003cCallRefreshTokenResult\u003e | null = null\n  /**\n   * Keeps track of the async client initialization.\n   * When null or not yet resolved the auth state is `unknown`\n   * Once resolved the the auth state is known and it's save to call any further client methods.\n   * Keep extra care to never reject or throw uncaught errors\n   */\n  protected initializePromise: Promise\u003cInitializeResult\u003e | null = null\n  protected detectSessionInUrl = true\n  protected url: string\n  protected headers: {\n    [key: string]: string\n  }\n  protected hasCustomAuthorizationHeader = false\n  protected suppressGetSessionWarning = false\n  protected fetch: Fetch\n  protected lock: LockFunc\n  protected lockAcquired = false\n  protected pendingInLock: Promise\u003cany\u003e[] = []\n\n  /**\n   * Used to broadcast state change events to other tabs listening.\n   */\n  protected broadcastChannel: BroadcastChannel | null = null\n\n  protected logDebugMessages: boolean\n  protected logger: (message: string, ...args: any[]) =\u003e void = console.log\n\n  /**\n   * Create a new client for use in the browser.\n   */\n  constructor(options: GoTrueClientOptions) {\n    this.instanceID = GoTrueClient.nextInstanceID\n    GoTrueClient.nextInstanceID += 1\n\n    if (this.instanceID \u003e 0 \u0026\u0026 isBrowser()) {\n      console.warn(\n        'Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'\n      )\n    }\n\n    const settings = { ...DEFAULT_OPTIONS, ...options }\n\n    this.logDebugMessages = !!settings.debug\n    if (typeof settings.debug === 'function') {\n      this.logger = settings.debug\n    }\n\n    this.persistSession = settings.persistSession\n    this.storageKey = settings.storageKey\n    this.autoRefreshToken = settings.autoRefreshToken\n    this.admin = new GoTrueAdminApi({\n      url: settings.url,\n      headers: settings.headers,\n      fetch: settings.fetch,\n    })\n\n    this.url = settings.url\n    this.headers = settings.headers\n    this.fetch = resolveFetch(settings.fetch)\n    this.lock = settings.lock || lockNoOp\n    this.detectSessionInUrl = settings.detectSessionInUrl\n    this.flowType = settings.flowType\n    this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader\n\n    if (settings.lock) {\n      this.lock = settings.lock\n    } else if (isBrowser() \u0026\u0026 globalThis?.navigator?.locks) {\n      this.lock = navigatorLock\n    } else {\n      this.lock = lockNoOp\n    }\n\n    this.mfa = {\n      verify: this._verify.bind(this),\n      enroll: this._enroll.bind(this),\n      unenroll: this._unenroll.bind(this),\n      challenge: this._challenge.bind(this),\n      listFactors: this._listFactors.bind(this),\n      challengeAndVerify: this._challengeAndVerify.bind(this),\n      getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),\n    }\n\n    if (this.persistSession) {\n      if (settings.storage) {\n        this.storage = settings.storage\n      } else {\n        if (supportsLocalStorage()) {\n          this.storage = localStorageAdapter\n        } else {\n          this.memoryStorage = {}\n          this.storage = memoryLocalStorageAdapter(this.memoryStorage)\n        }\n      }\n    } else {\n      this.memoryStorage = {}\n      this.storage = memoryLocalStorageAdapter(this.memoryStorage)\n    }\n\n    if (isBrowser() \u0026\u0026 globalThis.BroadcastChannel \u0026\u0026 this.persistSession \u0026\u0026 this.storageKey) {\n      try {\n        this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey)\n      } catch (e: any) {\n        console.error(\n          'Failed to create a new BroadcastChannel, multi-tab state changes will not be available',\n          e\n        )\n      }\n\n      this.broadcastChannel?.addEventListener('message', async (event) =\u003e {\n        this._debug('received broadcast notification from other tab or client', event)\n\n        await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages\n      })\n    }\n\n    this.initialize()\n  }\n\n  private _debug(...args: any[]): GoTrueClient {\n    if (this.logDebugMessages) {\n      this.logger(\n        `GoTrueClient@${this.instanceID} (${version}) ${new Date().toISOString()}`,\n        ...args\n      )\n    }\n\n    return this\n  }\n\n  /**\n   * Initializes the client session either from the url or from storage.\n   * This method is automatically called when instantiating the client, but should also be called\n   * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).\n   */\n  async initialize(): Promise\u003cInitializeResult\u003e {\n    if (this.initializePromise) {\n      return await this.initializePromise\n    }\n\n    this.initializePromise = (async () =\u003e {\n      return await this._acquireLock(-1, async () =\u003e {\n        return await this._initialize()\n      })\n    })()\n\n    return await this.initializePromise\n  }\n\n  /**\n   * IMPORTANT:\n   * 1. Never throw in this method, as it is called from the constructor\n   * 2. Never return a session from this method as it would be cached over\n   *    the whole lifetime of the client\n   */\n  private async _initialize(): Promise\u003cInitializeResult\u003e {\n    try {\n      const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false\n      this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow)\n\n      if (isPKCEFlow || (this.detectSessionInUrl \u0026\u0026 this._isImplicitGrantFlow())) {\n        const { data, error } = await this._getSessionFromURL(isPKCEFlow)\n        if (error) {\n          this._debug('#_initialize()', 'error detecting session from URL', error)\n\n          // hacky workaround to keep the existing session if there's an error returned from identity linking\n          // TODO: once error codes are ready, we should match against it instead of the message\n          if (\n            error?.message === 'Identity is already linked' ||\n            error?.message === 'Identity is already linked to another user'\n          ) {\n            return { error }\n          }\n\n          // failed login attempt via url,\n          // remove old session as in verifyOtp, signUp and signInWith*\n          await this._removeSession()\n\n          return { error }\n        }\n\n        const { session, redirectType } = data\n\n        this._debug(\n          '#_initialize()',\n          'detected session in URL',\n          session,\n          'redirect type',\n          redirectType\n        )\n\n        await this._saveSession(session)\n\n        setTimeout(async () =\u003e {\n          if (redirectType === 'recovery') {\n            await this._notifyAllSubscribers('PASSWORD_RECOVERY', session)\n          } else {\n            await this._notifyAllSubscribers('SIGNED_IN', session)\n          }\n        }, 0)\n\n        return { error: null }\n      }\n      // no login attempt via callback url try to recover session from storage\n      await this._recoverAndRefresh()\n      return { error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { error }\n      }\n\n      return {\n        error: new AuthUnknownError('Unexpected error during initialization', error),\n      }\n    } finally {\n      await this._handleVisibilityChange()\n      this._debug('#_initialize()', 'end')\n    }\n  }\n\n  /**\n   * Creates a new anonymous user.\n   *\n   * @returns A session where the is_anonymous claim in the access token JWT set to true\n   */\n  async signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise\u003cAuthResponse\u003e {\n    try {\n      const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n        headers: this.headers,\n        body: {\n          data: credentials?.options?.data ?? {},\n          gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken },\n        },\n        xform: _sessionResponse,\n      })\n      const { data, error } = res\n\n      if (error || !data) {\n        return { data: { user: null, session: null }, error: error }\n      }\n      const session: Session | null = data.session\n      const user: User | null = data.user\n\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return { data: { user, session }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Creates a new user.\n   *\n   * Be aware that if a user account exists in the system you may get back an\n   * error message that attempts to hide this information from the user.\n   * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.\n   *\n   * @returns A logged-in session if the server has \"autoconfirm\" ON\n   * @returns A user if the server has \"autoconfirm\" OFF\n   */\n  async signUp(credentials: SignUpWithPasswordCredentials): Promise\u003cAuthResponse\u003e {\n    try {\n      let res: AuthResponse\n      if ('email' in credentials) {\n        const { email, password, options } = credentials\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce') {\n          ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n            this.storage,\n            this.storageKey\n          )\n        }\n        res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n          headers: this.headers,\n          redirectTo: options?.emailRedirectTo,\n          body: {\n            email,\n            password,\n            data: options?.data ?? {},\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          xform: _sessionResponse,\n        })\n      } else if ('phone' in credentials) {\n        const { phone, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/signup`, {\n          headers: this.headers,\n          body: {\n            phone,\n            password,\n            data: options?.data ?? {},\n            channel: options?.channel ?? 'sms',\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponse,\n        })\n      } else {\n        throw new AuthInvalidCredentialsError(\n          'You must provide either an email or phone number and a password'\n        )\n      }\n\n      const { data, error } = res\n\n      if (error || !data) {\n        return { data: { user: null, session: null }, error: error }\n      }\n\n      const session: Session | null = data.session\n      const user: User | null = data.user\n\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return { data: { user, session }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Log in an existing user with an email and password or phone and password.\n   *\n   * Be aware that you may get back an error message that will not distinguish\n   * between the cases where the account does not exist or that the\n   * email/phone and password combination is wrong or that the account can only\n   * be accessed via social login.\n   */\n  async signInWithPassword(\n    credentials: SignInWithPasswordCredentials\n  ): Promise\u003cAuthTokenResponsePassword\u003e {\n    try {\n      let res: AuthResponsePassword\n      if ('email' in credentials) {\n        const { email, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n          headers: this.headers,\n          body: {\n            email,\n            password,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponsePassword,\n        })\n      } else if ('phone' in credentials) {\n        const { phone, password, options } = credentials\n        res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {\n          headers: this.headers,\n          body: {\n            phone,\n            password,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          xform: _sessionResponsePassword,\n        })\n      } else {\n        throw new AuthInvalidCredentialsError(\n          'You must provide either an email or phone number and a password'\n        )\n      }\n      const { data, error } = res\n\n      if (error) {\n        return { data: { user: null, session: null }, error }\n      } else if (!data || !data.session || !data.user) {\n        return { data: { user: null, session: null }, error: new AuthInvalidTokenResponseError() }\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return {\n        data: {\n          user: data.user,\n          session: data.session,\n          ...(data.weak_password ? { weakPassword: data.weak_password } : null),\n        },\n        error,\n      }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Log in an existing user via a third-party provider.\n   * This method supports the PKCE flow.\n   */\n  async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise\u003cOAuthResponse\u003e {\n    return await this._handleProviderSignIn(credentials.provider, {\n      redirectTo: credentials.options?.redirectTo,\n      scopes: credentials.options?.scopes,\n      queryParams: credentials.options?.queryParams,\n      skipBrowserRedirect: credentials.options?.skipBrowserRedirect,\n    })\n  }\n\n  /**\n   * Log in an existing user by exchanging an Auth Code issued during the PKCE flow.\n   */\n  async exchangeCodeForSession(authCode: string): Promise\u003cAuthTokenResponse\u003e {\n    await this.initializePromise\n\n    return this._acquireLock(-1, async () =\u003e {\n      return this._exchangeCodeForSession(authCode)\n    })\n  }\n\n  private async _exchangeCodeForSession(authCode: string): Promise\u003c\n    | {\n        data: { session: Session; user: User; redirectType: string | null }\n        error: null\n      }\n    | { data: { session: null; user: null; redirectType: null }; error: AuthError }\n  \u003e {\n    const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n    const [codeVerifier, redirectType] = ((storageItem ?? '') as string).split('/')\n\n    try {\n      const { data, error } = await _request(\n        this.fetch,\n        'POST',\n        `${this.url}/token?grant_type=pkce`,\n        {\n          headers: this.headers,\n          body: {\n            auth_code: authCode,\n            code_verifier: codeVerifier,\n          },\n          xform: _sessionResponse,\n        }\n      )\n      await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n      if (error) {\n        throw error\n      }\n      if (!data || !data.session || !data.user) {\n        return {\n          data: { user: null, session: null, redirectType: null },\n          error: new AuthInvalidTokenResponseError(),\n        }\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return { data: { ...data, redirectType: redirectType ?? null }, error }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null, redirectType: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Allows signing in with an OIDC ID token. The authentication provider used\n   * should be enabled and configured.\n   */\n  async signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise\u003cAuthTokenResponse\u003e {\n    try {\n      const { options, provider, token, access_token, nonce } = credentials\n\n      const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {\n        headers: this.headers,\n        body: {\n          provider,\n          id_token: token,\n          access_token,\n          nonce,\n          gotrue_meta_security: { captcha_token: options?.captchaToken },\n        },\n        xform: _sessionResponse,\n      })\n\n      const { data, error } = res\n      if (error) {\n        return { data: { user: null, session: null }, error }\n      } else if (!data || !data.session || !data.user) {\n        return {\n          data: { user: null, session: null },\n          error: new AuthInvalidTokenResponseError(),\n        }\n      }\n      if (data.session) {\n        await this._saveSession(data.session)\n        await this._notifyAllSubscribers('SIGNED_IN', data.session)\n      }\n      return { data, error }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Log in a user using magiclink or a one-time password (OTP).\n   *\n   * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.\n   * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.\n   * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.\n   *\n   * Be aware that you may get back an error message that will not distinguish\n   * between the cases where the account does not exist or, that the account\n   * can only be accessed via social login.\n   *\n   * Do note that you will need to configure a Whatsapp sender on Twilio\n   * if you are using phone sign in with the 'whatsapp' channel. The whatsapp\n   * channel is not supported on other providers\n   * at this time.\n   * This method supports PKCE when an email is passed.\n   */\n  async signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise\u003cAuthOtpResponse\u003e {\n    try {\n      if ('email' in credentials) {\n        const { email, options } = credentials\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce') {\n          ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n            this.storage,\n            this.storageKey\n          )\n        }\n        const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n          headers: this.headers,\n          body: {\n            email,\n            data: options?.data ?? {},\n            create_user: options?.shouldCreateUser ?? true,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          redirectTo: options?.emailRedirectTo,\n        })\n        return { data: { user: null, session: null }, error }\n      }\n      if ('phone' in credentials) {\n        const { phone, options } = credentials\n        const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {\n          headers: this.headers,\n          body: {\n            phone,\n            data: options?.data ?? {},\n            create_user: options?.shouldCreateUser ?? true,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n            channel: options?.channel ?? 'sms',\n          },\n        })\n        return { data: { user: null, session: null, messageId: data?.message_id }, error }\n      }\n      throw new AuthInvalidCredentialsError('You must provide either an email or phone number.')\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Log in a user given a User supplied OTP or TokenHash received through mobile or email.\n   */\n  async verifyOtp(params: VerifyOtpParams): Promise\u003cAuthResponse\u003e {\n    try {\n      let redirectTo: string | undefined = undefined\n      let captchaToken: string | undefined = undefined\n      if ('options' in params) {\n        redirectTo = params.options?.redirectTo\n        captchaToken = params.options?.captchaToken\n      }\n      const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {\n        headers: this.headers,\n        body: {\n          ...params,\n          gotrue_meta_security: { captcha_token: captchaToken },\n        },\n        redirectTo,\n        xform: _sessionResponse,\n      })\n\n      if (error) {\n        throw error\n      }\n\n      if (!data) {\n        throw new Error('An error occurred on token verification.')\n      }\n\n      const session: Session | null = data.session\n      const user: User = data.user\n\n      if (session?.access_token) {\n        await this._saveSession(session as Session)\n        await this._notifyAllSubscribers(\n          params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN',\n          session\n        )\n      }\n\n      return { data: { user, session }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Attempts a single-sign on using an enterprise Identity Provider. A\n   * successful SSO attempt will redirect the current page to the identity\n   * provider authorization page. The redirect URL is implementation and SSO\n   * protocol specific.\n   *\n   * You can use it by providing a SSO domain. Typically you can extract this\n   * domain by asking users for their email address. If this domain is\n   * registered on the Auth instance the redirect will use that organization's\n   * currently active SSO Identity Provider for the login.\n   *\n   * If you have built an organization-specific login page, you can use the\n   * organization's SSO Identity Provider UUID directly instead.\n   */\n  async signInWithSSO(params: SignInWithSSO): Promise\u003cSSOResponse\u003e {\n    try {\n      let codeChallenge: string | null = null\n      let codeChallengeMethod: string | null = null\n      if (this.flowType === 'pkce') {\n        ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n          this.storage,\n          this.storageKey\n        )\n      }\n\n      return await _request(this.fetch, 'POST', `${this.url}/sso`, {\n        body: {\n          ...('providerId' in params ? { provider_id: params.providerId } : null),\n          ...('domain' in params ? { domain: params.domain } : null),\n          redirect_to: params.options?.redirectTo ?? undefined,\n          ...(params?.options?.captchaToken\n            ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }\n            : null),\n          skip_http_redirect: true, // fetch does not handle redirects\n          code_challenge: codeChallenge,\n          code_challenge_method: codeChallengeMethod,\n        },\n        headers: this.headers,\n        xform: _ssoResponse,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Sends a reauthentication OTP to the user's email or phone number.\n   * Requires the user to be signed-in.\n   */\n  async reauthenticate(): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    return await this._acquireLock(-1, async () =\u003e {\n      return await this._reauthenticate()\n    })\n  }\n\n  private async _reauthenticate(): Promise\u003cAuthResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) throw sessionError\n        if (!session) throw new AuthSessionMissingError()\n\n        const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {\n          headers: this.headers,\n          jwt: session.access_token,\n        })\n        return { data: { user: null, session: null }, error }\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.\n   */\n  async resend(credentials: ResendParams): Promise\u003cAuthOtpResponse\u003e {\n    try {\n      const endpoint = `${this.url}/resend`\n      if ('email' in credentials) {\n        const { email, type, options } = credentials\n        const { error } = await _request(this.fetch, 'POST', endpoint, {\n          headers: this.headers,\n          body: {\n            email,\n            type,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n          redirectTo: options?.emailRedirectTo,\n        })\n        return { data: { user: null, session: null }, error }\n      } else if ('phone' in credentials) {\n        const { phone, type, options } = credentials\n        const { data, error } = await _request(this.fetch, 'POST', endpoint, {\n          headers: this.headers,\n          body: {\n            phone,\n            type,\n            gotrue_meta_security: { captcha_token: options?.captchaToken },\n          },\n        })\n        return { data: { user: null, session: null, messageId: data?.message_id }, error }\n      }\n      throw new AuthInvalidCredentialsError(\n        'You must provide either an email or phone number and a type'\n      )\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Returns the session, refreshing it if necessary.\n   *\n   * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.\n   *\n   * **IMPORTANT:** This method loads values directly from the storage attached\n   * to the client. If that storage is based on request cookies for example,\n   * the values in it may not be authentic and therefore it's strongly advised\n   * against using this method and its results in such circumstances. A warning\n   * will be emitted if this is detected. Use {@link #getUser()} instead.\n   */\n  async getSession() {\n    await this.initializePromise\n\n    const result = await this._acquireLock(-1, async () =\u003e {\n      return this._useSession(async (result) =\u003e {\n        return result\n      })\n    })\n\n    return result\n  }\n\n  /**\n   * Acquires a global lock based on the storage key.\n   */\n  private async _acquireLock\u003cR\u003e(acquireTimeout: number, fn: () =\u003e Promise\u003cR\u003e): Promise\u003cR\u003e {\n    this._debug('#_acquireLock', 'begin', acquireTimeout)\n\n    try {\n      if (this.lockAcquired) {\n        const last = this.pendingInLock.length\n          ? this.pendingInLock[this.pendingInLock.length - 1]\n          : Promise.resolve()\n\n        const result = (async () =\u003e {\n          await last\n          return await fn()\n        })()\n\n        this.pendingInLock.push(\n          (async () =\u003e {\n            try {\n              await result\n            } catch (e: any) {\n              // we just care if it finished\n            }\n          })()\n        )\n\n        return result\n      }\n\n      return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () =\u003e {\n        this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey)\n\n        try {\n          this.lockAcquired = true\n\n          const result = fn()\n\n          this.pendingInLock.push(\n            (async () =\u003e {\n              try {\n                await result\n              } catch (e: any) {\n                // we just care if it finished\n              }\n            })()\n          )\n\n          await result\n\n          // keep draining the queue until there's nothing to wait on\n          while (this.pendingInLock.length) {\n            const waitOn = [...this.pendingInLock]\n\n            await Promise.all(waitOn)\n\n            this.pendingInLock.splice(0, waitOn.length)\n          }\n\n          return await result\n        } finally {\n          this._debug('#_acquireLock', 'lock released for storage key', this.storageKey)\n\n          this.lockAcquired = false\n        }\n      })\n    } finally {\n      this._debug('#_acquireLock', 'end')\n    }\n  }\n\n  /**\n   * Use instead of {@link #getSession} inside the library. It is\n   * semantically usually what you want, as getting a session involves some\n   * processing afterwards that requires only one client operating on the\n   * session at once across multiple tabs or processes.\n   */\n  private async _useSession\u003cR\u003e(\n    fn: (\n      result:\n        | {\n            data: {\n              session: Session\n            }\n            error: null\n          }\n        | {\n            data: {\n              session: null\n            }\n            error: AuthError\n          }\n        | {\n            data: {\n              session: null\n            }\n            error: null\n          }\n    ) =\u003e Promise\u003cR\u003e\n  ): Promise\u003cR\u003e {\n    this._debug('#_useSession', 'begin')\n\n    try {\n      // the use of __loadSession here is the only correct use of the function!\n      const result = await this.__loadSession()\n\n      return await fn(result)\n    } finally {\n      this._debug('#_useSession', 'end')\n    }\n  }\n\n  /**\n   * NEVER USE DIRECTLY!\n   *\n   * Always use {@link #_useSession}.\n   */\n  private async __loadSession(): Promise\u003c\n    | {\n        data: {\n          session: Session\n        }\n        error: null\n      }\n    | {\n        data: {\n          session: null\n        }\n        error: AuthError\n      }\n    | {\n        data: {\n          session: null\n        }\n        error: null\n      }\n  \u003e {\n    this._debug('#__loadSession()', 'begin')\n\n    if (!this.lockAcquired) {\n      this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack)\n    }\n\n    try {\n      let currentSession: Session | null = null\n\n      const maybeSession = await getItemAsync(this.storage, this.storageKey)\n\n      this._debug('#getSession()', 'session from storage', maybeSession)\n\n      if (maybeSession !== null) {\n        if (this._isValidSession(maybeSession)) {\n          currentSession = maybeSession\n        } else {\n          this._debug('#getSession()', 'session from storage is not valid')\n          await this._removeSession()\n        }\n      }\n\n      if (!currentSession) {\n        return { data: { session: null }, error: null }\n      }\n\n      const hasExpired = currentSession.expires_at\n        ? currentSession.expires_at \u003c= Date.now() / 1000\n        : false\n\n      this._debug(\n        '#__loadSession()',\n        `session has${hasExpired ? '' : ' not'} expired`,\n        'expires_at',\n        currentSession.expires_at\n      )\n\n      if (!hasExpired) {\n        if (this.storage.isServer) {\n          let suppressWarning = this.suppressGetSessionWarning\n          const proxySession: Session = new Proxy(currentSession, {\n            get: (target: any, prop: string, receiver: any) =\u003e {\n              if (!suppressWarning \u0026\u0026 prop === 'user') {\n                // only show warning when the user object is being accessed from the server\n                console.warn(\n                  'Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'\n                )\n                suppressWarning = true // keeps this proxy instance from logging additional warnings\n                this.suppressGetSessionWarning = true // keeps this client's future proxy instances from warning\n              }\n              return Reflect.get(target, prop, receiver)\n            },\n          })\n          currentSession = proxySession\n        }\n\n        return { data: { session: currentSession }, error: null }\n      }\n\n      const { session, error } = await this._callRefreshToken(currentSession.refresh_token)\n      if (error) {\n        return { data: { session: null }, error }\n      }\n\n      return { data: { session }, error: null }\n    } finally {\n      this._debug('#__loadSession()', 'end')\n    }\n  }\n\n  /**\n   * Gets the current user details if there is an existing session. This method\n   * performs a network request to the Supabase Auth server, so the returned\n   * value is authentic and can be used to base authorization rules on.\n   *\n   * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.\n   */\n  async getUser(jwt?: string): Promise\u003cUserResponse\u003e {\n    if (jwt) {\n      return await this._getUser(jwt)\n    }\n\n    await this.initializePromise\n\n    const result = await this._acquireLock(-1, async () =\u003e {\n      return await this._getUser()\n    })\n\n    return result\n  }\n\n  private async _getUser(jwt?: string): Promise\u003cUserResponse\u003e {\n    try {\n      if (jwt) {\n        return await _request(this.fetch, 'GET', `${this.url}/user`, {\n          headers: this.headers,\n          jwt: jwt,\n          xform: _userResponse,\n        })\n      }\n\n      return await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) {\n          throw error\n        }\n\n        // returns an error if there is no access_token or custom authorization header\n        if (!data.session?.access_token \u0026\u0026 !this.hasCustomAuthorizationHeader) {\n          return { data: { user: null }, error: new AuthSessionMissingError() }\n        }\n\n        return await _request(this.fetch, 'GET', `${this.url}/user`, {\n          headers: this.headers,\n          jwt: data.session?.access_token ?? undefined,\n          xform: _userResponse,\n        })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        if (isAuthSessionMissingError(error)) {\n          // JWT contains a `session_id` which does not correspond to an active\n          // session in the database, indicating the user is signed out.\n\n          await this._removeSession()\n          await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n          await this._notifyAllSubscribers('SIGNED_OUT', null)\n        }\n\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Updates user data for a logged in user.\n   */\n  async updateUser(\n    attributes: UserAttributes,\n    options: {\n      emailRedirectTo?: string | undefined\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    await this.initializePromise\n\n    return await this._acquireLock(-1, async () =\u003e {\n      return await this._updateUser(attributes, options)\n    })\n  }\n\n  protected async _updateUser(\n    attributes: UserAttributes,\n    options: {\n      emailRedirectTo?: string | undefined\n    } = {}\n  ): Promise\u003cUserResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          throw sessionError\n        }\n        if (!sessionData.session) {\n          throw new AuthSessionMissingError()\n        }\n        const session: Session = sessionData.session\n        let codeChallenge: string | null = null\n        let codeChallengeMethod: string | null = null\n        if (this.flowType === 'pkce' \u0026\u0026 attributes.email != null) {\n          ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n            this.storage,\n            this.storageKey\n          )\n        }\n\n        const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {\n          headers: this.headers,\n          redirectTo: options?.emailRedirectTo,\n          body: {\n            ...attributes,\n            code_challenge: codeChallenge,\n            code_challenge_method: codeChallengeMethod,\n          },\n          jwt: session.access_token,\n          xform: _userResponse,\n        })\n        if (userError) throw userError\n        session.user = data.user as User\n        await this._saveSession(session)\n        await this._notifyAllSubscribers('USER_UPDATED', session)\n        return { data: { user: session.user }, error: null }\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Decodes a JWT (without performing any validation).\n   */\n  private _decodeJWT(jwt: string): {\n    exp?: number\n    aal?: AuthenticatorAssuranceLevels | null\n    amr?: AMREntry[] | null\n  } {\n    return decodeJWTPayload(jwt)\n  }\n\n  /**\n   * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.\n   * If the refresh token or access token in the current session is invalid, an error will be thrown.\n   * @param currentSession The current session that minimally contains an access token and refresh token.\n   */\n  async setSession(currentSession: {\n    access_token: string\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    return await this._acquireLock(-1, async () =\u003e {\n      return await this._setSession(currentSession)\n    })\n  }\n\n  protected async _setSession(currentSession: {\n    access_token: string\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    try {\n      if (!currentSession.access_token || !currentSession.refresh_token) {\n        throw new AuthSessionMissingError()\n      }\n\n      const timeNow = Date.now() / 1000\n      let expiresAt = timeNow\n      let hasExpired = true\n      let session: Session | null = null\n      const payload = decodeJWTPayload(currentSession.access_token)\n      if (payload.exp) {\n        expiresAt = payload.exp\n        hasExpired = expiresAt \u003c= timeNow\n      }\n\n      if (hasExpired) {\n        const { session: refreshedSession, error } = await this._callRefreshToken(\n          currentSession.refresh_token\n        )\n        if (error) {\n          return { data: { user: null, session: null }, error: error }\n        }\n\n        if (!refreshedSession) {\n          return { data: { user: null, session: null }, error: null }\n        }\n        session = refreshedSession\n      } else {\n        const { data, error } = await this._getUser(currentSession.access_token)\n        if (error) {\n          throw error\n        }\n        session = {\n          access_token: currentSession.access_token,\n          refresh_token: currentSession.refresh_token,\n          user: data.user,\n          token_type: 'bearer',\n          expires_in: expiresAt - timeNow,\n          expires_at: expiresAt,\n        }\n        await this._saveSession(session)\n        await this._notifyAllSubscribers('SIGNED_IN', session)\n      }\n\n      return { data: { user: session.user, session }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { session: null, user: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Returns a new session, regardless of expiry status.\n   * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().\n   * If the current session's refresh token is invalid, an error will be thrown.\n   * @param currentSession The current session. If passed in, it must contain a refresh token.\n   */\n  async refreshSession(currentSession?: { refresh_token: string }): Promise\u003cAuthResponse\u003e {\n    await this.initializePromise\n\n    return await this._acquireLock(-1, async () =\u003e {\n      return await this._refreshSession(currentSession)\n    })\n  }\n\n  protected async _refreshSession(currentSession?: {\n    refresh_token: string\n  }): Promise\u003cAuthResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        if (!currentSession) {\n          const { data, error } = result\n          if (error) {\n            throw error\n          }\n\n          currentSession = data.session ?? undefined\n        }\n\n        if (!currentSession?.refresh_token) {\n          throw new AuthSessionMissingError()\n        }\n\n        const { session, error } = await this._callRefreshToken(currentSession.refresh_token)\n        if (error) {\n          return { data: { user: null, session: null }, error: error }\n        }\n\n        if (!session) {\n          return { data: { user: null, session: null }, error: null }\n        }\n\n        return { data: { user: session.user, session }, error: null }\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { user: null, session: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Gets the session data from a URL string\n   */\n  private async _getSessionFromURL(isPKCEFlow: boolean): Promise\u003c\n    | {\n        data: { session: Session; redirectType: string | null }\n        error: null\n      }\n    | { data: { session: null; redirectType: null }; error: AuthError }\n  \u003e {\n    try {\n      if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.')\n      if (this.flowType === 'implicit' \u0026\u0026 !this._isImplicitGrantFlow()) {\n        throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.')\n      } else if (this.flowType == 'pkce' \u0026\u0026 !isPKCEFlow) {\n        throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.')\n      }\n\n      const params = parseParametersFromURL(window.location.href)\n\n      if (isPKCEFlow) {\n        if (!params.code) throw new AuthPKCEGrantCodeExchangeError('No code detected.')\n        const { data, error } = await this._exchangeCodeForSession(params.code)\n        if (error) throw error\n\n        const url = new URL(window.location.href)\n        url.searchParams.delete('code')\n\n        window.history.replaceState(window.history.state, '', url.toString())\n\n        return { data: { session: data.session, redirectType: null }, error: null }\n      }\n\n      if (params.error || params.error_description || params.error_code) {\n        throw new AuthImplicitGrantRedirectError(\n          params.error_description || 'Error in URL with unspecified error_description',\n          {\n            error: params.error || 'unspecified_error',\n            code: params.error_code || 'unspecified_code',\n          }\n        )\n      }\n\n      const {\n        provider_token,\n        provider_refresh_token,\n        access_token,\n        refresh_token,\n        expires_in,\n        expires_at,\n        token_type,\n      } = params\n\n      if (!access_token || !expires_in || !refresh_token || !token_type) {\n        throw new AuthImplicitGrantRedirectError('No session defined in URL')\n      }\n\n      const timeNow = Math.round(Date.now() / 1000)\n      const expiresIn = parseInt(expires_in)\n      let expiresAt = timeNow + expiresIn\n\n      if (expires_at) {\n        expiresAt = parseInt(expires_at)\n      }\n\n      const actuallyExpiresIn = expiresAt - timeNow\n      if (actuallyExpiresIn * 1000 \u003c= AUTO_REFRESH_TICK_DURATION) {\n        console.warn(\n          `@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`\n        )\n      }\n\n      const issuedAt = expiresAt - expiresIn\n      if (timeNow - issuedAt \u003e= 120) {\n        console.warn(\n          '@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale',\n          issuedAt,\n          expiresAt,\n          timeNow\n        )\n      } else if (timeNow - issuedAt \u003c 0) {\n        console.warn(\n          '@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew',\n          issuedAt,\n          expiresAt,\n          timeNow\n        )\n      }\n\n      const { data, error } = await this._getUser(access_token)\n      if (error) throw error\n\n      const session: Session = {\n        provider_token,\n        provider_refresh_token,\n        access_token,\n        expires_in: expiresIn,\n        expires_at: expiresAt,\n        refresh_token,\n        token_type,\n        user: data.user,\n      }\n\n      // Remove tokens from URL\n      window.location.hash = ''\n      this._debug('#_getSessionFromURL()', 'clearing window.location.hash')\n\n      return { data: { session, redirectType: params.type }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { session: null, redirectType: null }, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)\n   */\n  private _isImplicitGrantFlow(): boolean {\n    const params = parseParametersFromURL(window.location.href)\n\n    return !!(isBrowser() \u0026\u0026 (params.access_token || params.error_description))\n  }\n\n  /**\n   * Checks if the current URL and backing storage contain parameters given by a PKCE flow\n   */\n  private async _isPKCEFlow(): Promise\u003cboolean\u003e {\n    const params = parseParametersFromURL(window.location.href)\n\n    const currentStorageContent = await getItemAsync(\n      this.storage,\n      `${this.storageKey}-code-verifier`\n    )\n\n    return !!(params.code \u0026\u0026 currentStorageContent)\n  }\n\n  /**\n   * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `\"SIGNED_OUT\"` event.\n   *\n   * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.\n   * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.\n   *\n   * If using `others` scope, no `SIGNED_OUT` event is fired!\n   */\n  async signOut(options: SignOut = { scope: 'global' }): Promise\u003c{ error: AuthError | null }\u003e {\n    await this.initializePromise\n\n    return await this._acquireLock(-1, async () =\u003e {\n      return await this._signOut(options)\n    })\n  }\n\n  protected async _signOut(\n    { scope }: SignOut = { scope: 'global' }\n  ): Promise\u003c{ error: AuthError | null }\u003e {\n    return await this._useSession(async (result) =\u003e {\n      const { data, error: sessionError } = result\n      if (sessionError) {\n        return { error: sessionError }\n      }\n      const accessToken = data.session?.access_token\n      if (accessToken) {\n        const { error } = await this.admin.signOut(accessToken, scope)\n        if (error) {\n          // ignore 404s since user might not exist anymore\n          // ignore 401s since an invalid or expired JWT should sign out the current session\n          if (\n            !(\n              isAuthApiError(error) \u0026\u0026\n              (error.status === 404 || error.status === 401 || error.status === 403)\n            )\n          ) {\n            return { error }\n          }\n        }\n      }\n      if (scope !== 'others') {\n        await this._removeSession()\n        await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`)\n        await this._notifyAllSubscribers('SIGNED_OUT', null)\n      }\n      return { error: null }\n    })\n  }\n\n  /**\n   * Receive a notification every time an auth event happens.\n   * @param callback A callback function to be invoked when an auth event happens.\n   */\n  onAuthStateChange(\n    callback: (event: AuthChangeEvent, session: Session | null) =\u003e void | Promise\u003cvoid\u003e\n  ): {\n    data: { subscription: Subscription }\n  } {\n    const id: string = uuid()\n    const subscription: Subscription = {\n      id,\n      callback,\n      unsubscribe: () =\u003e {\n        this._debug('#unsubscribe()', 'state change callback with id removed', id)\n\n        this.stateChangeEmitters.delete(id)\n      },\n    }\n\n    this._debug('#onAuthStateChange()', 'registered callback with id', id)\n\n    this.stateChangeEmitters.set(id, subscription)\n    ;(async () =\u003e {\n      await this.initializePromise\n\n      await this._acquireLock(-1, async () =\u003e {\n        this._emitInitialSession(id)\n      })\n    })()\n\n    return { data: { subscription } }\n  }\n\n  private async _emitInitialSession(id: string): Promise\u003cvoid\u003e {\n    return await this._useSession(async (result) =\u003e {\n      try {\n        const {\n          data: { session },\n          error,\n        } = result\n        if (error) throw error\n\n        await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', session)\n        this._debug('INITIAL_SESSION', 'callback id', id, 'session', session)\n      } catch (err) {\n        await this.stateChangeEmitters.get(id)?.callback('INITIAL_SESSION', null)\n        this._debug('INITIAL_SESSION', 'callback id', id, 'error', err)\n        console.error(err)\n      }\n    })\n  }\n\n  /**\n   * Sends a password reset request to an email address. This method supports the PKCE flow.\n   *\n   * @param email The email address of the user.\n   * @param options.redirectTo The URL to send the user to after they click the password reset link.\n   * @param options.captchaToken Verification token received when the user completes the captcha on the site.\n   */\n  async resetPasswordForEmail(\n    email: string,\n    options: {\n      redirectTo?: string\n      captchaToken?: string\n    } = {}\n  ): Promise\u003c\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    let codeChallenge: string | null = null\n    let codeChallengeMethod: string | null = null\n\n    if (this.flowType === 'pkce') {\n      ;[codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n        this.storage,\n        this.storageKey,\n        true // isPasswordRecovery\n      )\n    }\n    try {\n      return await _request(this.fetch, 'POST', `${this.url}/recover`, {\n        body: {\n          email,\n          code_challenge: codeChallenge,\n          code_challenge_method: codeChallengeMethod,\n          gotrue_meta_security: { captcha_token: options.captchaToken },\n        },\n        headers: this.headers,\n        redirectTo: options.redirectTo,\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n\n      throw error\n    }\n  }\n\n  /**\n   * Gets all the identities linked to a user.\n   */\n  async getUserIdentities(): Promise\u003c\n    | {\n        data: {\n          identities: UserIdentity[]\n        }\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    try {\n      const { data, error } = await this.getUser()\n      if (error) throw error\n      return { data: { identities: data.user.identities ?? [] }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n  /**\n   * Links an oauth identity to an existing user.\n   * This method supports the PKCE flow.\n   */\n  async linkIdentity(credentials: SignInWithOAuthCredentials): Promise\u003cOAuthResponse\u003e {\n    try {\n      const { data, error } = await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) throw error\n        const url: string = await this._getUrlForProvider(\n          `${this.url}/user/identities/authorize`,\n          credentials.provider,\n          {\n            redirectTo: credentials.options?.redirectTo,\n            scopes: credentials.options?.scopes,\n            queryParams: credentials.options?.queryParams,\n            skipBrowserRedirect: true,\n          }\n        )\n        return await _request(this.fetch, 'GET', url, {\n          headers: this.headers,\n          jwt: data.session?.access_token ?? undefined,\n        })\n      })\n      if (error) throw error\n      if (isBrowser() \u0026\u0026 !credentials.options?.skipBrowserRedirect) {\n        window.location.assign(data?.url)\n      }\n      return { data: { provider: credentials.provider, url: data?.url }, error: null }\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: { provider: credentials.provider, url: null }, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.\n   */\n  async unlinkIdentity(identity: UserIdentity): Promise\u003c\n    | {\n        data: {}\n        error: null\n      }\n    | { data: null; error: AuthError }\n  \u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data, error } = result\n        if (error) {\n          throw error\n        }\n        return await _request(\n          this.fetch,\n          'DELETE',\n          `${this.url}/user/identities/${identity.identity_id}`,\n          {\n            headers: this.headers,\n            jwt: data.session?.access_token ?? undefined,\n          }\n        )\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Generates a new JWT.\n   * @param refreshToken A valid refresh token that was returned on login.\n   */\n  private async _refreshAccessToken(refreshToken: string): Promise\u003cAuthResponse\u003e {\n    const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`\n    this._debug(debugName, 'begin')\n\n    try {\n      const startedAt = Date.now()\n\n      // will attempt to refresh the token with exponential backoff\n      return await retryable(\n        async (attempt) =\u003e {\n          if (attempt \u003e 0) {\n            await sleep(200 * Math.pow(2, attempt - 1)) // 200, 400, 800, ...\n          }\n\n          this._debug(debugName, 'refreshing attempt', attempt)\n\n          return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {\n            body: { refresh_token: refreshToken },\n            headers: this.headers,\n            xform: _sessionResponse,\n          })\n        },\n        (attempt, error) =\u003e {\n          const nextBackOffInterval = 200 * Math.pow(2, attempt)\n          return (\n            error \u0026\u0026\n            isAuthRetryableFetchError(error) \u0026\u0026\n            // retryable only if the request can be sent before the backoff overflows the tick duration\n            Date.now() + nextBackOffInterval - startedAt \u003c AUTO_REFRESH_TICK_DURATION\n          )\n        }\n      )\n    } catch (error) {\n      this._debug(debugName, 'error', error)\n\n      if (isAuthError(error)) {\n        return { data: { session: null, user: null }, error }\n      }\n      throw error\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private _isValidSession(maybeSession: unknown): maybeSession is Session {\n    const isValidSession =\n      typeof maybeSession === 'object' \u0026\u0026\n      maybeSession !== null \u0026\u0026\n      'access_token' in maybeSession \u0026\u0026\n      'refresh_token' in maybeSession \u0026\u0026\n      'expires_at' in maybeSession\n\n    return isValidSession\n  }\n\n  private async _handleProviderSignIn(\n    provider: Provider,\n    options: {\n      redirectTo?: string\n      scopes?: string\n      queryParams?: { [key: string]: string }\n      skipBrowserRedirect?: boolean\n    }\n  ) {\n    const url: string = await this._getUrlForProvider(`${this.url}/authorize`, provider, {\n      redirectTo: options.redirectTo,\n      scopes: options.scopes,\n      queryParams: options.queryParams,\n    })\n\n    this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url)\n\n    // try to open on the browser\n    if (isBrowser() \u0026\u0026 !options.skipBrowserRedirect) {\n      window.location.assign(url)\n    }\n\n    return { data: { provider, url }, error: null }\n  }\n\n  /**\n   * Recovers the session from LocalStorage and refreshes\n   * Note: this method is async to accommodate for AsyncStorage e.g. in React native.\n   */\n  private async _recoverAndRefresh() {\n    const debugName = '#_recoverAndRefresh()'\n    this._debug(debugName, 'begin')\n\n    try {\n      const currentSession = await getItemAsync(this.storage, this.storageKey)\n      this._debug(debugName, 'session from storage', currentSession)\n\n      if (!this._isValidSession(currentSession)) {\n        this._debug(debugName, 'session is not valid')\n        if (currentSession !== null) {\n          await this._removeSession()\n        }\n\n        return\n      }\n\n      const timeNow = Math.round(Date.now() / 1000)\n      const expiresWithMargin = (currentSession.expires_at ?? Infinity) \u003c timeNow + EXPIRY_MARGIN\n\n      this._debug(\n        debugName,\n        `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN}s`\n      )\n\n      if (expiresWithMargin) {\n        if (this.autoRefreshToken \u0026\u0026 currentSession.refresh_token) {\n          const { error } = await this._callRefreshToken(currentSession.refresh_token)\n\n          if (error) {\n            console.error(error)\n\n            if (!isAuthRetryableFetchError(error)) {\n              this._debug(\n                debugName,\n                'refresh failed with a non-retryable error, removing the session',\n                error\n              )\n              await this._removeSession()\n            }\n          }\n        }\n      } else {\n        // no need to persist currentSession again, as we just loaded it from\n        // local storage; persisting it again may overwrite a value saved by\n        // another client with access to the same local storage\n        await this._notifyAllSubscribers('SIGNED_IN', currentSession)\n      }\n    } catch (err) {\n      this._debug(debugName, 'error', err)\n\n      console.error(err)\n      return\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private async _callRefreshToken(refreshToken: string): Promise\u003cCallRefreshTokenResult\u003e {\n    if (!refreshToken) {\n      throw new AuthSessionMissingError()\n    }\n\n    // refreshing is already in progress\n    if (this.refreshingDeferred) {\n      return this.refreshingDeferred.promise\n    }\n\n    const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`\n\n    this._debug(debugName, 'begin')\n\n    try {\n      this.refreshingDeferred = new Deferred\u003cCallRefreshTokenResult\u003e()\n\n      const { data, error } = await this._refreshAccessToken(refreshToken)\n      if (error) throw error\n      if (!data.session) throw new AuthSessionMissingError()\n\n      await this._saveSession(data.session)\n      await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session)\n\n      const result = { session: data.session, error: null }\n\n      this.refreshingDeferred.resolve(result)\n\n      return result\n    } catch (error) {\n      this._debug(debugName, 'error', error)\n\n      if (isAuthError(error)) {\n        const result = { session: null, error }\n\n        if (!isAuthRetryableFetchError(error)) {\n          await this._removeSession()\n          await this._notifyAllSubscribers('SIGNED_OUT', null)\n        }\n\n        this.refreshingDeferred?.resolve(result)\n\n        return result\n      }\n\n      this.refreshingDeferred?.reject(error)\n      throw error\n    } finally {\n      this.refreshingDeferred = null\n      this._debug(debugName, 'end')\n    }\n  }\n\n  private async _notifyAllSubscribers(\n    event: AuthChangeEvent,\n    session: Session | null,\n    broadcast = true\n  ) {\n    const debugName = `#_notifyAllSubscribers(${event})`\n    this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`)\n\n    try {\n      if (this.broadcastChannel \u0026\u0026 broadcast) {\n        this.broadcastChannel.postMessage({ event, session })\n      }\n\n      const errors: any[] = []\n      const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) =\u003e {\n        try {\n          await x.callback(event, session)\n        } catch (e: any) {\n          errors.push(e)\n        }\n      })\n\n      await Promise.all(promises)\n\n      if (errors.length \u003e 0) {\n        for (let i = 0; i \u003c errors.length; i += 1) {\n          console.error(errors[i])\n        }\n\n        throw errors[0]\n      }\n    } finally {\n      this._debug(debugName, 'end')\n    }\n  }\n\n  /**\n   * set currentSession and currentUser\n   * process to _startAutoRefreshToken if possible\n   */\n  private async _saveSession(session: Session) {\n    this._debug('#_saveSession()', session)\n    // _saveSession is always called whenever a new session has been acquired\n    // so we can safely suppress the warning returned by future getSession calls\n    this.suppressGetSessionWarning = true\n    await setItemAsync(this.storage, this.storageKey, session)\n  }\n\n  private async _removeSession() {\n    this._debug('#_removeSession()')\n\n    await removeItemAsync(this.storage, this.storageKey)\n  }\n\n  /**\n   * Removes any registered visibilitychange callback.\n   *\n   * {@see #startAutoRefresh}\n   * {@see #stopAutoRefresh}\n   */\n  private _removeVisibilityChangedCallback() {\n    this._debug('#_removeVisibilityChangedCallback()')\n\n    const callback = this.visibilityChangedCallback\n    this.visibilityChangedCallback = null\n\n    try {\n      if (callback \u0026\u0026 isBrowser() \u0026\u0026 window?.removeEventListener) {\n        window.removeEventListener('visibilitychange', callback)\n      }\n    } catch (e) {\n      console.error('removing visibilitychange callback failed', e)\n    }\n  }\n\n  /**\n   * This is the private implementation of {@link #startAutoRefresh}. Use this\n   * within the library.\n   */\n  private async _startAutoRefresh() {\n    await this._stopAutoRefresh()\n\n    this._debug('#_startAutoRefresh()')\n\n    const ticker = setInterval(() =\u003e this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION)\n    this.autoRefreshTicker = ticker\n\n    if (ticker \u0026\u0026 typeof ticker === 'object' \u0026\u0026 typeof ticker.unref === 'function') {\n      // ticker is a NodeJS Timeout object that has an `unref` method\n      // https://nodejs.org/api/timers.html#timeoutunref\n      // When auto refresh is used in NodeJS (like for testing) the\n      // `setInterval` is preventing the process from being marked as\n      // finished and tests run endlessly. This can be prevented by calling\n      // `unref()` on the returned object.\n      ticker.unref()\n      // @ts-ignore\n    } else if (typeof Deno !== 'undefined' \u0026\u0026 typeof Deno.unrefTimer === 'function') {\n      // similar like for NodeJS, but with the Deno API\n      // https://deno.land/api@latest?unstable\u0026s=Deno.unrefTimer\n      // @ts-ignore\n      Deno.unrefTimer(ticker)\n    }\n\n    // run the tick immediately, but in the next pass of the event loop so that\n    // #_initialize can be allowed to complete without recursively waiting on\n    // itself\n    setTimeout(async () =\u003e {\n      await this.initializePromise\n      await this._autoRefreshTokenTick()\n    }, 0)\n  }\n\n  /**\n   * This is the private implementation of {@link #stopAutoRefresh}. Use this\n   * within the library.\n   */\n  private async _stopAutoRefresh() {\n    this._debug('#_stopAutoRefresh()')\n\n    const ticker = this.autoRefreshTicker\n    this.autoRefreshTicker = null\n\n    if (ticker) {\n      clearInterval(ticker)\n    }\n  }\n\n  /**\n   * Starts an auto-refresh process in the background. The session is checked\n   * every few seconds. Close to the time of expiration a process is started to\n   * refresh the session. If refreshing fails it will be retried for as long as\n   * necessary.\n   *\n   * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need\n   * to call this function, it will be called for you.\n   *\n   * On browsers the refresh process works only when the tab/window is in the\n   * foreground to conserve resources as well as prevent race conditions and\n   * flooding auth with requests. If you call this method any managed\n   * visibility change callback will be removed and you must manage visibility\n   * changes on your own.\n   *\n   * On non-browser platforms the refresh process works *continuously* in the\n   * background, which may not be desirable. You should hook into your\n   * platform's foreground indication mechanism and call these methods\n   * appropriately to conserve resources.\n   *\n   * {@see #stopAutoRefresh}\n   */\n  async startAutoRefresh() {\n    this._removeVisibilityChangedCallback()\n    await this._startAutoRefresh()\n  }\n\n  /**\n   * Stops an active auto refresh process running in the background (if any).\n   *\n   * If you call this method any managed visibility change callback will be\n   * removed and you must manage visibility changes on your own.\n   *\n   * See {@link #startAutoRefresh} for more details.\n   */\n  async stopAutoRefresh() {\n    this._removeVisibilityChangedCallback()\n    await this._stopAutoRefresh()\n  }\n\n  /**\n   * Runs the auto refresh token tick.\n   */\n  private async _autoRefreshTokenTick() {\n    this._debug('#_autoRefreshTokenTick()', 'begin')\n\n    try {\n      await this._acquireLock(0, async () =\u003e {\n        try {\n          const now = Date.now()\n\n          try {\n            return await this._useSession(async (result) =\u003e {\n              const {\n                data: { session },\n              } = result\n\n              if (!session || !session.refresh_token || !session.expires_at) {\n                this._debug('#_autoRefreshTokenTick()', 'no session')\n                return\n              }\n\n              // session will expire in this many ticks (or has already expired if \u003c= 0)\n              const expiresInTicks = Math.floor(\n                (session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION\n              )\n\n              this._debug(\n                '#_autoRefreshTokenTick()',\n                `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`\n              )\n\n              if (expiresInTicks \u003c= AUTO_REFRESH_TICK_THRESHOLD) {\n                await this._callRefreshToken(session.refresh_token)\n              }\n            })\n          } catch (e: any) {\n            console.error(\n              'Auto refresh tick failed with error. This is likely a transient error.',\n              e\n            )\n          }\n        } finally {\n          this._debug('#_autoRefreshTokenTick()', 'end')\n        }\n      })\n    } catch (e: any) {\n      if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) {\n        this._debug('auto refresh token tick lock not available')\n      } else {\n        throw e\n      }\n    }\n  }\n\n  /**\n   * Registers callbacks on the browser / platform, which in-turn run\n   * algorithms when the browser window/tab are in foreground. On non-browser\n   * platforms it assumes always foreground.\n   */\n  private async _handleVisibilityChange() {\n    this._debug('#_handleVisibilityChange()')\n\n    if (!isBrowser() || !window?.addEventListener) {\n      if (this.autoRefreshToken) {\n        // in non-browser environments the refresh token ticker runs always\n        this.startAutoRefresh()\n      }\n\n      return false\n    }\n\n    try {\n      this.visibilityChangedCallback = async () =\u003e await this._onVisibilityChanged(false)\n\n      window?.addEventListener('visibilitychange', this.visibilityChangedCallback)\n\n      // now immediately call the visbility changed callback to setup with the\n      // current visbility state\n      await this._onVisibilityChanged(true) // initial call\n    } catch (error) {\n      console.error('_handleVisibilityChange', error)\n    }\n  }\n\n  /**\n   * Callback registered with `window.addEventListener('visibilitychange')`.\n   */\n  private async _onVisibilityChanged(calledFromInitialize: boolean) {\n    const methodName = `#_onVisibilityChanged(${calledFromInitialize})`\n    this._debug(methodName, 'visibilityState', document.visibilityState)\n\n    if (document.visibilityState === 'visible') {\n      if (this.autoRefreshToken) {\n        // in browser environments the refresh token ticker runs only on focused tabs\n        // which prevents race conditions\n        this._startAutoRefresh()\n      }\n\n      if (!calledFromInitialize) {\n        // called when the visibility has changed, i.e. the browser\n        // transitioned from hidden -\u003e visible so we need to see if the session\n        // should be recovered immediately... but to do that we need to acquire\n        // the lock first asynchronously\n        await this.initializePromise\n\n        await this._acquireLock(-1, async () =\u003e {\n          if (document.visibilityState !== 'visible') {\n            this._debug(\n              methodName,\n              'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'\n            )\n\n            // visibility has changed while waiting for the lock, abort\n            return\n          }\n\n          // recover the session\n          await this._recoverAndRefresh()\n        })\n      }\n    } else if (document.visibilityState === 'hidden') {\n      if (this.autoRefreshToken) {\n        this._stopAutoRefresh()\n      }\n    }\n  }\n\n  /**\n   * Generates the relevant login URL for a third-party provider.\n   * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.\n   * @param options.scopes A space-separated list of scopes granted to the OAuth application.\n   * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.\n   */\n  private async _getUrlForProvider(\n    url: string,\n    provider: Provider,\n    options: {\n      redirectTo?: string\n      scopes?: string\n      queryParams?: { [key: string]: string }\n      skipBrowserRedirect?: boolean\n    }\n  ) {\n    const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`]\n    if (options?.redirectTo) {\n      urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`)\n    }\n    if (options?.scopes) {\n      urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)\n    }\n    if (this.flowType === 'pkce') {\n      const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(\n        this.storage,\n        this.storageKey\n      )\n\n      const flowParams = new URLSearchParams({\n        code_challenge: `${encodeURIComponent(codeChallenge)}`,\n        code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,\n      })\n      urlParams.push(flowParams.toString())\n    }\n    if (options?.queryParams) {\n      const query = new URLSearchParams(options.queryParams)\n      urlParams.push(query.toString())\n    }\n    if (options?.skipBrowserRedirect) {\n      urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`)\n    }\n\n    return `${url}?${urlParams.join('\u0026')}`\n  }\n\n  private async _unenroll(params: MFAUnenrollParams): Promise\u003cAuthMFAUnenrollResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return { data: null, error: sessionError }\n        }\n\n        return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {\n          headers: this.headers,\n          jwt: sessionData?.session?.access_token,\n        })\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@see GoTrueMFAApi#enroll}\n   */\n  private async _enroll(params: MFAEnrollParams): Promise\u003cAuthMFAEnrollResponse\u003e {\n    try {\n      return await this._useSession(async (result) =\u003e {\n        const { data: sessionData, error: sessionError } = result\n        if (sessionError) {\n          return { data: null, error: sessionError }\n        }\n\n        const body = {\n          friendly_name: params.friendlyName,\n          factor_type: params.factorType,\n          ...(params.factorType === 'phone' ? { phone: params.phone } : { issuer: params.issuer }),\n        }\n\n        const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors`, {\n          body,\n          headers: this.headers,\n          jwt: sessionData?.session?.access_token,\n        })\n\n        if (error) {\n          return { data: null, error }\n        }\n\n        // TODO: Remove once: https://github.com/supabase/auth/pull/1717 is deployed\n        if (params.factorType === 'phone') {\n          delete data.totp\n        }\n\n        if (params.factorType === 'totp' \u0026\u0026 data?.totp?.qr_code) {\n          data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`\n        }\n\n        return { data, error: null }\n      })\n    } catch (error) {\n      if (isAuthError(error)) {\n        return { data: null, error }\n      }\n      throw error\n    }\n  }\n\n  /**\n   * {@see GoTrueMFAApi#verify}\n   */\n  private async _verify(params: MFAVerifyParams): Promise\u003cAuthMFAVerifyResponse\u003e {\n    return this._acquireLock(-1, async () =\u003e {\n      try {\n        return await this._useSession(async (result) =\u003e {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return { data: null, error: sessionError }\n          }\n\n          const { data, error } = await _request(\n            this.fetch,\n            'POST',\n            `${this.url}/factors/${params.factorId}/verify`,\n            {\n              body: { code: params.code, challenge_id: params.challengeId },\n              headers: this.headers,\n              jwt: sessionData?.session?.access_token,\n            }\n          )\n          if (error) {\n            return { data: null, error }\n          }\n\n          await this._saveSession({\n            expires_at: Math.round(Date.now() / 1000) + data.expires_in,\n            ...data,\n          })\n          await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data)\n\n          return { data, error }\n        })\n      } catch (error) {\n        if (isAuthError(error)) {\n          return { data: null, error }\n        }\n        throw error\n      }\n    })\n  }\n\n  /**\n   * {@see GoTrueMFAApi#challenge}\n   */\n  private async _challenge(params: MFAChallengeParams): Promise\u003cAuthMFAChallengeResponse\u003e {\n    return this._acquireLock(-1, async () =\u003e {\n      try {\n        return await this._useSession(async (result) =\u003e {\n          const { data: sessionData, error: sessionError } = result\n          if (sessionError) {\n            return { data: null, error: sessionError }\n          }\n\n          return await _request(\n            this.fetch,\n            'POST',\n            `${this.url}/factors/${params.factorId}/challenge`,\n            {\n              body: { channel: params.channel },\n              headers: this.headers,\n              jwt: sessionData?.session?.access_token,\n            }\n          )\n        })\n      } catch (error) {\n        if (isAuthError(error)) {\n          return { data: null, error }\n        }\n        throw error\n      }\n    })\n  }\n\n  /**\n   * {@see GoTrueMFAApi#challengeAndVerify}\n   */\n  private async _challengeAndVerify(\n    params: MFAChallengeAndVerifyParams\n  ): Promise\u003cAuthMFAVerifyResponse\u003e {\n    // both _challenge and _verify independently acquire the lock, so no need\n    // to acquire it here\n\n    const { data: challengeData, error: challengeError } = await this._challenge({\n      factorId: params.factorId,\n    })\n    if (challengeError) {\n      return { data: null, error: challengeError }\n    }\n\n    return await this._verify({\n      factorId: params.factorId,\n      challengeId: challengeData.id,\n      code: params.code,\n    })\n  }\n\n  /**\n   * {@see GoTrueMFAApi#listFactors}\n   */\n  private async _listFactors(): Promise\u003cAuthMFAListFactorsResponse\u003e {\n    // use #getUser instead of #_getUser as the former acquires a lock\n    const {\n      data: { user },\n      error: userError,\n    } = await this.getUser()\n    if (userError) {\n      return { data: null, error: userError }\n    }\n\n    const factors = user?.factors || []\n    const totp = factors.filter(\n      (factor) =\u003e factor.factor_type === 'totp' \u0026\u0026 factor.status === 'verified'\n    )\n    const phone = factors.filter(\n      (factor) =\u003e factor.factor_type === 'phone' \u0026\u0026 factor.status === 'verified'\n    )\n\n    return {\n      data: {\n        all: factors,\n        totp,\n        phone,\n      },\n      error: null,\n    }\n  }\n\n  /**\n   * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}\n   */\n  private async _getAuthenticatorAssuranceLevel(): Promise\u003cAuthMFAGetAuthenticatorAssuranceLevelResponse\u003e {\n    return this._acquireLock(-1, async () =\u003e {\n      return await this._useSession(async (result) =\u003e {\n        const {\n          data: { session },\n          error: sessionError,\n        } = result\n        if (sessionError) {\n          return { data: null, error: sessionError }\n        }\n        if (!session) {\n          return {\n            data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },\n            error: null,\n          }\n        }\n\n        const payload = this._decodeJWT(session.access_token)\n\n        let currentLevel: AuthenticatorAssuranceLevels | null = null\n\n        if (payload.aal) {\n          currentLevel = payload.aal\n        }\n\n        let nextLevel: AuthenticatorAssuranceLevels | null = currentLevel\n\n        const verifiedFactors =\n          session.user.factors?.filter((factor: Factor) =\u003e factor.status === 'verified') ?? []\n\n        if (verifiedFactors.length \u003e 0) {\n          nextLevel = 'aal2'\n        }\n\n        const currentAuthenticationMethods = payload.amr || []\n\n        return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }\n      })\n    })\n  }\n}\n","import GoTrueAdminApi from './GoTrueAdminApi'\n\nconst AuthAdminApi = GoTrueAdminApi\n\nexport default AuthAdminApi\n","import GoTrueClient from './GoTrueClient'\n\nconst AuthClient = GoTrueClient\n\nexport default AuthClient\n"],"version":3}
