{"version":3,"file":"firebase-app-check.js","sources":["../util/src/crypt.ts","../util/src/deferred.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../component/src/component.ts","../logger/src/logger.ts","../app-check/src/state.ts","../app-check/src/constants.ts","../app-check/src/proactive-refresh.ts","../app-check/src/errors.ts","../app-check/src/util.ts","../app-check/src/client.ts","../app-check/src/indexeddb.ts","../app-check/src/logger.ts","../app-check/src/storage.ts","../app-check/src/debug.ts","../util/src/global.ts","../app-check/src/internal-api.ts","../app-check/src/factory.ts","../app-check/src/recaptcha.ts","../app-check/src/providers.ts","../util/src/exponential_backoff.ts","../app-check/src/api.ts","../util/src/compat.ts","../app-check/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n  // TODO(user): Use native implementations if/when available\n  const out: number[] = [];\n  let p = 0;\n  for (let i = 0; i < str.length; i++) {\n    let c = str.charCodeAt(i);\n    if (c < 128) {\n      out[p++] = c;\n    } else if (c < 2048) {\n      out[p++] = (c >> 6) | 192;\n      out[p++] = (c & 63) | 128;\n    } else if (\n      (c & 0xfc00) === 0xd800 &&\n      i + 1 < str.length &&\n      (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n    ) {\n      // Surrogate Pair\n      c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n      out[p++] = (c >> 18) | 240;\n      out[p++] = ((c >> 12) & 63) | 128;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    } else {\n      out[p++] = (c >> 12) | 224;\n      out[p++] = ((c >> 6) & 63) | 128;\n      out[p++] = (c & 63) | 128;\n    }\n  }\n  return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n  // TODO(user): Use native implementations if/when available\n  const out: string[] = [];\n  let pos = 0,\n    c = 0;\n  while (pos < bytes.length) {\n    const c1 = bytes[pos++];\n    if (c1 < 128) {\n      out[c++] = String.fromCharCode(c1);\n    } else if (c1 > 191 && c1 < 224) {\n      const c2 = bytes[pos++];\n      out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n    } else if (c1 > 239 && c1 < 365) {\n      // Surrogate Pair\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      const c4 = bytes[pos++];\n      const u =\n        (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n        0x10000;\n      out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n      out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n    } else {\n      const c2 = bytes[pos++];\n      const c3 = bytes[pos++];\n      out[c++] = String.fromCharCode(\n        ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n      );\n    }\n  }\n  return out.join('');\n};\n\ninterface Base64 {\n  byteToCharMap_: { [key: number]: string } | null;\n  charToByteMap_: { [key: string]: number } | null;\n  byteToCharMapWebSafe_: { [key: number]: string } | null;\n  charToByteMapWebSafe_: { [key: string]: number } | null;\n  ENCODED_VALS_BASE: string;\n  readonly ENCODED_VALS: string;\n  readonly ENCODED_VALS_WEBSAFE: string;\n  HAS_NATIVE_SUPPORT: boolean;\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n  encodeString(input: string, webSafe?: boolean): string;\n  decodeString(input: string, webSafe: boolean): string;\n  decodeStringToByteArray(input: string, webSafe: boolean): number[];\n  init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n  /**\n   * Maps bytes to characters.\n   */\n  byteToCharMap_: null,\n\n  /**\n   * Maps characters to bytes.\n   */\n  charToByteMap_: null,\n\n  /**\n   * Maps bytes to websafe characters.\n   * @private\n   */\n  byteToCharMapWebSafe_: null,\n\n  /**\n   * Maps websafe characters to bytes.\n   * @private\n   */\n  charToByteMapWebSafe_: null,\n\n  /**\n   * Our default alphabet, shared between\n   * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n   */\n  ENCODED_VALS_BASE:\n    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n  /**\n   * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n   */\n  get ENCODED_VALS() {\n    return this.ENCODED_VALS_BASE + '+/=';\n  },\n\n  /**\n   * Our websafe alphabet.\n   */\n  get ENCODED_VALS_WEBSAFE() {\n    return this.ENCODED_VALS_BASE + '-_.';\n  },\n\n  /**\n   * Whether this browser supports the atob and btoa functions. This extension\n   * started at Mozilla but is now implemented by many browsers. We use the\n   * ASSUME_* variables to avoid pulling in the full useragent detection library\n   * but still allowing the standard per-browser compilations.\n   *\n   */\n  HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n  /**\n   * Base64-encode an array of bytes.\n   *\n   * @param input An array of bytes (numbers with\n   *     value in [0, 255]) to encode.\n   * @param webSafe Boolean indicating we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n    if (!Array.isArray(input)) {\n      throw Error('encodeByteArray takes an array as a parameter');\n    }\n\n    this.init_();\n\n    const byteToCharMap = webSafe\n      ? this.byteToCharMapWebSafe_!\n      : this.byteToCharMap_!;\n\n    const output = [];\n\n    for (let i = 0; i < input.length; i += 3) {\n      const byte1 = input[i];\n      const haveByte2 = i + 1 < input.length;\n      const byte2 = haveByte2 ? input[i + 1] : 0;\n      const haveByte3 = i + 2 < input.length;\n      const byte3 = haveByte3 ? input[i + 2] : 0;\n\n      const outByte1 = byte1 >> 2;\n      const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n      let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n      let outByte4 = byte3 & 0x3f;\n\n      if (!haveByte3) {\n        outByte4 = 64;\n\n        if (!haveByte2) {\n          outByte3 = 64;\n        }\n      }\n\n      output.push(\n        byteToCharMap[outByte1],\n        byteToCharMap[outByte2],\n        byteToCharMap[outByte3],\n        byteToCharMap[outByte4]\n      );\n    }\n\n    return output.join('');\n  },\n\n  /**\n   * Base64-encode a string.\n   *\n   * @param input A string to encode.\n   * @param webSafe If true, we should use the\n   *     alternative alphabet.\n   * @return The base64 encoded string.\n   */\n  encodeString(input: string, webSafe?: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return btoa(input);\n    }\n    return this.encodeByteArray(stringToByteArray(input), webSafe);\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * @param input to decode.\n   * @param webSafe True if we should use the\n   *     alternative alphabet.\n   * @return string representing the decoded value.\n   */\n  decodeString(input: string, webSafe: boolean): string {\n    // Shortcut for Mozilla browsers that implement\n    // a native base64 encoder in the form of \"btoa/atob\"\n    if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n      return atob(input);\n    }\n    return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n  },\n\n  /**\n   * Base64-decode a string.\n   *\n   * In base-64 decoding, groups of four characters are converted into three\n   * bytes.  If the encoder did not apply padding, the input length may not\n   * be a multiple of 4.\n   *\n   * In this case, the last group will have fewer than 4 characters, and\n   * padding will be inferred.  If the group has one or two characters, it decodes\n   * to one byte.  If the group has three characters, it decodes to two bytes.\n   *\n   * @param input Input to decode.\n   * @param webSafe True if we should use the web-safe alphabet.\n   * @return bytes representing the decoded value.\n   */\n  decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n    this.init_();\n\n    const charToByteMap = webSafe\n      ? this.charToByteMapWebSafe_!\n      : this.charToByteMap_!;\n\n    const output: number[] = [];\n\n    for (let i = 0; i < input.length; ) {\n      const byte1 = charToByteMap[input.charAt(i++)];\n\n      const haveByte2 = i < input.length;\n      const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n      ++i;\n\n      const haveByte3 = i < input.length;\n      const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      const haveByte4 = i < input.length;\n      const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n      ++i;\n\n      if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n        throw new DecodeBase64StringError();\n      }\n\n      const outByte1 = (byte1 << 2) | (byte2 >> 4);\n      output.push(outByte1);\n\n      if (byte3 !== 64) {\n        const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n        output.push(outByte2);\n\n        if (byte4 !== 64) {\n          const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n          output.push(outByte3);\n        }\n      }\n    }\n\n    return output;\n  },\n\n  /**\n   * Lazy static initialization function. Called before\n   * accessing any of the static map variables.\n   * @private\n   */\n  init_() {\n    if (!this.byteToCharMap_) {\n      this.byteToCharMap_ = {};\n      this.charToByteMap_ = {};\n      this.byteToCharMapWebSafe_ = {};\n      this.charToByteMapWebSafe_ = {};\n\n      // We want quick mappings back and forth, so we precompute two maps.\n      for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n        this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n        this.charToByteMap_[this.byteToCharMap_[i]] = i;\n        this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n        this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n        // Be forgiving when decoding and correctly decode both encodings.\n        if (i >= this.ENCODED_VALS_BASE.length) {\n          this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n          this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n        }\n      }\n    }\n  }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n  readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n  const utf8Bytes = stringToByteArray(str);\n  return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n  // Use base64url encoding and remove padding in the end (dot characters).\n  return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n  try {\n    return base64.decodeString(str, true);\n  } catch (e) {\n    console.error('base64Decode failed: ', e);\n  }\n  return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<R> {\n  promise: Promise<R>;\n  reject: (value?: unknown) => void = () => {};\n  resolve: (value?: unknown) => void = () => {};\n  constructor() {\n    this.promise = new Promise((resolve, reject) => {\n      this.resolve = resolve as (value?: unknown) => void;\n      this.reject = reject as (value?: unknown) => void;\n    });\n  }\n\n  /**\n   * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around\n   * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n   * and returns a node-style callback which will resolve or reject the Deferred's promise.\n   */\n  wrapCallback(\n    callback?: (error?: unknown, value?: unknown) => void\n  ): (error: unknown, value?: unknown) => void {\n    return (error, value?) => {\n      if (error) {\n        this.reject(error);\n      } else {\n        this.resolve(value);\n      }\n      if (typeof callback === 'function') {\n        // Attaching noop handler just in case developer wasn't expecting\n        // promises\n        this.promise.catch(() => {});\n\n        // Some of our callbacks don't expect a value and our own tests\n        // assert that the parameter length is 1\n        if (callback.length === 1) {\n          callback(error);\n        } else {\n          callback(error, value);\n        }\n      }\n    };\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Type placeholder for `WorkerGlobalScope` from `webworker`\n */\ndeclare class WorkerGlobalScope {}\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n  if (\n    typeof navigator !== 'undefined' &&\n    typeof navigator['userAgent'] === 'string'\n  ) {\n    return navigator['userAgent'];\n  } else {\n    return '';\n  }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n  return (\n    typeof window !== 'undefined' &&\n    // @ts-ignore Setting up an broadly applicable index signature for Window\n    // just to deal with this case would probably be a bad idea.\n    !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n    /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n  );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n  const forceEnvironment = getDefaults()?.forceEnvironment;\n  if (forceEnvironment === 'node') {\n    return true;\n  } else if (forceEnvironment === 'browser') {\n    return false;\n  }\n\n  try {\n    return (\n      Object.prototype.toString.call(global.process) === '[object process]'\n    );\n  } catch (e) {\n    return false;\n  }\n}\n\n/**\n * Detect Browser Environment.\n * Note: This will return true for certain test frameworks that are incompletely\n * mimicking a browser, and should not lead to assuming all browser APIs are\n * available.\n */\nexport function isBrowser(): boolean {\n  return typeof window !== 'undefined' || isWebWorker();\n}\n\n/**\n * Detect Web Worker context.\n */\nexport function isWebWorker(): boolean {\n  return (\n    typeof WorkerGlobalScope !== 'undefined' &&\n    typeof self !== 'undefined' &&\n    self instanceof WorkerGlobalScope\n  );\n}\n\n/**\n * Detect Cloudflare Worker context.\n */\nexport function isCloudflareWorker(): boolean {\n  return (\n    typeof navigator !== 'undefined' &&\n    navigator.userAgent === 'Cloudflare-Workers'\n  );\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n  id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n  const runtime =\n    typeof chrome === 'object'\n      ? chrome.runtime\n      : typeof browser === 'object'\n      ? browser.runtime\n      : undefined;\n  return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n  return (\n    typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n  );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n  return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n  const ua = getUA();\n  return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n  return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n  return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n  return (\n    !isNode() &&\n    !!navigator.userAgent &&\n    navigator.userAgent.includes('Safari') &&\n    !navigator.userAgent.includes('Chrome')\n  );\n}\n\n/** Returns true if we are running in Safari or WebKit */\nexport function isSafariOrWebkit(): boolean {\n  return (\n    !isNode() &&\n    !!navigator.userAgent &&\n    (navigator.userAgent.includes('Safari') ||\n      navigator.userAgent.includes('WebKit')) &&\n    !navigator.userAgent.includes('Chrome')\n  );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n  try {\n    return typeof indexedDB === 'object';\n  } catch (e) {\n    return false;\n  }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n  return new Promise((resolve, reject) => {\n    try {\n      let preExist: boolean = true;\n      const DB_CHECK_NAME =\n        'validate-browser-context-for-indexeddb-analytics-module';\n      const request = self.indexedDB.open(DB_CHECK_NAME);\n      request.onsuccess = () => {\n        request.result.close();\n        // delete database only when it doesn't pre-exist\n        if (!preExist) {\n          self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n        }\n        resolve(true);\n      };\n      request.onupgradeneeded = () => {\n        preExist = false;\n      };\n\n      request.onerror = () => {\n        reject(request.error?.message || '');\n      };\n    } catch (error) {\n      reject(error);\n    }\n  });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n  if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n    return false;\n  }\n  return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n *   // TypeScript string literals for type-safe codes\n *   type Err =\n *     'unknown' |\n *     'object-not-found'\n *     ;\n *\n *   // Closure enum for type-safe error codes\n *   // at-enum {string}\n *   var Err = {\n *     UNKNOWN: 'unknown',\n *     OBJECT_NOT_FOUND: 'object-not-found',\n *   }\n *\n *   let errors: Map<Err, string> = {\n *     'generic-error': \"Unknown error\",\n *     'file-not-found': \"Could not find file: {$file}\",\n *   };\n *\n *   // Type-safe function - must pass a valid error code as param.\n *   let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n *   ...\n *   throw error.create(Err.GENERIC);\n *   ...\n *   throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n *   ...\n *   // Service: Could not file file: foo.txt (service/file-not-found).\n *\n *   catch (e) {\n *     assert(e.message === \"Could not find file: foo.txt.\");\n *     if ((e as FirebaseError)?.code === 'service/file-not-found') {\n *       console.log(\"Could not read file: \" + e['file']);\n *     }\n *   }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n  readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n  toString(): string;\n}\n\nexport interface ErrorData {\n  [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n  /** The custom name for all FirebaseErrors. */\n  readonly name: string = ERROR_NAME;\n\n  constructor(\n    /** The error code for this error. */\n    readonly code: string,\n    message: string,\n    /** Custom data for this error. */\n    public customData?: Record<string, unknown>\n  ) {\n    super(message);\n\n    // Fix For ES5\n    // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n    // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n    //                   which we can now use since we no longer target ES5.\n    Object.setPrototypeOf(this, FirebaseError.prototype);\n\n    // Maintains proper stack trace for where our error was thrown.\n    // Only available on V8.\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, ErrorFactory.prototype.create);\n    }\n  }\n}\n\nexport class ErrorFactory<\n  ErrorCode extends string,\n  ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n  constructor(\n    private readonly service: string,\n    private readonly serviceName: string,\n    private readonly errors: ErrorMap<ErrorCode>\n  ) {}\n\n  create<K extends ErrorCode>(\n    code: K,\n    ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n  ): FirebaseError {\n    const customData = (data[0] as ErrorData) || {};\n    const fullCode = `${this.service}/${code}`;\n    const template = this.errors[code];\n\n    const message = template ? replaceTemplate(template, customData) : 'Error';\n    // Service Name: Error message (service/code).\n    const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n    const error = new FirebaseError(fullCode, fullMessage, customData);\n\n    return error;\n  }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n  try {\n    let ptr = 0;\n    let result = '';\n    while (ptr < template.length) {\n      const start = template.indexOf('{$', ptr);\n      if (start === -1) {\n        result += template.substring(ptr);\n        break;\n      }\n      const end = template.indexOf('}', start + 2);\n      if (end === -1) {\n        result += template.substring(ptr);\n        break;\n      }\n      const key = template.substring(start + 2, end);\n      const value = data[key];\n      result +=\n        template.substring(ptr, start) +\n        (value != null ? String(value) : `<${key}?>`);\n      ptr = end + 1;\n    }\n    return result;\n  } catch (e) {\n    // Should never happen, but fallback just in case\n    return template;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n  return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n  return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n  [key: string]: {};\n}\n\ninterface DecodedToken {\n  header: object;\n  claims: Claims;\n  data: object;\n  signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n  let header = {},\n    claims: Claims = {},\n    data = {},\n    signature = '';\n\n  try {\n    const parts = token.split('.');\n    header = jsonEval(base64Decode(parts[0]) || '') as object;\n    claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n    signature = parts[2];\n    data = claims['d'] || {};\n    delete claims['d'];\n  } catch (e) {}\n\n  return {\n    header,\n    claims,\n    data,\n    signature\n  };\n};\n\ninterface DecodedToken {\n  header: object;\n  claims: Claims;\n  data: object;\n  signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n  const claims: Claims = decode(token).claims;\n  const now: number = Math.floor(new Date().getTime() / 1000);\n  let validSince: number = 0,\n    validUntil: number = 0;\n\n  if (typeof claims === 'object') {\n    if (claims.hasOwnProperty('nbf')) {\n      validSince = claims['nbf'] as number;\n    } else if (claims.hasOwnProperty('iat')) {\n      validSince = claims['iat'] as number;\n    }\n\n    if (claims.hasOwnProperty('exp')) {\n      validUntil = claims['exp'] as number;\n    } else {\n      // token will expire after 24h by default\n      validUntil = validSince + 86400;\n    }\n  }\n\n  return (\n    !!now &&\n    !!validSince &&\n    !!validUntil &&\n    now >= validSince &&\n    now <= validUntil\n  );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n  const claims: Claims = decode(token).claims;\n  if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n    return claims['iat'] as number;\n  }\n  return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n  const decoded = decode(token),\n    claims = decoded.claims;\n\n  return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n  const claims: Claims = decode(token).claims;\n  return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n  InstantiationMode,\n  InstanceFactory,\n  ComponentType,\n  Dictionary,\n  Name,\n  onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n  multipleInstances = false;\n  /**\n   * Properties to be added to the service namespace\n   */\n  serviceProps: Dictionary = {};\n\n  instantiationMode = InstantiationMode.LAZY;\n\n  onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n  /**\n   *\n   * @param name The public service name, e.g. app, auth, firestore, database\n   * @param instanceFactory Service factory responsible for creating the public interface\n   * @param type whether the service provided by the component is public or private\n   */\n  constructor(\n    readonly name: T,\n    readonly instanceFactory: InstanceFactory<T>,\n    readonly type: ComponentType\n  ) {}\n\n  setInstantiationMode(mode: InstantiationMode): this {\n    this.instantiationMode = mode;\n    return this;\n  }\n\n  setMultipleInstances(multipleInstances: boolean): this {\n    this.multipleInstances = multipleInstances;\n    return this;\n  }\n\n  setServiceProps(props: Dictionary): this {\n    this.serviceProps = props;\n    return this;\n  }\n\n  setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n    this.onInstanceCreated = callback;\n    return this;\n  }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n  | 'debug'\n  | 'verbose'\n  | 'info'\n  | 'warn'\n  | 'error'\n  | 'silent';\n\nexport interface LogOptions {\n  level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n  level: LogLevelString;\n  message: string;\n  args: unknown[];\n  type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n  DEBUG,\n  VERBOSE,\n  INFO,\n  WARN,\n  ERROR,\n  SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n  'debug': LogLevel.DEBUG,\n  'verbose': LogLevel.VERBOSE,\n  'info': LogLevel.INFO,\n  'warn': LogLevel.WARN,\n  'error': LogLevel.ERROR,\n  'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n  loggerInstance: Logger,\n  logType: LogLevel,\n  ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n  [LogLevel.DEBUG]: 'log',\n  [LogLevel.VERBOSE]: 'log',\n  [LogLevel.INFO]: 'info',\n  [LogLevel.WARN]: 'warn',\n  [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n  if (logType < instance.logLevel) {\n    return;\n  }\n  const now = new Date().toISOString();\n  const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n  if (method) {\n    console[method as 'log' | 'info' | 'warn' | 'error'](\n      `[${now}]  ${instance.name}:`,\n      ...args\n    );\n  } else {\n    throw new Error(\n      `Attempted to log a message with an invalid logType (value: ${logType})`\n    );\n  }\n};\n\nexport class Logger {\n  /**\n   * Gives you an instance of a Logger to capture messages according to\n   * Firebase's logging scheme.\n   *\n   * @param name The name that the logs will be associated with\n   */\n  constructor(public name: string) {\n    /**\n     * Capture the current instance for later use\n     */\n    instances.push(this);\n  }\n\n  /**\n   * The log level of the given Logger instance.\n   */\n  private _logLevel = defaultLogLevel;\n\n  get logLevel(): LogLevel {\n    return this._logLevel;\n  }\n\n  set logLevel(val: LogLevel) {\n    if (!(val in LogLevel)) {\n      throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n    }\n    this._logLevel = val;\n  }\n\n  // Workaround for setter/getter having to be the same type.\n  setLogLevel(val: LogLevel | LogLevelString): void {\n    this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n  }\n\n  /**\n   * The main (internal) log handler for the Logger instance.\n   * Can be set to a new function in internal package code but not by user.\n   */\n  private _logHandler: LogHandler = defaultLogHandler;\n  get logHandler(): LogHandler {\n    return this._logHandler;\n  }\n  set logHandler(val: LogHandler) {\n    if (typeof val !== 'function') {\n      throw new TypeError('Value assigned to `logHandler` must be a function');\n    }\n    this._logHandler = val;\n  }\n\n  /**\n   * The optional, additional, user-defined log handler for the Logger instance.\n   */\n  private _userLogHandler: LogHandler | null = null;\n  get userLogHandler(): LogHandler | null {\n    return this._userLogHandler;\n  }\n  set userLogHandler(val: LogHandler | null) {\n    this._userLogHandler = val;\n  }\n\n  /**\n   * The functions below are all based on the `console` interface\n   */\n\n  debug(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n    this._logHandler(this, LogLevel.DEBUG, ...args);\n  }\n  log(...args: unknown[]): void {\n    this._userLogHandler &&\n      this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n    this._logHandler(this, LogLevel.VERBOSE, ...args);\n  }\n  info(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n    this._logHandler(this, LogLevel.INFO, ...args);\n  }\n  warn(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n    this._logHandler(this, LogLevel.WARN, ...args);\n  }\n  error(...args: unknown[]): void {\n    this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n    this._logHandler(this, LogLevel.ERROR, ...args);\n  }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n  instances.forEach(inst => {\n    inst.setLogLevel(level);\n  });\n}\n\nexport function setUserLogHandler(\n  logCallback: LogCallback | null,\n  options?: LogOptions\n): void {\n  for (const instance of instances) {\n    let customLogLevel: LogLevel | null = null;\n    if (options && options.level) {\n      customLogLevel = levelStringToEnum[options.level];\n    }\n    if (logCallback === null) {\n      instance.userLogHandler = null;\n    } else {\n      instance.userLogHandler = (\n        instance: Logger,\n        level: LogLevel,\n        ...args: unknown[]\n      ) => {\n        const message = args\n          .map(arg => {\n            if (arg == null) {\n              return null;\n            } else if (typeof arg === 'string') {\n              return arg;\n            } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n              return arg.toString();\n            } else if (arg instanceof Error) {\n              return arg.message;\n            } else {\n              try {\n                return JSON.stringify(arg);\n              } catch (ignored) {\n                return null;\n              }\n            }\n          })\n          .filter(arg => arg)\n          .join(' ');\n        if (level >= (customLogLevel ?? instance.logLevel)) {\n          logCallback({\n            level: LogLevel[level].toLowerCase() as LogLevelString,\n            message,\n            args,\n            type: instance.name\n          });\n        }\n      };\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n  AppCheckProvider,\n  AppCheckTokenInternal,\n  AppCheckTokenObserver\n} from './types';\nimport { Refresher } from './proactive-refresh';\nimport { Deferred } from '@firebase/util';\nimport { GreCAPTCHA } from './recaptcha';\nexport interface AppCheckState {\n  activated: boolean;\n  tokenObservers: AppCheckTokenObserver[];\n  provider?: AppCheckProvider;\n  token?: AppCheckTokenInternal;\n  cachedTokenPromise?: Promise<AppCheckTokenInternal | undefined>;\n  exchangeTokenPromise?: Promise<AppCheckTokenInternal>;\n  tokenRefresher?: Refresher;\n  reCAPTCHAState?: ReCAPTCHAState;\n  isTokenAutoRefreshEnabled?: boolean;\n}\n\nexport interface ReCAPTCHAState {\n  initialized: Deferred<GreCAPTCHA>;\n  widgetId?: string;\n  // True if the most recent recaptcha check succeeded.\n  succeeded?: boolean;\n}\n\nexport interface DebugState {\n  initialized: boolean;\n  enabled: boolean;\n  token?: Deferred<string>;\n}\n\nconst APP_CHECK_STATES = new Map<FirebaseApp, AppCheckState>();\nexport const DEFAULT_STATE: AppCheckState = {\n  activated: false,\n  tokenObservers: []\n};\n\nconst DEBUG_STATE: DebugState = {\n  initialized: false,\n  enabled: false\n};\n\n/**\n * Gets a reference to the state object.\n */\nexport function getStateReference(app: FirebaseApp): AppCheckState {\n  return APP_CHECK_STATES.get(app) || { ...DEFAULT_STATE };\n}\n\n/**\n * Set once on initialization. The map should hold the same reference to the\n * same object until this entry is deleted.\n */\nexport function setInitialState(\n  app: FirebaseApp,\n  state: AppCheckState\n): AppCheckState {\n  APP_CHECK_STATES.set(app, state);\n  return APP_CHECK_STATES.get(app) as AppCheckState;\n}\n\n// for testing only\nexport function clearState(): void {\n  APP_CHECK_STATES.clear();\n  DEBUG_STATE.enabled = false;\n  DEBUG_STATE.token = undefined;\n  DEBUG_STATE.initialized = false;\n}\n\nexport function getDebugState(): DebugState {\n  return DEBUG_STATE;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const BASE_ENDPOINT =\n  'https://content-firebaseappcheck.googleapis.com/v1';\n\nexport const EXCHANGE_RECAPTCHA_TOKEN_METHOD = 'exchangeRecaptchaV3Token';\nexport const EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD =\n  'exchangeRecaptchaEnterpriseToken';\nexport const EXCHANGE_DEBUG_TOKEN_METHOD = 'exchangeDebugToken';\n\nexport const TOKEN_REFRESH_TIME = {\n  /**\n   * The offset time before token natural expiration to run the refresh.\n   * This is currently 5 minutes.\n   */\n  OFFSET_DURATION: 5 * 60 * 1000,\n  /**\n   * This is the first retrial wait after an error. This is currently\n   * 30 seconds.\n   */\n  RETRIAL_MIN_WAIT: 30 * 1000,\n  /**\n   * This is the maximum retrial wait, currently 16 minutes.\n   */\n  RETRIAL_MAX_WAIT: 16 * 60 * 1000\n};\n\n/**\n * One day in millis, for certain error code backoffs.\n */\nexport const ONE_DAY = 24 * 60 * 60 * 1000;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from '@firebase/util';\n\n/**\n * Port from auth proactiverefresh.js\n *\n */\n// TODO: move it to @firebase/util?\n// TODO: allow to config whether refresh should happen in the background\nexport class Refresher {\n  private pending: Deferred<unknown> | null = null;\n  private nextErrorWaitInterval: number;\n  constructor(\n    private readonly operation: () => Promise<unknown>,\n    private readonly retryPolicy: (error: unknown) => boolean,\n    private readonly getWaitDuration: () => number,\n    private readonly lowerBound: number,\n    private readonly upperBound: number\n  ) {\n    this.nextErrorWaitInterval = lowerBound;\n\n    if (lowerBound > upperBound) {\n      throw new Error(\n        'Proactive refresh lower bound greater than upper bound!'\n      );\n    }\n  }\n\n  start(): void {\n    this.nextErrorWaitInterval = this.lowerBound;\n    this.process(true).catch(() => {\n      /* we don't care about the result */\n    });\n  }\n\n  stop(): void {\n    if (this.pending) {\n      this.pending.reject('cancelled');\n      this.pending = null;\n    }\n  }\n\n  isRunning(): boolean {\n    return !!this.pending;\n  }\n\n  private async process(hasSucceeded: boolean): Promise<void> {\n    this.stop();\n    try {\n      this.pending = new Deferred();\n      this.pending.promise.catch(_e => {\n        /* ignore */\n      });\n      await sleep(this.getNextRun(hasSucceeded));\n\n      // Why do we resolve a promise, then immediate wait for it?\n      // We do it to make the promise chain cancellable.\n      // We can call stop() which rejects the promise before the following line execute, which makes\n      // the code jump to the catch block.\n      // TODO: unit test this\n      this.pending.resolve();\n      await this.pending.promise;\n      this.pending = new Deferred();\n      this.pending.promise.catch(_e => {\n        /* ignore */\n      });\n      await this.operation();\n\n      this.pending.resolve();\n      await this.pending.promise;\n\n      this.process(true).catch(() => {\n        /* we don't care about the result */\n      });\n    } catch (error) {\n      if (this.retryPolicy(error)) {\n        this.process(false).catch(() => {\n          /* we don't care about the result */\n        });\n      } else {\n        this.stop();\n      }\n    }\n  }\n\n  private getNextRun(hasSucceeded: boolean): number {\n    if (hasSucceeded) {\n      // If last operation succeeded, reset next error wait interval and return\n      // the default wait duration.\n      this.nextErrorWaitInterval = this.lowerBound;\n      // Return typical wait duration interval after a successful operation.\n      return this.getWaitDuration();\n    } else {\n      // Get next error wait interval.\n      const currentErrorWaitInterval = this.nextErrorWaitInterval;\n      // Double interval for next consecutive error.\n      this.nextErrorWaitInterval *= 2;\n      // Make sure next wait interval does not exceed the maximum upper bound.\n      if (this.nextErrorWaitInterval > this.upperBound) {\n        this.nextErrorWaitInterval = this.upperBound;\n      }\n      return currentErrorWaitInterval;\n    }\n  }\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise<void>(resolve => {\n    setTimeout(resolve, ms);\n  });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppCheckError {\n  ALREADY_INITIALIZED = 'already-initialized',\n  USE_BEFORE_ACTIVATION = 'use-before-activation',\n  FETCH_NETWORK_ERROR = 'fetch-network-error',\n  FETCH_PARSE_ERROR = 'fetch-parse-error',\n  FETCH_STATUS_ERROR = 'fetch-status-error',\n  STORAGE_OPEN = 'storage-open',\n  STORAGE_GET = 'storage-get',\n  STORAGE_WRITE = 'storage-set',\n  RECAPTCHA_ERROR = 'recaptcha-error',\n  INITIAL_THROTTLE = 'initial-throttle',\n  THROTTLED = 'throttled'\n}\n\nconst ERRORS: ErrorMap<AppCheckError> = {\n  [AppCheckError.ALREADY_INITIALIZED]:\n    'You have already called initializeAppCheck() for FirebaseApp {$appName} with ' +\n    'different options. To avoid this error, call initializeAppCheck() with the ' +\n    'same options as when it was originally called. This will return the ' +\n    'already initialized instance.',\n  [AppCheckError.USE_BEFORE_ACTIVATION]:\n    'App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. ' +\n    'Call initializeAppCheck() before instantiating other Firebase services.',\n  [AppCheckError.FETCH_NETWORK_ERROR]:\n    'Fetch failed to connect to a network. Check Internet connection. ' +\n    'Original error: {$originalErrorMessage}.',\n  [AppCheckError.FETCH_PARSE_ERROR]:\n    'Fetch client could not parse response.' +\n    ' Original error: {$originalErrorMessage}.',\n  [AppCheckError.FETCH_STATUS_ERROR]:\n    'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n  [AppCheckError.STORAGE_OPEN]:\n    'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.STORAGE_GET]:\n    'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.STORAGE_WRITE]:\n    'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n  [AppCheckError.RECAPTCHA_ERROR]: 'ReCAPTCHA error.',\n  [AppCheckError.INITIAL_THROTTLE]: `{$httpStatus} error. Attempts allowed again after {$time}`,\n  [AppCheckError.THROTTLED]: `Requests throttled due to previous {$httpStatus} error. Attempts allowed again after {$time}`\n};\n\ninterface ErrorParams {\n  [AppCheckError.ALREADY_INITIALIZED]: { appName: string };\n  [AppCheckError.USE_BEFORE_ACTIVATION]: { appName: string };\n  [AppCheckError.FETCH_NETWORK_ERROR]: { originalErrorMessage: string };\n  [AppCheckError.FETCH_PARSE_ERROR]: { originalErrorMessage: string };\n  [AppCheckError.FETCH_STATUS_ERROR]: { httpStatus: number };\n  [AppCheckError.STORAGE_OPEN]: { originalErrorMessage?: string };\n  [AppCheckError.STORAGE_GET]: { originalErrorMessage?: string };\n  [AppCheckError.STORAGE_WRITE]: { originalErrorMessage?: string };\n  [AppCheckError.INITIAL_THROTTLE]: { time: string; httpStatus: number };\n  [AppCheckError.THROTTLED]: { time: string; httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AppCheckError, ErrorParams>(\n  'appCheck',\n  'AppCheck',\n  ERRORS\n);\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GreCAPTCHA } from './recaptcha';\nimport { getStateReference } from './state';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { FirebaseApp } from '@firebase/app';\n\nexport function getRecaptcha(\n  isEnterprise: boolean = false\n): GreCAPTCHA | undefined {\n  if (isEnterprise) {\n    return self.grecaptcha?.enterprise;\n  }\n  return self.grecaptcha;\n}\n\nexport function ensureActivated(app: FirebaseApp): void {\n  if (!getStateReference(app).activated) {\n    throw ERROR_FACTORY.create(AppCheckError.USE_BEFORE_ACTIVATION, {\n      appName: app.name\n    });\n  }\n}\n\nexport function getDurationString(durationInMillis: number): string {\n  const totalSeconds = Math.round(durationInMillis / 1000);\n  const days = Math.floor(totalSeconds / (3600 * 24));\n  const hours = Math.floor((totalSeconds - days * 3600 * 24) / 3600);\n  const minutes = Math.floor(\n    (totalSeconds - days * 3600 * 24 - hours * 3600) / 60\n  );\n  const seconds = totalSeconds - days * 3600 * 24 - hours * 3600 - minutes * 60;\n\n  let result = '';\n  if (days) {\n    result += pad(days) + 'd:';\n  }\n  if (hours) {\n    result += pad(hours) + 'h:';\n  }\n  result += pad(minutes) + 'm:' + pad(seconds) + 's';\n  return result;\n}\n\nfunction pad(value: number): string {\n  if (value === 0) {\n    return '00';\n  }\n  return value >= 10 ? value.toString() : '0' + value;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  BASE_ENDPOINT,\n  EXCHANGE_DEBUG_TOKEN_METHOD,\n  EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD,\n  EXCHANGE_RECAPTCHA_TOKEN_METHOD\n} from './constants';\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { Provider } from '@firebase/component';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Response JSON returned from AppCheck server endpoint.\n */\ninterface AppCheckResponse {\n  token: string;\n  // timeToLive\n  ttl: string;\n}\n\ninterface AppCheckRequest {\n  url: string;\n  body: { [key: string]: string | boolean };\n}\n\nexport async function exchangeToken(\n  { url, body }: AppCheckRequest,\n  heartbeatServiceProvider: Provider<'heartbeat'>\n): Promise<AppCheckTokenInternal> {\n  const headers: HeadersInit = {\n    'Content-Type': 'application/json'\n  };\n  // If heartbeat service exists, add heartbeat header string to the header.\n  const heartbeatService = heartbeatServiceProvider.getImmediate({\n    optional: true\n  });\n  if (heartbeatService) {\n    const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\n    if (heartbeatsHeader) {\n      headers['X-Firebase-Client'] = heartbeatsHeader;\n    }\n  }\n  const options: RequestInit = {\n    method: 'POST',\n    body: JSON.stringify(body),\n    headers\n  };\n  let response;\n  try {\n    response = await fetch(url, options);\n  } catch (originalError) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_NETWORK_ERROR, {\n      originalErrorMessage: (originalError as Error)?.message\n    });\n  }\n\n  if (response.status !== 200) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_STATUS_ERROR, {\n      httpStatus: response.status\n    });\n  }\n\n  let responseBody: AppCheckResponse;\n  try {\n    // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n    responseBody = await response.json();\n  } catch (originalError) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n      originalErrorMessage: (originalError as Error)?.message\n    });\n  }\n\n  // Protobuf duration format.\n  // https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Duration\n  const match = responseBody.ttl.match(/^([\\d.]+)(s)$/);\n  if (!match || !match[2] || isNaN(Number(match[1]))) {\n    throw ERROR_FACTORY.create(AppCheckError.FETCH_PARSE_ERROR, {\n      originalErrorMessage:\n        `ttl field (timeToLive) is not in standard Protobuf Duration ` +\n        `format: ${responseBody.ttl}`\n    });\n  }\n  const timeToLiveAsNumber = Number(match[1]) * 1000;\n\n  const now = Date.now();\n  return {\n    token: responseBody.token,\n    expireTimeMillis: now + timeToLiveAsNumber,\n    issuedAtTimeMillis: now\n  };\n}\n\nexport function getExchangeRecaptchaV3TokenRequest(\n  app: FirebaseApp,\n  reCAPTCHAToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      'recaptcha_v3_token': reCAPTCHAToken\n    }\n  };\n}\n\nexport function getExchangeRecaptchaEnterpriseTokenRequest(\n  app: FirebaseApp,\n  reCAPTCHAToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      'recaptcha_enterprise_token': reCAPTCHAToken\n    }\n  };\n}\n\nexport function getExchangeDebugTokenRequest(\n  app: FirebaseApp,\n  debugToken: string\n): AppCheckRequest {\n  const { projectId, appId, apiKey } = app.options;\n\n  return {\n    url: `${BASE_ENDPOINT}/projects/${projectId}/apps/${appId}:${EXCHANGE_DEBUG_TOKEN_METHOD}?key=${apiKey}`,\n    body: {\n      // eslint-disable-next-line\n      debug_token: debugToken\n    }\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport { AppCheckTokenInternal } from './types';\nconst DB_NAME = 'firebase-app-check-database';\nconst DB_VERSION = 1;\nconst STORE_NAME = 'firebase-app-check-store';\nconst DEBUG_TOKEN_KEY = 'debug-token';\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\nfunction getDBPromise(): Promise<IDBDatabase> {\n  if (dbPromise) {\n    return dbPromise;\n  }\n\n  dbPromise = new Promise((resolve, reject) => {\n    try {\n      const request = indexedDB.open(DB_NAME, DB_VERSION);\n\n      request.onsuccess = event => {\n        resolve((event.target as IDBOpenDBRequest).result);\n      };\n\n      request.onerror = event => {\n        reject(\n          ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n            originalErrorMessage: (event.target as IDBRequest).error?.message\n          })\n        );\n      };\n\n      request.onupgradeneeded = event => {\n        const db = (event.target as IDBOpenDBRequest).result;\n\n        // We don't use 'break' in this switch statement, the fall-through\n        // behavior is what we want, because if there are multiple versions between\n        // the old version and the current version, we want ALL the migrations\n        // that correspond to those versions to run, not only the last one.\n        // eslint-disable-next-line default-case\n        switch (event.oldVersion) {\n          case 0:\n            db.createObjectStore(STORE_NAME, {\n              keyPath: 'compositeKey'\n            });\n        }\n      };\n    } catch (e) {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_OPEN, {\n          originalErrorMessage: (e as Error)?.message\n        })\n      );\n    }\n  });\n\n  return dbPromise;\n}\n\nexport function readTokenFromIndexedDB(\n  app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n  return read(computeKey(app)) as Promise<AppCheckTokenInternal | undefined>;\n}\n\nexport function writeTokenToIndexedDB(\n  app: FirebaseApp,\n  token?: AppCheckTokenInternal\n): Promise<void> {\n  return write(computeKey(app), token);\n}\n\nexport function writeDebugTokenToIndexedDB(token: string): Promise<void> {\n  return write(DEBUG_TOKEN_KEY, token);\n}\n\nexport function readDebugTokenFromIndexedDB(): Promise<string | undefined> {\n  return read(DEBUG_TOKEN_KEY) as Promise<string | undefined>;\n}\n\nasync function write(key: string, value: unknown): Promise<void> {\n  const db = await getDBPromise();\n\n  const transaction = db.transaction(STORE_NAME, 'readwrite');\n  const store = transaction.objectStore(STORE_NAME);\n  const request = store.put({\n    compositeKey: key,\n    value\n  });\n\n  return new Promise((resolve, reject) => {\n    request.onsuccess = _event => {\n      resolve();\n    };\n\n    transaction.onerror = event => {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_WRITE, {\n          originalErrorMessage: (event.target as IDBRequest).error?.message\n        })\n      );\n    };\n  });\n}\n\nasync function read(key: string): Promise<unknown> {\n  const db = await getDBPromise();\n\n  const transaction = db.transaction(STORE_NAME, 'readonly');\n  const store = transaction.objectStore(STORE_NAME);\n  const request = store.get(key);\n\n  return new Promise((resolve, reject) => {\n    request.onsuccess = event => {\n      const result = (event.target as IDBRequest).result;\n\n      if (result) {\n        resolve(result.value);\n      } else {\n        resolve(undefined);\n      }\n    };\n\n    transaction.onerror = event => {\n      reject(\n        ERROR_FACTORY.create(AppCheckError.STORAGE_GET, {\n          originalErrorMessage: (event.target as IDBRequest).error?.message\n        })\n      );\n    };\n  });\n}\n\nfunction computeKey(app: FirebaseApp): string {\n  return `${app.options.appId}-${app.name}`;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app-check');\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { isIndexedDBAvailable } from '@firebase/util';\nimport {\n  readDebugTokenFromIndexedDB,\n  readTokenFromIndexedDB,\n  writeDebugTokenToIndexedDB,\n  writeTokenToIndexedDB\n} from './indexeddb';\nimport { logger } from './logger';\nimport { AppCheckTokenInternal } from './types';\n\n/**\n * Always resolves. In case of an error reading from indexeddb, resolve with undefined\n */\nexport async function readTokenFromStorage(\n  app: FirebaseApp\n): Promise<AppCheckTokenInternal | undefined> {\n  if (isIndexedDBAvailable()) {\n    let token = undefined;\n    try {\n      token = await readTokenFromIndexedDB(app);\n    } catch (e) {\n      // swallow the error and return undefined\n      logger.warn(`Failed to read token from IndexedDB. Error: ${e}`);\n    }\n    return token;\n  }\n\n  return undefined;\n}\n\n/**\n * Always resolves. In case of an error writing to indexeddb, print a warning and resolve the promise\n */\nexport function writeTokenToStorage(\n  app: FirebaseApp,\n  token?: AppCheckTokenInternal\n): Promise<void> {\n  if (isIndexedDBAvailable()) {\n    return writeTokenToIndexedDB(app, token).catch(e => {\n      // swallow the error and resolve the promise\n      logger.warn(`Failed to write token to IndexedDB. Error: ${e}`);\n    });\n  }\n\n  return Promise.resolve();\n}\n\nexport async function readOrCreateDebugTokenFromStorage(): Promise<string> {\n  /**\n   * Theoretically race condition can happen if we read, then write in 2 separate transactions.\n   * But it won't happen here, because this function will be called exactly once.\n   */\n  let existingDebugToken: string | undefined = undefined;\n  try {\n    existingDebugToken = await readDebugTokenFromIndexedDB();\n  } catch (_e) {\n    // failed to read from indexeddb. We assume there is no existing debug token, and generate a new one.\n  }\n\n  if (!existingDebugToken) {\n    // create a new debug token\n    // This function is only available in secure contexts. See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts\n    const newToken = crypto.randomUUID();\n    // We don't need to block on writing to indexeddb\n    // In case persistence failed, a new debug token will be generated every time the page is refreshed.\n    // It renders the debug token useless because you have to manually register(whitelist) the new token in the firebase console again and again.\n    // If you see this error trying to use debug token, it probably means you are using a browser that doesn't support indexeddb.\n    // You should switch to a different browser that supports indexeddb\n    writeDebugTokenToIndexedDB(newToken).catch(e =>\n      logger.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)\n    );\n    return newToken;\n  } else {\n    return existingDebugToken;\n  }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getDebugState } from './state';\nimport { readOrCreateDebugTokenFromStorage } from './storage';\nimport { Deferred, getGlobal } from '@firebase/util';\n\ndeclare global {\n  // var must be used for global scopes\n  // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis\n  // eslint-disable-next-line no-var\n  var FIREBASE_APPCHECK_DEBUG_TOKEN: boolean | string | undefined;\n}\n\nexport function isDebugMode(): boolean {\n  const debugState = getDebugState();\n  return debugState.enabled;\n}\n\nexport async function getDebugToken(): Promise<string> {\n  const state = getDebugState();\n\n  if (state.enabled && state.token) {\n    return state.token.promise;\n  } else {\n    // should not happen!\n    throw Error(`\n            Can't get debug token in production mode.\n        `);\n  }\n}\n\nexport function initializeDebugMode(): void {\n  const globals = getGlobal();\n  const debugState = getDebugState();\n  // Set to true if this function has been called, whether or not\n  // it enabled debug mode.\n  debugState.initialized = true;\n\n  if (\n    typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== 'string' &&\n    globals.FIREBASE_APPCHECK_DEBUG_TOKEN !== true\n  ) {\n    return;\n  }\n\n  debugState.enabled = true;\n  const deferredToken = new Deferred<string>();\n  debugState.token = deferredToken;\n\n  if (typeof globals.FIREBASE_APPCHECK_DEBUG_TOKEN === 'string') {\n    deferredToken.resolve(globals.FIREBASE_APPCHECK_DEBUG_TOKEN);\n  } else {\n    deferredToken.resolve(readOrCreateDebugTokenFromStorage());\n  }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n  if (typeof self !== 'undefined') {\n    return self;\n  }\n  if (typeof window !== 'undefined') {\n    return window;\n  }\n  if (typeof global !== 'undefined') {\n    return global;\n  }\n  throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n  AppCheckTokenResult,\n  AppCheckTokenInternal,\n  AppCheckTokenObserver,\n  ListenerType\n} from './types';\nimport { AppCheckTokenListener } from './public-types';\nimport { getStateReference } from './state';\nimport { TOKEN_REFRESH_TIME } from './constants';\nimport { Refresher } from './proactive-refresh';\nimport { ensureActivated } from './util';\nimport { exchangeToken, getExchangeDebugTokenRequest } from './client';\nimport { writeTokenToStorage } from './storage';\nimport { getDebugToken, isDebugMode } from './debug';\nimport { base64, FirebaseError } from '@firebase/util';\nimport { logger } from './logger';\nimport { AppCheckService } from './factory';\nimport { AppCheckError } from './errors';\n\n// Initial hardcoded value agreed upon across platforms for initial launch.\n// Format left open for possible dynamic error values and other fields in the future.\nexport const defaultTokenErrorData = { error: 'UNKNOWN_ERROR' };\n\n/**\n * Stringify and base64 encode token error data.\n *\n * @param tokenError Error data, currently hardcoded.\n */\nexport function formatDummyToken(\n  tokenErrorData: Record<string, string>\n): string {\n  return base64.encodeString(\n    JSON.stringify(tokenErrorData),\n    /* webSafe= */ false\n  );\n}\n\n/**\n * This function always resolves.\n * The result will contain an error field if there is any error.\n * In case there is an error, the token field in the result will be populated with a dummy value\n */\nexport async function getToken(\n  appCheck: AppCheckService,\n  forceRefresh = false,\n  shouldLogErrors = false\n): Promise<AppCheckTokenResult> {\n  const app = appCheck.app;\n  ensureActivated(app);\n\n  const state = getStateReference(app);\n\n  /**\n   * First check if there is a token in memory from a previous `getToken()` call.\n   */\n  let token: AppCheckTokenInternal | undefined = state.token;\n  let error: Error | undefined = undefined;\n\n  /**\n   * If an invalid token was found in memory, clear token from\n   * memory and unset the local variable `token`.\n   */\n  if (token && !isValid(token)) {\n    state.token = undefined;\n    token = undefined;\n  }\n\n  /**\n   * If there is no valid token in memory, try to load token from indexedDB.\n   */\n  if (!token) {\n    // cachedTokenPromise contains the token found in IndexedDB or undefined if not found.\n    const cachedToken = await state.cachedTokenPromise;\n    if (cachedToken) {\n      if (isValid(cachedToken)) {\n        token = cachedToken;\n      } else {\n        // If there was an invalid token in the indexedDB cache, clear it.\n        await writeTokenToStorage(app, undefined);\n      }\n    }\n  }\n\n  // Return the cached token (from either memory or indexedDB) if it's valid\n  if (!forceRefresh && token && isValid(token)) {\n    return {\n      token: token.token\n    };\n  }\n\n  // Only set to true if this `getToken()` call is making the actual\n  // REST call to the exchange endpoint, versus waiting for an already\n  // in-flight call (see debug and regular exchange endpoint paths below)\n  let shouldCallListeners = false;\n\n  /**\n   * DEBUG MODE\n   * If debug mode is set, and there is no cached token, fetch a new App\n   * Check token using the debug token, and return it directly.\n   */\n  if (isDebugMode()) {\n    try {\n      const debugToken = await getDebugToken();\n      // Avoid making another call to the exchange endpoint if one is in flight.\n      if (!state.exchangeTokenPromise) {\n        state.exchangeTokenPromise = exchangeToken(\n          getExchangeDebugTokenRequest(app, debugToken),\n          appCheck.heartbeatServiceProvider\n        ).finally(() => {\n          // Clear promise when settled - either resolved or rejected.\n          state.exchangeTokenPromise = undefined;\n        });\n        shouldCallListeners = true;\n      }\n      const tokenFromDebugExchange: AppCheckTokenInternal =\n        await state.exchangeTokenPromise;\n      // Write debug token to indexedDB.\n      await writeTokenToStorage(app, tokenFromDebugExchange);\n      // Write debug token to state.\n      state.token = tokenFromDebugExchange;\n      return { token: tokenFromDebugExchange.token };\n    } catch (e) {\n      if (\n        (e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}` ||\n        (e as FirebaseError).code ===\n          `appCheck/${AppCheckError.INITIAL_THROTTLE}`\n      ) {\n        // Warn if throttled, but do not treat it as an error.\n        logger.warn((e as FirebaseError).message);\n      } else if (shouldLogErrors) {\n        logger.error(e);\n      }\n      // Return dummy token and error\n      return makeDummyTokenResult(e as FirebaseError);\n    }\n  }\n\n  /**\n   * There are no valid tokens in memory or indexedDB and we are not in\n   * debug mode.\n   * Request a new token from the exchange endpoint.\n   */\n  try {\n    // Avoid making another call to the exchange endpoint if one is in flight.\n    if (!state.exchangeTokenPromise) {\n      // state.provider is populated in initializeAppCheck()\n      // ensureActivated() at the top of this function checks that\n      // initializeAppCheck() has been called.\n      state.exchangeTokenPromise = state.provider!.getToken().finally(() => {\n        // Clear promise when settled - either resolved or rejected.\n        state.exchangeTokenPromise = undefined;\n      });\n      shouldCallListeners = true;\n    }\n    token = await getStateReference(app).exchangeTokenPromise;\n  } catch (e) {\n    if (\n      (e as FirebaseError).code === `appCheck/${AppCheckError.THROTTLED}` ||\n      (e as FirebaseError).code === `appCheck/${AppCheckError.INITIAL_THROTTLE}`\n    ) {\n      // Warn if throttled, but do not treat it as an error.\n      logger.warn((e as FirebaseError).message);\n    } else if (shouldLogErrors) {\n      logger.error(e);\n    }\n    // Always save error to be added to dummy token.\n    error = e as FirebaseError;\n  }\n\n  let interopTokenResult: AppCheckTokenResult | undefined;\n  if (!token) {\n    // If token is undefined, there must be an error.\n    // Return a dummy token along with the error.\n    interopTokenResult = makeDummyTokenResult(error!);\n  } else if (error) {\n    if (isValid(token)) {\n      // It's also possible a valid token exists, but there's also an error.\n      // (Such as if the token is almost expired, tries to refresh, and\n      // the exchange request fails.)\n      // We add a special error property here so that the refresher will\n      // count this as a failed attempt and use the backoff instead of\n      // retrying repeatedly with no delay, but any 3P listeners will not\n      // be hindered in getting the still-valid token.\n      interopTokenResult = {\n        token: token.token,\n        internalError: error\n      };\n    } else {\n      // No invalid tokens should make it to this step. Memory and cached tokens\n      // are checked. Other tokens are from fresh exchanges. But just in case.\n      interopTokenResult = makeDummyTokenResult(error!);\n    }\n  } else {\n    interopTokenResult = {\n      token: token.token\n    };\n    // write the new token to the memory state as well as the persistent storage.\n    // Only do it if we got a valid new token\n    state.token = token;\n    await writeTokenToStorage(app, token);\n  }\n\n  if (shouldCallListeners) {\n    notifyTokenListeners(app, interopTokenResult);\n  }\n  return interopTokenResult;\n}\n\n/**\n * Internal API for limited use tokens. Skips all FAC state and simply calls\n * the underlying provider.\n */\nexport async function getLimitedUseToken(\n  appCheck: AppCheckService\n): Promise<AppCheckTokenResult> {\n  const app = appCheck.app;\n  ensureActivated(app);\n\n  const { provider } = getStateReference(app);\n\n  if (isDebugMode()) {\n    const debugToken = await getDebugToken();\n    const request = getExchangeDebugTokenRequest(app, debugToken);\n    request.body['limited_use'] = true;\n    const { token } = await exchangeToken(\n      request,\n      appCheck.heartbeatServiceProvider\n    );\n    return { token };\n  } else {\n    // provider is definitely valid since we ensure AppCheck was activated\n    const { token } = await provider!.getToken(true /* isLimitedUse */);\n    return { token };\n  }\n}\n\nexport function addTokenListener(\n  appCheck: AppCheckService,\n  type: ListenerType,\n  listener: AppCheckTokenListener,\n  onError?: (error: Error) => void\n): void {\n  const { app } = appCheck;\n  const state = getStateReference(app);\n  const tokenObserver: AppCheckTokenObserver = {\n    next: listener,\n    error: onError,\n    type\n  };\n  state.tokenObservers = [...state.tokenObservers, tokenObserver];\n\n  // Invoke the listener async immediately if there is a valid token\n  // in memory.\n  if (state.token && isValid(state.token)) {\n    const validToken = state.token;\n    Promise.resolve()\n      .then(() => {\n        listener({ token: validToken.token });\n        initTokenRefresher(appCheck);\n      })\n      .catch(() => {\n        /* we don't care about exceptions thrown in listeners */\n      });\n  }\n\n  /**\n   * Wait for any cached token promise to resolve before starting the token\n   * refresher. The refresher checks to see if there is an existing token\n   * in state and calls the exchange endpoint if not. We should first let the\n   * IndexedDB check have a chance to populate state if it can.\n   *\n   * Listener call isn't needed here because cachedTokenPromise will call any\n   * listeners that exist when it resolves.\n   */\n\n  // state.cachedTokenPromise is always populated in `activate()`.\n  void state.cachedTokenPromise!.then(() => initTokenRefresher(appCheck));\n}\n\nexport function removeTokenListener(\n  app: FirebaseApp,\n  listener: AppCheckTokenListener\n): void {\n  const state = getStateReference(app);\n\n  const newObservers = state.tokenObservers.filter(\n    tokenObserver => tokenObserver.next !== listener\n  );\n  if (\n    newObservers.length === 0 &&\n    state.tokenRefresher &&\n    state.tokenRefresher.isRunning()\n  ) {\n    state.tokenRefresher.stop();\n  }\n\n  state.tokenObservers = newObservers;\n}\n\n/**\n * Logic to create and start refresher as needed.\n */\nfunction initTokenRefresher(appCheck: AppCheckService): void {\n  const { app } = appCheck;\n  const state = getStateReference(app);\n  // Create the refresher but don't start it if `isTokenAutoRefreshEnabled`\n  // is not true.\n  let refresher: Refresher | undefined = state.tokenRefresher;\n  if (!refresher) {\n    refresher = createTokenRefresher(appCheck);\n    state.tokenRefresher = refresher;\n  }\n  if (!refresher.isRunning() && state.isTokenAutoRefreshEnabled) {\n    refresher.start();\n  }\n}\n\nfunction createTokenRefresher(appCheck: AppCheckService): Refresher {\n  const { app } = appCheck;\n  return new Refresher(\n    // Keep in mind when this fails for any reason other than the ones\n    // for which we should retry, it will effectively stop the proactive refresh.\n    async () => {\n      const state = getStateReference(app);\n      // If there is no token, we will try to load it from storage and use it\n      // If there is a token, we force refresh it because we know it's going to expire soon\n      let result;\n      if (!state.token) {\n        result = await getToken(appCheck);\n      } else {\n        result = await getToken(appCheck, true);\n      }\n\n      /**\n       * getToken() always resolves. In case the result has an error field defined, it means\n       * the operation failed, and we should retry.\n       */\n      if (result.error) {\n        throw result.error;\n      }\n      /**\n       * A special `internalError` field reflects that there was an error\n       * getting a new token from the exchange endpoint, but there's still a\n       * previous token that's valid for now and this should be passed to 2P/3P\n       * requests for a token. But we want this callback (`this.operation` in\n       * `Refresher`) to throw in order to kick off the Refresher's retry\n       * backoff. (Setting `hasSucceeded` to false.)\n       */\n      if (result.internalError) {\n        throw result.internalError;\n      }\n    },\n    () => {\n      return true;\n    },\n    () => {\n      const state = getStateReference(app);\n\n      if (state.token) {\n        // issuedAtTime + (50% * total TTL) + 5 minutes\n        let nextRefreshTimeMillis =\n          state.token.issuedAtTimeMillis +\n          (state.token.expireTimeMillis - state.token.issuedAtTimeMillis) *\n            0.5 +\n          5 * 60 * 1000;\n        // Do not allow refresh time to be past (expireTime - 5 minutes)\n        const latestAllowableRefresh =\n          state.token.expireTimeMillis - 5 * 60 * 1000;\n        nextRefreshTimeMillis = Math.min(\n          nextRefreshTimeMillis,\n          latestAllowableRefresh\n        );\n        return Math.max(0, nextRefreshTimeMillis - Date.now());\n      } else {\n        return 0;\n      }\n    },\n    TOKEN_REFRESH_TIME.RETRIAL_MIN_WAIT,\n    TOKEN_REFRESH_TIME.RETRIAL_MAX_WAIT\n  );\n}\n\nexport function notifyTokenListeners(\n  app: FirebaseApp,\n  token: AppCheckTokenResult\n): void {\n  const observers = getStateReference(app).tokenObservers;\n\n  for (const observer of observers) {\n    try {\n      if (observer.type === ListenerType.EXTERNAL && token.error != null) {\n        // If this listener was added by a 3P call, send any token error to\n        // the supplied error handler. A 3P observer always has an error\n        // handler.\n        observer.error!(token.error);\n      } else {\n        // If the token has no error field, always return the token.\n        // If this is a 2P listener, return the token, whether or not it\n        // has an error field.\n        observer.next(token);\n      }\n    } catch (e) {\n      // Errors in the listener function itself are always ignored.\n    }\n  }\n}\n\nexport function isValid(token: AppCheckTokenInternal): boolean {\n  return token.expireTimeMillis - Date.now() > 0;\n}\n\nfunction makeDummyTokenResult(error: Error): AppCheckTokenResult {\n  return {\n    token: formatDummyToken(defaultTokenErrorData),\n    error\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheck } from './public-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { FirebaseAppCheckInternal, ListenerType } from './types';\nimport {\n  getToken,\n  getLimitedUseToken,\n  addTokenListener,\n  removeTokenListener\n} from './internal-api';\nimport { Provider } from '@firebase/component';\nimport { getStateReference } from './state';\n\n/**\n * AppCheck Service class.\n */\nexport class AppCheckService implements AppCheck, _FirebaseService {\n  constructor(\n    public app: FirebaseApp,\n    public heartbeatServiceProvider: Provider<'heartbeat'>\n  ) {}\n  _delete(): Promise<void> {\n    const { tokenObservers } = getStateReference(this.app);\n    for (const tokenObserver of tokenObservers) {\n      removeTokenListener(this.app, tokenObserver.next);\n    }\n    return Promise.resolve();\n  }\n}\n\nexport function factory(\n  app: FirebaseApp,\n  heartbeatServiceProvider: Provider<'heartbeat'>\n): AppCheckService {\n  return new AppCheckService(app, heartbeatServiceProvider);\n}\n\nexport function internalFactory(\n  appCheck: AppCheckService\n): FirebaseAppCheckInternal {\n  return {\n    getToken: forceRefresh => getToken(appCheck, forceRefresh),\n    getLimitedUseToken: () => getLimitedUseToken(appCheck),\n    addTokenListener: listener =>\n      addTokenListener(appCheck, ListenerType.INTERNAL, listener),\n    removeTokenListener: listener => removeTokenListener(appCheck.app, listener)\n  };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport { getStateReference } from './state';\nimport { Deferred } from '@firebase/util';\nimport { getRecaptcha, ensureActivated } from './util';\n\nexport const RECAPTCHA_URL = 'https://www.google.com/recaptcha/api.js';\nexport const RECAPTCHA_ENTERPRISE_URL =\n  'https://www.google.com/recaptcha/enterprise.js';\n\nexport function initializeV3(\n  app: FirebaseApp,\n  siteKey: string\n): Promise<GreCAPTCHA> {\n  const initialized = new Deferred<GreCAPTCHA>();\n\n  const state = getStateReference(app);\n  state.reCAPTCHAState = { initialized };\n\n  const divId = makeDiv(app);\n\n  const grecaptcha = getRecaptcha(false);\n  if (!grecaptcha) {\n    loadReCAPTCHAV3Script(() => {\n      const grecaptcha = getRecaptcha(false);\n\n      if (!grecaptcha) {\n        // it shouldn't happen.\n        throw new Error('no recaptcha');\n      }\n      queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n    });\n  } else {\n    queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n  }\n  return initialized.promise;\n}\nexport function initializeEnterprise(\n  app: FirebaseApp,\n  siteKey: string\n): Promise<GreCAPTCHA> {\n  const initialized = new Deferred<GreCAPTCHA>();\n\n  const state = getStateReference(app);\n  state.reCAPTCHAState = { initialized };\n\n  const divId = makeDiv(app);\n\n  const grecaptcha = getRecaptcha(true);\n  if (!grecaptcha) {\n    loadReCAPTCHAEnterpriseScript(() => {\n      const grecaptcha = getRecaptcha(true);\n\n      if (!grecaptcha) {\n        // it shouldn't happen.\n        throw new Error('no recaptcha');\n      }\n      queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n    });\n  } else {\n    queueWidgetRender(app, siteKey, grecaptcha, divId, initialized);\n  }\n  return initialized.promise;\n}\n\n/**\n * Add listener to render the widget and resolve the promise when\n * the grecaptcha.ready() event fires.\n */\nfunction queueWidgetRender(\n  app: FirebaseApp,\n  siteKey: string,\n  grecaptcha: GreCAPTCHA,\n  container: string,\n  initialized: Deferred<GreCAPTCHA>\n): void {\n  grecaptcha.ready(() => {\n    // Invisible widgets allow us to set a different siteKey for each widget,\n    // so we use them to support multiple apps\n    renderInvisibleWidget(app, siteKey, grecaptcha, container);\n    initialized.resolve(grecaptcha);\n  });\n}\n\n/**\n * Add invisible div to page.\n */\nfunction makeDiv(app: FirebaseApp): string {\n  const divId = `fire_app_check_${app.name}`;\n  const invisibleDiv = document.createElement('div');\n  invisibleDiv.id = divId;\n  invisibleDiv.style.display = 'none';\n\n  document.body.appendChild(invisibleDiv);\n  return divId;\n}\n\nexport async function getToken(app: FirebaseApp): Promise<string> {\n  ensureActivated(app);\n\n  // ensureActivated() guarantees that reCAPTCHAState is set\n  const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n  const recaptcha = await reCAPTCHAState.initialized.promise;\n\n  return new Promise((resolve, _reject) => {\n    // Updated after initialization is complete.\n    const reCAPTCHAState = getStateReference(app).reCAPTCHAState!;\n    recaptcha.ready(() => {\n      resolve(\n        // widgetId is guaranteed to be available if reCAPTCHAState.initialized.promise resolved.\n        recaptcha.execute(reCAPTCHAState.widgetId!, {\n          action: 'fire_app_check'\n        })\n      );\n    });\n  });\n}\n\n/**\n *\n * @param app\n * @param container - Id of a HTML element.\n */\nfunction renderInvisibleWidget(\n  app: FirebaseApp,\n  siteKey: string,\n  grecaptcha: GreCAPTCHA,\n  container: string\n): void {\n  const widgetId = grecaptcha.render(container, {\n    sitekey: siteKey,\n    size: 'invisible',\n    // Success callback - set state\n    callback: () => {\n      getStateReference(app).reCAPTCHAState!.succeeded = true;\n    },\n    // Failure callback - set state\n    'error-callback': () => {\n      getStateReference(app).reCAPTCHAState!.succeeded = false;\n    }\n  });\n\n  const state = getStateReference(app);\n\n  state.reCAPTCHAState = {\n    ...state.reCAPTCHAState!, // state.reCAPTCHAState is set in the initialize()\n    widgetId\n  };\n}\n\nfunction loadReCAPTCHAV3Script(onload: () => void): void {\n  const script = document.createElement('script');\n  script.src = RECAPTCHA_URL;\n  script.onload = onload;\n  document.head.appendChild(script);\n}\n\nfunction loadReCAPTCHAEnterpriseScript(onload: () => void): void {\n  const script = document.createElement('script');\n  // This param is required when we plan to render a widget explicitly.\n  script.src = RECAPTCHA_ENTERPRISE_URL + '?render=explicit';\n  script.onload = onload;\n  document.head.appendChild(script);\n}\n\ndeclare global {\n  interface Window {\n    grecaptcha: GreCAPTCHATopLevel | undefined;\n  }\n}\n\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n  enterprise: GreCAPTCHA;\n}\n\nexport interface GreCAPTCHA {\n  ready: (callback: () => void) => void;\n  execute: (siteKey: string, options: { action: string }) => Promise<string>;\n  render: (\n    container: string | HTMLElement,\n    parameters: GreCAPTCHARenderOption\n  ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n  sitekey: string;\n  size: 'invisible';\n  callback: () => void;\n  'error-callback': () => void;\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _getProvider } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport {\n  FirebaseError,\n  issuedAtTime,\n  calculateBackoffMillis\n} from '@firebase/util';\nimport {\n  exchangeToken,\n  getExchangeRecaptchaEnterpriseTokenRequest,\n  getExchangeRecaptchaV3TokenRequest\n} from './client';\nimport { ONE_DAY } from './constants';\nimport { AppCheckError, ERROR_FACTORY } from './errors';\nimport { CustomProviderOptions } from './public-types';\nimport {\n  getToken as getReCAPTCHAToken,\n  initializeV3 as initializeRecaptchaV3,\n  initializeEnterprise as initializeRecaptchaEnterprise\n} from './recaptcha';\nimport { getStateReference } from './state';\nimport { AppCheckProvider, AppCheckTokenInternal, ThrottleData } from './types';\nimport { getDurationString } from './util';\n\n/**\n * App Check provider that can obtain a reCAPTCHA V3 token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaV3Provider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n  private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n  /**\n   * Throttle requests on certain error codes to prevent too many retries\n   * in a short time.\n   */\n  private _throttleData: ThrottleData | null = null;\n  /**\n   * Create a ReCaptchaV3Provider instance.\n   * @param siteKey - ReCAPTCHA V3 siteKey.\n   */\n  constructor(private _siteKey: string) {}\n\n  /**\n   * Returns an App Check token.\n   * @internal\n   */\n  async getToken(\n    isLimitedUse: boolean = false\n  ): Promise<AppCheckTokenInternal> {\n    throwIfThrottled(this._throttleData);\n\n    // Top-level `getToken()` has already checked that App Check is initialized\n    // and therefore this._app and this._heartbeatServiceProvider are available.\n    const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n      _e => {\n        // reCaptcha.execute() throws null which is not very descriptive.\n        throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n      }\n    );\n    // Check if a failure state was set by the recaptcha \"error-callback\".\n    if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n      throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n    }\n    let result;\n    try {\n      const request = getExchangeRecaptchaV3TokenRequest(\n        this._app!,\n        attestedClaimsToken\n      );\n      if (isLimitedUse) {\n        request.body['limited_use'] = true;\n      }\n      result = await exchangeToken(request, this._heartbeatServiceProvider!);\n    } catch (e) {\n      if (\n        (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n      ) {\n        this._throttleData = setBackoff(\n          Number((e as FirebaseError).customData?.httpStatus),\n          this._throttleData\n        );\n        throw ERROR_FACTORY.create(AppCheckError.INITIAL_THROTTLE, {\n          time: getDurationString(\n            this._throttleData.allowRequestsAfter - Date.now()\n          ),\n          httpStatus: this._throttleData.httpStatus\n        });\n      } else {\n        throw e;\n      }\n    }\n    // If successful, clear throttle data.\n    this._throttleData = null;\n    return result;\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n    this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n    initializeRecaptchaV3(app, this._siteKey).catch(() => {\n      /* we don't care about the initialization result */\n    });\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof ReCaptchaV3Provider) {\n      return this._siteKey === otherProvider._siteKey;\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * App Check provider that can obtain a reCAPTCHA Enterprise token and exchange it\n * for an App Check token.\n *\n * @public\n */\nexport class ReCaptchaEnterpriseProvider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n  private _heartbeatServiceProvider?: Provider<'heartbeat'>;\n  /**\n   * Throttle requests on certain error codes to prevent too many retries\n   * in a short time.\n   */\n  private _throttleData: ThrottleData | null = null;\n  /**\n   * Create a ReCaptchaEnterpriseProvider instance.\n   * @param siteKey - reCAPTCHA Enterprise score-based site key.\n   */\n  constructor(private _siteKey: string) {}\n\n  /**\n   * Returns an App Check token.\n   * @internal\n   */\n  async getToken(\n    isLimitedUse: boolean = false\n  ): Promise<AppCheckTokenInternal> {\n    throwIfThrottled(this._throttleData);\n    // Top-level `getToken()` has already checked that App Check is initialized\n    // and therefore this._app and this._heartbeatServiceProvider are available.\n    const attestedClaimsToken = await getReCAPTCHAToken(this._app!).catch(\n      _e => {\n        // reCaptcha.execute() throws null which is not very descriptive.\n        throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n      }\n    );\n    // Check if a failure state was set by the recaptcha \"error-callback\".\n    if (!getStateReference(this._app!).reCAPTCHAState?.succeeded) {\n      throw ERROR_FACTORY.create(AppCheckError.RECAPTCHA_ERROR);\n    }\n    let result;\n    try {\n      const request = getExchangeRecaptchaEnterpriseTokenRequest(\n        this._app!,\n        attestedClaimsToken\n      );\n      if (isLimitedUse) {\n        request.body['limited_use'] = true;\n      }\n      result = await exchangeToken(request, this._heartbeatServiceProvider!);\n    } catch (e) {\n      if (\n        (e as FirebaseError).code?.includes(AppCheckError.FETCH_STATUS_ERROR)\n      ) {\n        this._throttleData = setBackoff(\n          Number((e as FirebaseError).customData?.httpStatus),\n          this._throttleData\n        );\n        throw ERROR_FACTORY.create(AppCheckError.INITIAL_THROTTLE, {\n          time: getDurationString(\n            this._throttleData.allowRequestsAfter - Date.now()\n          ),\n          httpStatus: this._throttleData.httpStatus\n        });\n      } else {\n        throw e;\n      }\n    }\n    // If successful, clear throttle data.\n    this._throttleData = null;\n    return result;\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n    this._heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n    initializeRecaptchaEnterprise(app, this._siteKey).catch(() => {\n      /* we don't care about the initialization result */\n    });\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof ReCaptchaEnterpriseProvider) {\n      return this._siteKey === otherProvider._siteKey;\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * Custom provider class.\n * @public\n */\nexport class CustomProvider implements AppCheckProvider {\n  private _app?: FirebaseApp;\n\n  constructor(private _customProviderOptions: CustomProviderOptions) {}\n\n  /**\n   * @internal\n   */\n  async getToken(): Promise<AppCheckTokenInternal> {\n    // custom provider\n    const customToken = await this._customProviderOptions.getToken();\n    // Try to extract IAT from custom token, in case this token is not\n    // being newly issued. JWT timestamps are in seconds since epoch.\n    const issuedAtTimeSeconds = issuedAtTime(customToken.token);\n    // Very basic validation, use current timestamp as IAT if JWT\n    // has no `iat` field or value is out of bounds.\n    const issuedAtTimeMillis =\n      issuedAtTimeSeconds !== null &&\n      issuedAtTimeSeconds < Date.now() &&\n      issuedAtTimeSeconds > 0\n        ? issuedAtTimeSeconds * 1000\n        : Date.now();\n\n    return { ...customToken, issuedAtTimeMillis };\n  }\n\n  /**\n   * @internal\n   */\n  initialize(app: FirebaseApp): void {\n    this._app = app;\n  }\n\n  /**\n   * @internal\n   */\n  isEqual(otherProvider: unknown): boolean {\n    if (otherProvider instanceof CustomProvider) {\n      return (\n        this._customProviderOptions.getToken.toString() ===\n        otherProvider._customProviderOptions.getToken.toString()\n      );\n    } else {\n      return false;\n    }\n  }\n}\n\n/**\n * Set throttle data to block requests until after a certain time\n * depending on the failed request's status code.\n * @param httpStatus - Status code of failed request.\n * @param throttleData - `ThrottleData` object containing previous throttle\n * data state.\n * @returns Data about current throttle state and expiration time.\n */\nfunction setBackoff(\n  httpStatus: number,\n  throttleData: ThrottleData | null\n): ThrottleData {\n  /**\n   * Block retries for 1 day for the following error codes:\n   *\n   * 404: Likely malformed URL.\n   *\n   * 403:\n   * - Attestation failed\n   * - Wrong API key\n   * - Project deleted\n   */\n  if (httpStatus === 404 || httpStatus === 403) {\n    return {\n      backoffCount: 1,\n      allowRequestsAfter: Date.now() + ONE_DAY,\n      httpStatus\n    };\n  } else {\n    /**\n     * For all other error codes, the time when it is ok to retry again\n     * is based on exponential backoff.\n     */\n    const backoffCount = throttleData ? throttleData.backoffCount : 0;\n    const backoffMillis = calculateBackoffMillis(backoffCount, 1000, 2);\n    return {\n      backoffCount: backoffCount + 1,\n      allowRequestsAfter: Date.now() + backoffMillis,\n      httpStatus\n    };\n  }\n}\n\nfunction throwIfThrottled(throttleData: ThrottleData | null): void {\n  if (throttleData) {\n    if (Date.now() - throttleData.allowRequestsAfter <= 0) {\n      // If before, throw.\n      throw ERROR_FACTORY.create(AppCheckError.THROTTLED, {\n        time: getDurationString(throttleData.allowRequestsAfter - Date.now()),\n        httpStatus: throttleData.httpStatus\n      });\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The amount of milliseconds to exponentially increase.\n */\nconst DEFAULT_INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(\n  backoffCount: number,\n  intervalMillis: number = DEFAULT_INTERVAL_MILLIS,\n  backoffFactor: number = DEFAULT_BACKOFF_FACTOR\n): number {\n  // Calculates an exponentially increasing value.\n  // Deviation: calculates value from count and a constant interval, so we only need to save value\n  // and count to restore state.\n  const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\n\n  // A random \"fuzz\" to avoid waves of retries.\n  // Deviation: randomFactor is required.\n  const randomWait = Math.round(\n    // A fraction of the backoff value to add/subtract.\n    // Deviation: changes multiplication order to improve readability.\n    RANDOM_FACTOR *\n      currBaseValue *\n      // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n      // if we add or subtract.\n      (Math.random() - 0.5) *\n      2\n  );\n\n  // Limits backoff to max to avoid effectively permanent backoff.\n  return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n  AppCheck,\n  AppCheckOptions,\n  AppCheckTokenResult,\n  Unsubscribe,\n  PartialObserver\n} from './public-types';\nimport { ERROR_FACTORY, AppCheckError } from './errors';\nimport {\n  getStateReference,\n  getDebugState,\n  DEFAULT_STATE,\n  setInitialState\n} from './state';\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\nimport { getModularInstance, ErrorFn, NextFn } from '@firebase/util';\nimport { AppCheckService } from './factory';\nimport { AppCheckProvider, ListenerType } from './types';\nimport {\n  getToken as getTokenInternal,\n  getLimitedUseToken as getLimitedUseTokenInternal,\n  addTokenListener,\n  removeTokenListener,\n  isValid,\n  notifyTokenListeners\n} from './internal-api';\nimport { readTokenFromStorage } from './storage';\nimport { getDebugToken, initializeDebugMode, isDebugMode } from './debug';\nimport { logger } from './logger';\n\ndeclare module '@firebase/component' {\n  interface NameServiceMapping {\n    'app-check': AppCheckService;\n  }\n}\n\nexport {\n  ReCaptchaV3Provider,\n  CustomProvider,\n  ReCaptchaEnterpriseProvider\n} from './providers';\n\n/**\n * Activate App Check for the given app. Can be called only once per app.\n * @param app - the {@link @firebase/app#FirebaseApp} to activate App Check for\n * @param options - App Check initialization options\n * @public\n */\nexport function initializeAppCheck(\n  app: FirebaseApp = getApp(),\n  options: AppCheckOptions\n): AppCheck {\n  app = getModularInstance(app);\n  const provider = _getProvider(app, 'app-check');\n\n  // Ensure initializeDebugMode() is only called once.\n  if (!getDebugState().initialized) {\n    initializeDebugMode();\n  }\n\n  // Log a message containing the debug token when `initializeAppCheck()`\n  // is called in debug mode.\n  if (isDebugMode()) {\n    // Do not block initialization to get the token for the message.\n    void getDebugToken().then(token =>\n      // Not using logger because I don't think we ever want this accidentally hidden.\n      console.log(\n        `App Check debug token: ${token}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`\n      )\n    );\n  }\n\n  if (provider.isInitialized()) {\n    const existingInstance = provider.getImmediate();\n    const initialOptions = provider.getOptions() as unknown as AppCheckOptions;\n    if (\n      initialOptions &&\n      !!initialOptions.isTokenAutoRefreshEnabled ===\n        !!options.isTokenAutoRefreshEnabled &&\n      initialOptions.provider?.isEqual(options.provider)\n    ) {\n      return existingInstance;\n    } else {\n      throw ERROR_FACTORY.create(AppCheckError.ALREADY_INITIALIZED, {\n        appName: app.name\n      });\n    }\n  }\n\n  const appCheck = provider.initialize({ options });\n  _activate(app, options.provider, options.isTokenAutoRefreshEnabled);\n  // If isTokenAutoRefreshEnabled is false, do not send any requests to the\n  // exchange endpoint without an explicit call from the user either directly\n  // or through another Firebase library (storage, functions, etc.)\n  if (getStateReference(app).isTokenAutoRefreshEnabled) {\n    // Adding a listener will start the refresher and fetch a token if needed.\n    // This gets a token ready and prevents a delay when an internal library\n    // requests the token.\n    // Listener function does not need to do anything, its base functionality\n    // of calling getToken() already fetches token and writes it to memory/storage.\n    addTokenListener(appCheck, ListenerType.INTERNAL, () => {});\n  }\n\n  return appCheck;\n}\n\n/**\n * Activate App Check\n * @param app - Firebase app to activate App Check for.\n * @param provider - reCAPTCHA v3 provider or\n * custom token provider.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. If undefined, defaults to the\n * value of `app.automaticDataCollectionEnabled`, which defaults to\n * false and can be set in the app config.\n */\nfunction _activate(\n  app: FirebaseApp,\n  provider: AppCheckProvider,\n  isTokenAutoRefreshEnabled: boolean = false\n): void {\n  // Create an entry in the APP_CHECK_STATES map. Further changes should\n  // directly mutate this object.\n  const state = setInitialState(app, { ...DEFAULT_STATE });\n\n  state.activated = true;\n  state.provider = provider; // Read cached token from storage if it exists and store it in memory.\n  state.cachedTokenPromise = readTokenFromStorage(app).then(cachedToken => {\n    if (cachedToken && isValid(cachedToken)) {\n      state.token = cachedToken;\n      // notify all listeners with the cached token\n      notifyTokenListeners(app, { token: cachedToken.token });\n    }\n    return cachedToken;\n  });\n\n  // Global `automaticDataCollectionEnabled` (defaults to true) and\n  // `isTokenAutoRefreshEnabled` must both be true.\n  state.isTokenAutoRefreshEnabled =\n    isTokenAutoRefreshEnabled && app.automaticDataCollectionEnabled;\n\n  if (!app.automaticDataCollectionEnabled && isTokenAutoRefreshEnabled) {\n    logger.warn(\n      '`isTokenAutoRefreshEnabled` is true but ' +\n        '`automaticDataCollectionEnabled` was set to false during' +\n        ' `initializeApp()`. This blocks automatic token refresh.'\n    );\n  }\n\n  state.provider.initialize(app);\n}\n\n/**\n * Set whether App Check will automatically refresh tokens as needed.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param isTokenAutoRefreshEnabled - If true, the SDK automatically\n * refreshes App Check tokens as needed. This overrides any value set\n * during `initializeAppCheck()`.\n * @public\n */\nexport function setTokenAutoRefreshEnabled(\n  appCheckInstance: AppCheck,\n  isTokenAutoRefreshEnabled: boolean\n): void {\n  const app = appCheckInstance.app;\n  const state = getStateReference(app);\n  // This will exist if any product libraries have called\n  // `addTokenListener()`\n  if (state.tokenRefresher) {\n    if (isTokenAutoRefreshEnabled === true) {\n      state.tokenRefresher.start();\n    } else {\n      state.tokenRefresher.stop();\n    }\n  }\n  state.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;\n}\n/**\n * Get the current App Check token. If `forceRefresh` is false, this function first\n * checks for a valid token in memory, then local persistence (IndexedDB).\n * If not found, or if `forceRefresh` is true, it makes a request to the\n * App Check endpoint for a fresh token. That request attaches\n * to the most recent in-flight request if one is present.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param forceRefresh - If true, will always try to fetch a fresh token.\n * If false, will use a cached token if found in storage.\n * @public\n */\nexport async function getToken(\n  appCheckInstance: AppCheck,\n  forceRefresh?: boolean\n): Promise<AppCheckTokenResult> {\n  const result = await getTokenInternal(\n    appCheckInstance as AppCheckService,\n    forceRefresh\n  );\n  if (result.error) {\n    throw result.error;\n  }\n  if (result.internalError) {\n    throw result.internalError;\n  }\n  return { token: result.token };\n}\n\n/**\n * Requests a Firebase App Check token. This method should be used\n * only if you need to authorize requests to a non-Firebase backend.\n *\n * Returns limited-use tokens that are intended for use with your\n * non-Firebase backend endpoints that are protected with\n * <a href=\"https://firebase.google.com/docs/app-check/custom-resource-backend#replay-protection\">\n * Replay Protection</a>. This method\n * does not affect the token generation behavior of the\n * #getAppCheckToken() method.\n *\n * @param appCheckInstance - The App Check service instance.\n * @returns The limited use token.\n * @public\n */\nexport function getLimitedUseToken(\n  appCheckInstance: AppCheck\n): Promise<AppCheckTokenResult> {\n  return getLimitedUseTokenInternal(appCheckInstance as AppCheckService);\n}\n\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param observer - An object with `next`, `error`, and `complete`\n * properties. `next` is called with an\n * {@link AppCheckTokenResult}\n * whenever the token changes. `error` is optional and is called if an\n * error is thrown by the listener (the `next` function). `complete`\n * is unused, as the token stream is unending.\n *\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  observer: PartialObserver<AppCheckTokenResult>\n): Unsubscribe;\n/**\n * Registers a listener to changes in the token state. There can be more\n * than one listener registered at the same time for one or more\n * App Check instances. The listeners call back on the UI thread whenever\n * the current token associated with this App Check instance changes.\n *\n * @param appCheckInstance - The App Check service instance.\n * @param onNext - When the token changes, this function is called with an\n * {@link AppCheckTokenResult}.\n * @param onError - Optional. Called if there is an error thrown by the\n * listener (the `onNext` function).\n * @param onCompletion - Currently unused, as the token stream is unending.\n * @returns A function that unsubscribes this listener.\n * @public\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  onNext: (tokenResult: AppCheckTokenResult) => void,\n  onError?: (error: Error) => void,\n  onCompletion?: () => void\n): Unsubscribe;\n/**\n * Wraps `addTokenListener`/`removeTokenListener` methods in an `Observer`\n * pattern for public use.\n */\nexport function onTokenChanged(\n  appCheckInstance: AppCheck,\n  onNextOrObserver:\n    | ((tokenResult: AppCheckTokenResult) => void)\n    | PartialObserver<AppCheckTokenResult>,\n  onError?: (error: Error) => void,\n  /**\n   * NOTE: Although an `onCompletion` callback can be provided, it will\n   * never be called because the token stream is never-ending.\n   * It is added only for API consistency with the observer pattern, which\n   * we follow in JS APIs.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  onCompletion?: () => void\n): Unsubscribe {\n  let nextFn: NextFn<AppCheckTokenResult> = () => {};\n  let errorFn: ErrorFn = () => {};\n  if ((onNextOrObserver as PartialObserver<AppCheckTokenResult>).next != null) {\n    nextFn = (\n      onNextOrObserver as PartialObserver<AppCheckTokenResult>\n    ).next!.bind(onNextOrObserver);\n  } else {\n    nextFn = onNextOrObserver as NextFn<AppCheckTokenResult>;\n  }\n  if (\n    (onNextOrObserver as PartialObserver<AppCheckTokenResult>).error != null\n  ) {\n    errorFn = (\n      onNextOrObserver as PartialObserver<AppCheckTokenResult>\n    ).error!.bind(onNextOrObserver);\n  } else if (onError) {\n    errorFn = onError;\n  }\n  addTokenListener(\n    appCheckInstance as AppCheckService,\n    ListenerType.EXTERNAL,\n    nextFn,\n    errorFn\n  );\n  return () => removeTokenListener(appCheckInstance.app, nextFn);\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n  _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n  service: Compat<ExpService> | ExpService\n): ExpService {\n  if (service && (service as Compat<ExpService>)._delegate) {\n    return (service as Compat<ExpService>)._delegate;\n  } else {\n    return service as ExpService;\n  }\n}\n","/**\n * The Firebase App Check Web SDK.\n *\n * @remarks\n * Firebase App Check does not work in a Node.js environment using `ReCaptchaV3Provider` or\n * `ReCaptchaEnterpriseProvider`, but can be used in Node.js if you use\n * `CustomProvider` and write your own attestation method.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { registerVersion, _registerComponent } from '@firebase/app';\nimport {\n  Component,\n  ComponentType,\n  InstantiationMode\n} from '@firebase/component';\nimport { _AppCheckComponentName } from './public-types';\nimport { factory, internalFactory } from './factory';\nimport { _AppCheckInternalComponentName } from './types';\nimport { name, version } from '../package.json';\n\n// Used by other Firebase packages.\nexport { _AppCheckInternalComponentName };\n\nexport * from './api';\nexport * from './public-types';\n\nconst APP_CHECK_NAME: _AppCheckComponentName = 'app-check';\nconst APP_CHECK_NAME_INTERNAL: _AppCheckInternalComponentName =\n  'app-check-internal';\nfunction registerAppCheck(): void {\n  // The public interface\n  _registerComponent(\n    new Component(\n      APP_CHECK_NAME,\n      container => {\n        // getImmediate for FirebaseApp will always succeed\n        const app = container.getProvider('app').getImmediate();\n        const heartbeatServiceProvider = container.getProvider('heartbeat');\n        return factory(app, heartbeatServiceProvider);\n      },\n      ComponentType.PUBLIC\n    )\n      .setInstantiationMode(InstantiationMode.EXPLICIT)\n      /**\n       * Initialize app-check-internal after app-check is initialized to make AppCheck available to\n       * other Firebase SDKs\n       */\n      .setInstanceCreatedCallback(\n        (container, _identifier, _appcheckService) => {\n          container.getProvider(APP_CHECK_NAME_INTERNAL).initialize();\n        }\n      )\n  );\n\n  // The internal interface used by other Firebase products\n  _registerComponent(\n    new Component(\n      APP_CHECK_NAME_INTERNAL,\n      container => {\n        const appCheck = container.getProvider('app-check').getImmediate();\n        return internalFactory(appCheck);\n      },\n      ComponentType.PUBLIC\n    ).setInstantiationMode(InstantiationMode.EXPLICIT)\n  );\n\n  registerVersion(name, version);\n}\n\nregisterAppCheck();\n"],"names":["base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","i","length","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","str","out","p","c","charCodeAt","stringToByteArray","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Decode","e","console","error","Deferred","reject","resolve","promise","Promise","wrapCallback","callback","value","catch","isIndexedDBAvailable","indexedDB","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","ptr","result","start","indexOf","substring","end","key","fullMessage","jsonEval","JSON","parse","issuedAtTime","token","claims","header","signature","parts","split","decode","hasOwnProperty","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","LogLevel","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","info","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","APP_CHECK_STATES","Map","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","initialized","enabled","getStateReference","app","get","getDebugState","BASE_ENDPOINT","TOKEN_REFRESH_TIME","Refresher","operation","retryPolicy","getWaitDuration","lowerBound","upperBound","pending","nextErrorWaitInterval","process","stop","isRunning","hasSucceeded","_e","sleep","ms","setTimeout","getNextRun","currentErrorWaitInterval","ERROR_FACTORY","throttled","getRecaptcha","isEnterprise","self","grecaptcha","enterprise","ensureActivated","appName","getDurationString","durationInMillis","totalSeconds","Math","round","days","floor","hours","minutes","seconds","pad","toString","async","exchangeToken","url","body","heartbeatServiceProvider","headers","heartbeatService","getImmediate","optional","heartbeatsHeader","getHeartbeatsHeader","options","stringify","response","responseBody","fetch","originalError","originalErrorMessage","status","httpStatus","json","match","ttl","isNaN","Number","timeToLiveAsNumber","expireTimeMillis","issuedAtTimeMillis","getExchangeDebugTokenRequest","debugToken","projectId","appId","apiKey","debug_token","STORE_NAME","DEBUG_TOKEN_KEY","dbPromise","getDBPromise","request","open","onsuccess","event","target","onerror","onupgradeneeded","db","oldVersion","createObjectStore","keyPath","write","transaction","objectStore","put","compositeKey","_event","read","undefined","computeKey","logger","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","readTokenFromStorage","readTokenFromIndexedDB","writeTokenToStorage","writeTokenToIndexedDB","readOrCreateDebugTokenFromStorage","existingDebugToken","readDebugTokenFromIndexedDB","newToken","crypto","randomUUID","writeDebugTokenToIndexedDB","isDebugMode","getDebugToken","state","initializeDebugMode","globals","getGlobal","window","global","debugState","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","defaultTokenErrorData","getToken","appCheck","forceRefresh","shouldLogErrors","isValid","cachedToken","cachedTokenPromise","interopTokenResult","shouldCallListeners","exchangeTokenPromise","finally","tokenFromDebugExchange","makeDummyTokenResult","provider","internalError","notifyTokenListeners","getLimitedUseToken","addTokenListener","listener","onError","tokenObserver","next","validToken","then","initTokenRefresher","removeTokenListener","newObservers","filter","tokenRefresher","refresher","createTokenRefresher","nextRefreshTimeMillis","latestAllowableRefresh","min","max","isTokenAutoRefreshEnabled","observers","observer","tokenErrorData","AppCheckService","_delete","RECAPTCHA_URL","RECAPTCHA_ENTERPRISE_URL","initializeV3","siteKey","reCAPTCHAState","divId","makeDiv","queueWidgetRender","loadReCAPTCHAV3Script","onload","script","document","createElement","src","head","appendChild","initializeEnterprise","loadReCAPTCHAEnterpriseScript","container","ready","renderInvisibleWidget","widgetId","render","sitekey","size","succeeded","invisibleDiv","id","style","display","recaptcha","_reject","execute","action","ReCaptchaV3Provider","_siteKey","_throttleData","isLimitedUse","throwIfThrottled","attestedClaimsToken","getReCAPTCHAToken","_app","getExchangeRecaptchaV3TokenRequest","reCAPTCHAToken","recaptcha_v3_token","_heartbeatServiceProvider","includes","setBackoff","time","allowRequestsAfter","initialize","_getProvider","initializeRecaptchaV3","isEqual","otherProvider","ReCaptchaEnterpriseProvider","getExchangeRecaptchaEnterpriseTokenRequest","recaptcha_enterprise_token","initializeRecaptchaEnterprise","CustomProvider","_customProviderOptions","customToken","issuedAtTimeSeconds","throttleData","backoffCount","backoffMillis","calculateBackoffMillis","intervalMillis","backoffFactor","currBaseValue","pow","randomWait","random","initializeAppCheck","getApp","getModularInstance","_delegate","isInitialized","existingInstance","initialOptions","getOptions","_activate","setInitialState","set","automaticDataCollectionEnabled","setTokenAutoRefreshEnabled","appCheckInstance","getTokenInternal","getLimitedUseTokenInternal","onTokenChanged","onNextOrObserver","onCompletion","nextFn","errorFn","bind","APP_CHECK_NAME_INTERNAL","registerAppCheck","_registerComponent","factory","getProvider","_identifier","_appcheckService","internalFactory","registerVersion"],"mappings":"iGAiBA,MA0FaA,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKF,gBAAIC,GACF,OAAOC,KAAKF,kBAAoB,KAClC,EAKA,wBAAIG,GACF,OAAOD,KAAKF,kBAAoB,KAClC,EASAI,mBAAoC,mBAATC,KAW3B,eAAAC,CAAgBC,EAA8BC,GAC5C,IAAKC,MAAMC,QAAQH,GACjB,MAAMI,MAAM,iDAGdT,KAAKU,QAEL,MAAMC,EAAgBL,EAClBN,KAAKJ,sBACLI,KAAKN,eAEHkB,EAAS,GAEf,IAAK,IAAIC,EAAI,EAAGA,EAAIR,EAAMS,OAAQD,GAAK,EAAG,CACxC,MAAME,EAAQV,EAAMQ,GACdG,EAAYH,EAAI,EAAIR,EAAMS,OAC1BG,EAAQD,EAAYX,EAAMQ,EAAI,GAAK,EACnCK,EAAYL,EAAI,EAAIR,EAAMS,OAC1BK,EAAQD,EAAYb,EAAMQ,EAAI,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