{"version":3,"file":"firebase-installations-compat.js","sources":["../util/src/errors.ts","../component/src/component.ts","../../node_modules/idb/build/wrap-idb-value.js","../../node_modules/idb/build/index.js","../installations/src/util/constants.ts","../installations-compat/src/index.ts","../installations/src/util/errors.ts","../installations/src/functions/common.ts","../installations/src/util/sleep.ts","../installations/src/helpers/generate-fid.ts","../installations/src/helpers/buffer-to-base64-url-safe.ts","../installations/src/util/get-key.ts","../installations/src/helpers/fid-changed.ts","../installations/src/helpers/idb-manager.ts","../installations/src/helpers/get-installation-entry.ts","../installations/src/functions/create-installation-request.ts","../installations/src/functions/generate-auth-token-request.ts","../installations/src/helpers/refresh-auth-token.ts","../installations/src/api/get-id.ts","../installations/src/api/get-token.ts","../installations/src/functions/delete-installation-request.ts","../installations/src/api/on-id-change.ts","../installations/src/helpers/extract-app-config.ts","../installations/src/functions/config.ts","../installations/src/index.ts","../installations-compat/src/installationsCompat.ts","../installations/src/api/delete-installations.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/**\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 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","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n    return (idbProxyableTypes ||\n        (idbProxyableTypes = [\n            IDBDatabase,\n            IDBObjectStore,\n            IDBIndex,\n            IDBCursor,\n            IDBTransaction,\n        ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n    return (cursorAdvanceMethods ||\n        (cursorAdvanceMethods = [\n            IDBCursor.prototype.advance,\n            IDBCursor.prototype.continue,\n            IDBCursor.prototype.continuePrimaryKey,\n        ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n    const promise = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            request.removeEventListener('success', success);\n            request.removeEventListener('error', error);\n        };\n        const success = () => {\n            resolve(wrap(request.result));\n            unlisten();\n        };\n        const error = () => {\n            reject(request.error);\n            unlisten();\n        };\n        request.addEventListener('success', success);\n        request.addEventListener('error', error);\n    });\n    promise\n        .then((value) => {\n        // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n        // (see wrapFunction).\n        if (value instanceof IDBCursor) {\n            cursorRequestMap.set(value, request);\n        }\n        // Catching to avoid \"Uncaught Promise exceptions\"\n    })\n        .catch(() => { });\n    // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n    // is because we create many promises from a single IDBRequest.\n    reverseTransformCache.set(promise, request);\n    return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n    // Early bail if we've already created a done promise for this transaction.\n    if (transactionDoneMap.has(tx))\n        return;\n    const done = new Promise((resolve, reject) => {\n        const unlisten = () => {\n            tx.removeEventListener('complete', complete);\n            tx.removeEventListener('error', error);\n            tx.removeEventListener('abort', error);\n        };\n        const complete = () => {\n            resolve();\n            unlisten();\n        };\n        const error = () => {\n            reject(tx.error || new DOMException('AbortError', 'AbortError'));\n            unlisten();\n        };\n        tx.addEventListener('complete', complete);\n        tx.addEventListener('error', error);\n        tx.addEventListener('abort', error);\n    });\n    // Cache it for later retrieval.\n    transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n    get(target, prop, receiver) {\n        if (target instanceof IDBTransaction) {\n            // Special handling for transaction.done.\n            if (prop === 'done')\n                return transactionDoneMap.get(target);\n            // Polyfill for objectStoreNames because of Edge.\n            if (prop === 'objectStoreNames') {\n                return target.objectStoreNames || transactionStoreNamesMap.get(target);\n            }\n            // Make tx.store return the only store in the transaction, or undefined if there are many.\n            if (prop === 'store') {\n                return receiver.objectStoreNames[1]\n                    ? undefined\n                    : receiver.objectStore(receiver.objectStoreNames[0]);\n            }\n        }\n        // Else transform whatever we get back.\n        return wrap(target[prop]);\n    },\n    set(target, prop, value) {\n        target[prop] = value;\n        return true;\n    },\n    has(target, prop) {\n        if (target instanceof IDBTransaction &&\n            (prop === 'done' || prop === 'store')) {\n            return true;\n        }\n        return prop in target;\n    },\n};\nfunction replaceTraps(callback) {\n    idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n    // Due to expected object equality (which is enforced by the caching in `wrap`), we\n    // only create one new func per func.\n    // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n    if (func === IDBDatabase.prototype.transaction &&\n        !('objectStoreNames' in IDBTransaction.prototype)) {\n        return function (storeNames, ...args) {\n            const tx = func.call(unwrap(this), storeNames, ...args);\n            transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n            return wrap(tx);\n        };\n    }\n    // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n    // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n    // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n    // with real promises, so each advance methods returns a new promise for the cursor object, or\n    // undefined if the end of the cursor has been reached.\n    if (getCursorAdvanceMethods().includes(func)) {\n        return function (...args) {\n            // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n            // the original object.\n            func.apply(unwrap(this), args);\n            return wrap(cursorRequestMap.get(this));\n        };\n    }\n    return function (...args) {\n        // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n        // the original object.\n        return wrap(func.apply(unwrap(this), args));\n    };\n}\nfunction transformCachableValue(value) {\n    if (typeof value === 'function')\n        return wrapFunction(value);\n    // This doesn't return, it just creates a 'done' promise for the transaction,\n    // which is later returned for transaction.done (see idbObjectHandler).\n    if (value instanceof IDBTransaction)\n        cacheDonePromiseForTransaction(value);\n    if (instanceOfAny(value, getIdbProxyableTypes()))\n        return new Proxy(value, idbProxyTraps);\n    // Return the same value back if we're not going to transform it.\n    return value;\n}\nfunction wrap(value) {\n    // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n    // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n    if (value instanceof IDBRequest)\n        return promisifyRequest(value);\n    // If we've already transformed this value before, reuse the transformed value.\n    // This is faster, but it also provides object equality.\n    if (transformCache.has(value))\n        return transformCache.get(value);\n    const newValue = transformCachableValue(value);\n    // Not all types are transformed.\n    // These may be primitive types, so they can't be WeakMap keys.\n    if (newValue !== value) {\n        transformCache.set(value, newValue);\n        reverseTransformCache.set(newValue, value);\n    }\n    return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n    const request = indexedDB.open(name, version);\n    const openPromise = wrap(request);\n    if (upgrade) {\n        request.addEventListener('upgradeneeded', (event) => {\n            upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n        });\n    }\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event.newVersion, event));\n    }\n    openPromise\n        .then((db) => {\n        if (terminated)\n            db.addEventListener('close', () => terminated());\n        if (blocking) {\n            db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n        }\n    })\n        .catch(() => { });\n    return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n    const request = indexedDB.deleteDatabase(name);\n    if (blocked) {\n        request.addEventListener('blocked', (event) => blocked(\n        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n        event.oldVersion, event));\n    }\n    return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n    if (!(target instanceof IDBDatabase &&\n        !(prop in target) &&\n        typeof prop === 'string')) {\n        return;\n    }\n    if (cachedMethods.get(prop))\n        return cachedMethods.get(prop);\n    const targetFuncName = prop.replace(/FromIndex$/, '');\n    const useIndex = prop !== targetFuncName;\n    const isWrite = writeMethods.includes(targetFuncName);\n    if (\n    // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n    !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n        !(isWrite || readMethods.includes(targetFuncName))) {\n        return;\n    }\n    const method = async function (storeName, ...args) {\n        // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n        const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n        let target = tx.store;\n        if (useIndex)\n            target = target.index(args.shift());\n        // Must reject if op rejects.\n        // If it's a write operation, must reject if tx.done rejects.\n        // Must reject with op rejection first.\n        // Must resolve with op value.\n        // Must handle both promises (no unhandled rejections)\n        return (await Promise.all([\n            target[targetFuncName](...args),\n            isWrite && tx.done,\n        ]))[0];\n    };\n    cachedMethods.set(prop, method);\n    return method;\n}\nreplaceTraps((oldTraps) => ({\n    ...oldTraps,\n    get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n    has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\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\nimport { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n  'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\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 firebase, { _FirebaseNamespace } from '@firebase/app-compat';\nimport { name, version } from '../package.json';\nimport { Component, ComponentType } from '@firebase/component';\nimport { FirebaseInstallations as FirebaseInstallationsCompat } from '@firebase/installations-types';\nimport { InstallationsCompat } from './installationsCompat';\n\ndeclare module '@firebase/component' {\n  interface NameServiceMapping {\n    'installations-compat': FirebaseInstallationsCompat;\n  }\n}\n\nfunction registerInstallations(instance: _FirebaseNamespace): void {\n  instance.INTERNAL.registerComponent(\n    new Component(\n      'installations-compat',\n      container => {\n        const app = container.getProvider('app-compat').getImmediate()!;\n        const installations = container\n          .getProvider('installations')\n          .getImmediate()!;\n        return new InstallationsCompat(app, installations);\n      },\n      ComponentType.PUBLIC\n    )\n  );\n\n  instance.registerVersion(name, version);\n}\n\nregisterInstallations(firebase as _FirebaseNamespace);\n\n/**\n * Define extension behavior of `registerInstallations`\n */\ndeclare module '@firebase/app-compat' {\n  interface FirebaseNamespace {\n    installations(app?: FirebaseApp): FirebaseInstallationsCompat;\n  }\n  interface FirebaseApp {\n    installations(): FirebaseInstallationsCompat;\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\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n  MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n  NOT_REGISTERED = 'not-registered',\n  INSTALLATION_NOT_FOUND = 'installation-not-found',\n  REQUEST_FAILED = 'request-failed',\n  APP_OFFLINE = 'app-offline',\n  DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n  [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n    'Missing App configuration value: \"{$valueName}\"',\n  [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n  [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n  [ErrorCode.REQUEST_FAILED]:\n    '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n  [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n  [ErrorCode.DELETE_PENDING_REGISTRATION]:\n    \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n  [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n    valueName: string;\n  };\n  [ErrorCode.REQUEST_FAILED]: {\n    requestName: string;\n    [index: string]: string | number; // to make TypeScript 3.8 happy\n  } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n  SERVICE,\n  SERVICE_NAME,\n  ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n  serverCode: number;\n  serverMessage: string;\n  serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & { customData: ServerErrorData };\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n  return (\n    error instanceof FirebaseError &&\n    error.code.includes(ErrorCode.REQUEST_FAILED)\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\nimport { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n  CompletedAuthToken,\n  RegisteredInstallationEntry,\n  RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n  INSTALLATIONS_API_URL,\n  INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { AppConfig } from '../interfaces/installation-impl';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n  return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n  response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n  return {\n    token: response.token,\n    requestStatus: RequestStatus.COMPLETED,\n    expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n    creationTime: Date.now()\n  };\n}\n\nexport async function getErrorFromResponse(\n  requestName: string,\n  response: Response\n): Promise<FirebaseError> {\n  const responseJson: ErrorResponse = await response.json();\n  const errorData = responseJson.error;\n  return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n    requestName,\n    serverCode: errorData.code,\n    serverMessage: errorData.message,\n    serverStatus: errorData.status\n  });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n  return new Headers({\n    'Content-Type': 'application/json',\n    Accept: 'application/json',\n    'x-goog-api-key': apiKey\n  });\n}\n\nexport function getHeadersWithAuth(\n  appConfig: AppConfig,\n  { refreshToken }: RegisteredInstallationEntry\n): Headers {\n  const headers = getHeaders(appConfig);\n  headers.append('Authorization', getAuthorizationHeader(refreshToken));\n  return headers;\n}\n\nexport interface ErrorResponse {\n  error: {\n    code: number;\n    message: string;\n    status: string;\n  };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n  fn: () => Promise<Response>\n): Promise<Response> {\n  const result = await fn();\n\n  if (result.status >= 500 && result.status < 600) {\n    // Internal Server Error. Retry request.\n    return fn();\n  }\n\n  return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n  // This works because the server will never respond with fractions of a second.\n  return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n  return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\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/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n  return new Promise<void>(resolve => {\n    setTimeout(resolve, ms);\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\nimport { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n  try {\n    // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n    // bytes. our implementation generates a 17 byte array instead.\n    const fidByteArray = new Uint8Array(17);\n    const crypto =\n      self.crypto || (self as unknown as { msCrypto: Crypto }).msCrypto;\n    crypto.getRandomValues(fidByteArray);\n\n    // Replace the first 4 random bits with the constant FID header of 0b0111.\n    fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n    const fid = encode(fidByteArray);\n\n    return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n  } catch {\n    // FID generation errored\n    return INVALID_FID;\n  }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n  const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n  // Remove the 23rd character that was added because of the extra 4 bits at the\n  // end of our 17 byte array, and the '=' padding.\n  return b64String.substr(0, 22);\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\nexport function bufferToBase64UrlSafe(array: Uint8Array): string {\n  const b64 = btoa(String.fromCharCode(...array));\n  return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\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\nimport { AppConfig } from '../interfaces/installation-impl';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n  return `${appConfig.appName}!${appConfig.appId}`;\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\nimport { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { IdChangeCallbackFn } from '../api';\n\nconst fidChangeCallbacks: Map<string, Set<IdChangeCallbackFn>> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n  const key = getKey(appConfig);\n\n  callFidChangeCallbacks(key, fid);\n  broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n  appConfig: AppConfig,\n  callback: IdChangeCallbackFn\n): void {\n  // Open the broadcast channel if it's not already open,\n  // to be able to listen to change events from other tabs.\n  getBroadcastChannel();\n\n  const key = getKey(appConfig);\n\n  let callbackSet = fidChangeCallbacks.get(key);\n  if (!callbackSet) {\n    callbackSet = new Set();\n    fidChangeCallbacks.set(key, callbackSet);\n  }\n  callbackSet.add(callback);\n}\n\nexport function removeCallback(\n  appConfig: AppConfig,\n  callback: IdChangeCallbackFn\n): void {\n  const key = getKey(appConfig);\n\n  const callbackSet = fidChangeCallbacks.get(key);\n\n  if (!callbackSet) {\n    return;\n  }\n\n  callbackSet.delete(callback);\n  if (callbackSet.size === 0) {\n    fidChangeCallbacks.delete(key);\n  }\n\n  // Close broadcast channel if there are no more callbacks.\n  closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n  const callbacks = fidChangeCallbacks.get(key);\n  if (!callbacks) {\n    return;\n  }\n\n  for (const callback of callbacks) {\n    callback(fid);\n  }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n  const channel = getBroadcastChannel();\n  if (channel) {\n    channel.postMessage({ key, fid });\n  }\n  closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n  if (!broadcastChannel && 'BroadcastChannel' in self) {\n    broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n    broadcastChannel.onmessage = e => {\n      callFidChangeCallbacks(e.data.key, e.data.fid);\n    };\n  }\n  return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n  if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n    broadcastChannel.close();\n    broadcastChannel = null;\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\nimport { DBSchema, IDBPDatabase, openDB } from 'idb';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\ninterface InstallationsDB extends DBSchema {\n  'firebase-installations-store': {\n    key: string;\n    value: InstallationEntry | undefined;\n  };\n}\n\nlet dbPromise: Promise<IDBPDatabase<InstallationsDB>> | null = null;\nfunction getDbPromise(): Promise<IDBPDatabase<InstallationsDB>> {\n  if (!dbPromise) {\n    dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {\n      upgrade: (db, oldVersion) => {\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 (oldVersion) {\n          case 0:\n            db.createObjectStore(OBJECT_STORE_NAME);\n        }\n      }\n    });\n  }\n  return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n  appConfig: AppConfig\n): Promise<InstallationEntry | undefined> {\n  const key = getKey(appConfig);\n  const db = await getDbPromise();\n  return db\n    .transaction(OBJECT_STORE_NAME)\n    .objectStore(OBJECT_STORE_NAME)\n    .get(key) as Promise<InstallationEntry>;\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set<ValueType extends InstallationEntry>(\n  appConfig: AppConfig,\n  value: ValueType\n): Promise<ValueType> {\n  const key = getKey(appConfig);\n  const db = await getDbPromise();\n  const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n  const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n  const oldValue = (await objectStore.get(key)) as InstallationEntry;\n  await objectStore.put(value, key);\n  await tx.done;\n\n  if (!oldValue || oldValue.fid !== value.fid) {\n    fidChanged(appConfig, value.fid);\n  }\n\n  return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise<void> {\n  const key = getKey(appConfig);\n  const db = await getDbPromise();\n  const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n  await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n  await tx.done;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update<ValueType extends InstallationEntry | undefined>(\n  appConfig: AppConfig,\n  updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise<ValueType> {\n  const key = getKey(appConfig);\n  const db = await getDbPromise();\n  const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n  const store = tx.objectStore(OBJECT_STORE_NAME);\n  const oldValue: InstallationEntry | undefined = (await store.get(\n    key\n  )) as InstallationEntry;\n  const newValue = updateFn(oldValue);\n\n  if (newValue === undefined) {\n    await store.delete(key);\n  } else {\n    await store.put(newValue, key);\n  }\n  await tx.done;\n\n  if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n    fidChanged(appConfig, newValue.fid);\n  }\n\n  return newValue;\n}\n\nexport async function clear(): Promise<void> {\n  const db = await getDbPromise();\n  const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n  await tx.objectStore(OBJECT_STORE_NAME).clear();\n  await tx.done;\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\nimport { createInstallationRequest } from '../functions/create-installation-request';\nimport {\n  AppConfig,\n  FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n  InProgressInstallationEntry,\n  InstallationEntry,\n  RegisteredInstallationEntry,\n  RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n  installationEntry: InstallationEntry;\n  /** Exist iff the installationEntry is not registered. */\n  registrationPromise?: Promise<RegisteredInstallationEntry>;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n  installations: FirebaseInstallationsImpl\n): Promise<InstallationEntryWithRegistrationPromise> {\n  let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n  const installationEntry = await update(installations.appConfig, oldEntry => {\n    const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n    const entryWithPromise = triggerRegistrationIfNecessary(\n      installations,\n      installationEntry\n    );\n    registrationPromise = entryWithPromise.registrationPromise;\n    return entryWithPromise.installationEntry;\n  });\n\n  if (installationEntry.fid === INVALID_FID) {\n    // FID generation failed. Waiting for the FID from the server.\n    return { installationEntry: await registrationPromise! };\n  }\n\n  return {\n    installationEntry,\n    registrationPromise\n  };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n  oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n  const entry: InstallationEntry = oldEntry || {\n    fid: generateFid(),\n    registrationStatus: RequestStatus.NOT_STARTED\n  };\n\n  return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n  installations: FirebaseInstallationsImpl,\n  installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n  if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n    if (!navigator.onLine) {\n      // Registration required but app is offline.\n      const registrationPromiseWithError = Promise.reject(\n        ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n      );\n      return {\n        installationEntry,\n        registrationPromise: registrationPromiseWithError\n      };\n    }\n\n    // Try registering. Change status to IN_PROGRESS.\n    const inProgressEntry: InProgressInstallationEntry = {\n      fid: installationEntry.fid,\n      registrationStatus: RequestStatus.IN_PROGRESS,\n      registrationTime: Date.now()\n    };\n    const registrationPromise = registerInstallation(\n      installations,\n      inProgressEntry\n    );\n    return { installationEntry: inProgressEntry, registrationPromise };\n  } else if (\n    installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n  ) {\n    return {\n      installationEntry,\n      registrationPromise: waitUntilFidRegistration(installations)\n    };\n  } else {\n    return { installationEntry };\n  }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n  installations: FirebaseInstallationsImpl,\n  installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n  try {\n    const registeredInstallationEntry = await createInstallationRequest(\n      installations,\n      installationEntry\n    );\n    return set(installations.appConfig, registeredInstallationEntry);\n  } catch (e) {\n    if (isServerError(e) && e.customData.serverCode === 409) {\n      // Server returned a \"FID cannot be used\" error.\n      // Generate a new ID next time.\n      await remove(installations.appConfig);\n    } else {\n      // Registration failed. Set FID as not registered.\n      await set(installations.appConfig, {\n        fid: installationEntry.fid,\n        registrationStatus: RequestStatus.NOT_STARTED\n      });\n    }\n    throw e;\n  }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n  installations: FirebaseInstallationsImpl\n): Promise<RegisteredInstallationEntry> {\n  // Unfortunately, there is no way of reliably observing when a value in\n  // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n  // so we need to poll.\n\n  let entry: InstallationEntry = await updateInstallationRequest(\n    installations.appConfig\n  );\n  while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n    // createInstallation request still in progress.\n    await sleep(100);\n\n    entry = await updateInstallationRequest(installations.appConfig);\n  }\n\n  if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n    // The request timed out or failed in a different call. Try again.\n    const { installationEntry, registrationPromise } =\n      await getInstallationEntry(installations);\n\n    if (registrationPromise) {\n      return registrationPromise;\n    } else {\n      // if there is no registrationPromise, entry is registered.\n      return installationEntry as RegisteredInstallationEntry;\n    }\n  }\n\n  return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n  appConfig: AppConfig\n): Promise<InstallationEntry> {\n  return update(appConfig, oldEntry => {\n    if (!oldEntry) {\n      throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n    }\n    return clearTimedOutRequest(oldEntry);\n  });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n  if (hasInstallationRequestTimedOut(entry)) {\n    return {\n      fid: entry.fid,\n      registrationStatus: RequestStatus.NOT_STARTED\n    };\n  }\n\n  return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n  installationEntry: InstallationEntry\n): boolean {\n  return (\n    installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n    installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\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\nimport { CreateInstallationResponse } from '../interfaces/api-response';\nimport {\n  InProgressInstallationEntry,\n  RegisteredInstallationEntry,\n  RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n  extractAuthTokenInfoFromResponse,\n  getErrorFromResponse,\n  getHeaders,\n  getInstallationsEndpoint,\n  retryIfServerError\n} from './common';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\n\nexport async function createInstallationRequest(\n  { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n  { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n  const endpoint = getInstallationsEndpoint(appConfig);\n\n  const headers = getHeaders(appConfig);\n\n  // If heartbeat service exists, add the heartbeat 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.append('x-firebase-client', heartbeatsHeader);\n    }\n  }\n\n  const body = {\n    fid,\n    authVersion: INTERNAL_AUTH_VERSION,\n    appId: appConfig.appId,\n    sdkVersion: PACKAGE_VERSION\n  };\n\n  const request: RequestInit = {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body)\n  };\n\n  const response = await retryIfServerError(() => fetch(endpoint, request));\n  if (response.ok) {\n    const responseValue: CreateInstallationResponse = await response.json();\n    const registeredInstallationEntry: RegisteredInstallationEntry = {\n      fid: responseValue.fid || fid,\n      registrationStatus: RequestStatus.COMPLETED,\n      refreshToken: responseValue.refreshToken,\n      authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n    };\n    return registeredInstallationEntry;\n  } else {\n    throw await getErrorFromResponse('Create Installation', response);\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\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport {\n  CompletedAuthToken,\n  RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n  extractAuthTokenInfoFromResponse,\n  getErrorFromResponse,\n  getHeadersWithAuth,\n  getInstallationsEndpoint,\n  retryIfServerError\n} from './common';\nimport {\n  FirebaseInstallationsImpl,\n  AppConfig\n} from '../interfaces/installation-impl';\n\nexport async function generateAuthTokenRequest(\n  { appConfig, heartbeatServiceProvider }: FirebaseInstallationsImpl,\n  installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n  const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n  const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n  // If heartbeat service exists, add the heartbeat 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.append('x-firebase-client', heartbeatsHeader);\n    }\n  }\n\n  const body = {\n    installation: {\n      sdkVersion: PACKAGE_VERSION,\n      appId: appConfig.appId\n    }\n  };\n\n  const request: RequestInit = {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body)\n  };\n\n  const response = await retryIfServerError(() => fetch(endpoint, request));\n  if (response.ok) {\n    const responseValue: GenerateAuthTokenResponse = await response.json();\n    const completedAuthToken: CompletedAuthToken =\n      extractAuthTokenInfoFromResponse(responseValue);\n    return completedAuthToken;\n  } else {\n    throw await getErrorFromResponse('Generate Auth Token', response);\n  }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n  appConfig: AppConfig,\n  { fid }: RegisteredInstallationEntry\n): string {\n  return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\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\nimport { generateAuthTokenRequest } from '../functions/generate-auth-token-request';\nimport {\n  AppConfig,\n  FirebaseInstallationsImpl\n} from '../interfaces/installation-impl';\nimport {\n  AuthToken,\n  CompletedAuthToken,\n  InProgressAuthToken,\n  InstallationEntry,\n  RegisteredInstallationEntry,\n  RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n  installations: FirebaseInstallationsImpl,\n  forceRefresh = false\n): Promise<CompletedAuthToken> {\n  let tokenPromise: Promise<CompletedAuthToken> | undefined;\n  const entry = await update(installations.appConfig, oldEntry => {\n    if (!isEntryRegistered(oldEntry)) {\n      throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n    }\n\n    const oldAuthToken = oldEntry.authToken;\n    if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n      // There is a valid token in the DB.\n      return oldEntry;\n    } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n      // There already is a token request in progress.\n      tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\n      return oldEntry;\n    } else {\n      // No token or token expired.\n      if (!navigator.onLine) {\n        throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n      }\n\n      const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n      tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\n      return inProgressEntry;\n    }\n  });\n\n  const authToken = tokenPromise\n    ? await tokenPromise\n    : (entry.authToken as CompletedAuthToken);\n  return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n  installations: FirebaseInstallationsImpl,\n  forceRefresh: boolean\n): Promise<CompletedAuthToken> {\n  // Unfortunately, there is no way of reliably observing when a value in\n  // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n  // so we need to poll.\n\n  let entry = await updateAuthTokenRequest(installations.appConfig);\n  while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n    // generateAuthToken still in progress.\n    await sleep(100);\n\n    entry = await updateAuthTokenRequest(installations.appConfig);\n  }\n\n  const authToken = entry.authToken;\n  if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n    // The request timed out or failed in a different call. Try again.\n    return refreshAuthToken(installations, forceRefresh);\n  } else {\n    return authToken;\n  }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n  appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n  return update(appConfig, oldEntry => {\n    if (!isEntryRegistered(oldEntry)) {\n      throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n    }\n\n    const oldAuthToken = oldEntry.authToken;\n    if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n      return {\n        ...oldEntry,\n        authToken: { requestStatus: RequestStatus.NOT_STARTED }\n      };\n    }\n\n    return oldEntry;\n  });\n}\n\nasync function fetchAuthTokenFromServer(\n  installations: FirebaseInstallationsImpl,\n  installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n  try {\n    const authToken = await generateAuthTokenRequest(\n      installations,\n      installationEntry\n    );\n    const updatedInstallationEntry: RegisteredInstallationEntry = {\n      ...installationEntry,\n      authToken\n    };\n    await set(installations.appConfig, updatedInstallationEntry);\n    return authToken;\n  } catch (e) {\n    if (\n      isServerError(e) &&\n      (e.customData.serverCode === 401 || e.customData.serverCode === 404)\n    ) {\n      // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n      // Generate a new ID next time.\n      await remove(installations.appConfig);\n    } else {\n      const updatedInstallationEntry: RegisteredInstallationEntry = {\n        ...installationEntry,\n        authToken: { requestStatus: RequestStatus.NOT_STARTED }\n      };\n      await set(installations.appConfig, updatedInstallationEntry);\n    }\n    throw e;\n  }\n}\n\nfunction isEntryRegistered(\n  installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n  return (\n    installationEntry !== undefined &&\n    installationEntry.registrationStatus === RequestStatus.COMPLETED\n  );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n  return (\n    authToken.requestStatus === RequestStatus.COMPLETED &&\n    !isAuthTokenExpired(authToken)\n  );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n  const now = Date.now();\n  return (\n    now < authToken.creationTime ||\n    authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n  );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n  oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n  const inProgressAuthToken: InProgressAuthToken = {\n    requestStatus: RequestStatus.IN_PROGRESS,\n    requestTime: Date.now()\n  };\n  return {\n    ...oldEntry,\n    authToken: inProgressAuthToken\n  };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n  return (\n    authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n    authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\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\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Creates a Firebase Installation if there isn't one for the app and\n * returns the Installation ID.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function getId(installations: Installations): Promise<string> {\n  const installationsImpl = installations as FirebaseInstallationsImpl;\n  const { installationEntry, registrationPromise } = await getInstallationEntry(\n    installationsImpl\n  );\n\n  if (registrationPromise) {\n    registrationPromise.catch(console.error);\n  } else {\n    // If the installation is already registered, update the authentication\n    // token if needed.\n    refreshAuthToken(installationsImpl).catch(console.error);\n  }\n\n  return installationEntry.fid;\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\nimport { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Returns a Firebase Installations auth token, identifying the current\n * Firebase Installation.\n * @param installations - The `Installations` instance.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getToken(\n  installations: Installations,\n  forceRefresh = false\n): Promise<string> {\n  const installationsImpl = installations as FirebaseInstallationsImpl;\n  await completeInstallationRegistration(installationsImpl);\n\n  // At this point we either have a Registered Installation in the DB, or we've\n  // already thrown an error.\n  const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\n  return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n  installations: FirebaseInstallationsImpl\n): Promise<void> {\n  const { registrationPromise } = await getInstallationEntry(installations);\n\n  if (registrationPromise) {\n    // A createInstallation request is in progress. Wait until it finishes.\n    await registrationPromise;\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\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { RegisteredInstallationEntry } from '../interfaces/installation-entry';\nimport {\n  getErrorFromResponse,\n  getHeadersWithAuth,\n  getInstallationsEndpoint,\n  retryIfServerError\n} from './common';\n\nexport async function deleteInstallationRequest(\n  appConfig: AppConfig,\n  installationEntry: RegisteredInstallationEntry\n): Promise<void> {\n  const endpoint = getDeleteEndpoint(appConfig, installationEntry);\n\n  const headers = getHeadersWithAuth(appConfig, installationEntry);\n  const request: RequestInit = {\n    method: 'DELETE',\n    headers\n  };\n\n  const response = await retryIfServerError(() => fetch(endpoint, request));\n  if (!response.ok) {\n    throw await getErrorFromResponse('Delete Installation', response);\n  }\n}\n\nfunction getDeleteEndpoint(\n  appConfig: AppConfig,\n  { fid }: RegisteredInstallationEntry\n): string {\n  return `${getInstallationsEndpoint(appConfig)}/${fid}`;\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\nimport { addCallback, removeCallback } from '../helpers/fid-changed';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * An user defined callback function that gets called when Installations ID changes.\n *\n * @public\n */\nexport type IdChangeCallbackFn = (installationId: string) => void;\n/**\n * Unsubscribe a callback function previously added via {@link IdChangeCallbackFn}.\n *\n * @public\n */\nexport type IdChangeUnsubscribeFn = () => void;\n\n/**\n * Sets a new callback that will get called when Installation ID changes.\n * Returns an unsubscribe function that will remove the callback when called.\n * @param installations - The `Installations` instance.\n * @param callback - The callback function that is invoked when FID changes.\n * @returns A function that can be called to unsubscribe.\n *\n * @public\n */\nexport function onIdChange(\n  installations: Installations,\n  callback: IdChangeCallbackFn\n): IdChangeUnsubscribeFn {\n  const { appConfig } = installations as FirebaseInstallationsImpl;\n\n  addCallback(appConfig, callback);\n  return () => {\n    removeCallback(appConfig, callback);\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\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/installation-impl';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n  if (!app || !app.options) {\n    throw getMissingValueError('App Configuration');\n  }\n\n  if (!app.name) {\n    throw getMissingValueError('App Name');\n  }\n\n  // Required app config keys\n  const configKeys: Array<keyof FirebaseOptions> = [\n    'projectId',\n    'apiKey',\n    'appId'\n  ];\n\n  for (const keyName of configKeys) {\n    if (!app.options[keyName]) {\n      throw getMissingValueError(keyName);\n    }\n  }\n\n  return {\n    appName: app.name,\n    projectId: app.options.projectId!,\n    apiKey: app.options.apiKey!,\n    appId: app.options.appId!\n  };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n  return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n    valueName\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 { _registerComponent, _getProvider } from '@firebase/app';\nimport {\n  Component,\n  ComponentType,\n  InstanceFactory,\n  ComponentContainer\n} from '@firebase/component';\nimport { getId, getToken } from '../api/index';\nimport { _FirebaseInstallationsInternal } from '../interfaces/public-types';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { extractAppConfig } from '../helpers/extract-app-config';\n\nconst INSTALLATIONS_NAME = 'installations';\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\n\nconst publicFactory: InstanceFactory<'installations'> = (\n  container: ComponentContainer\n) => {\n  const app = container.getProvider('app').getImmediate();\n  // Throws if app isn't configured properly.\n  const appConfig = extractAppConfig(app);\n  const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\n\n  const installationsImpl: FirebaseInstallationsImpl = {\n    app,\n    appConfig,\n    heartbeatServiceProvider,\n    _delete: () => Promise.resolve()\n  };\n  return installationsImpl;\n};\n\nconst internalFactory: InstanceFactory<'installations-internal'> = (\n  container: ComponentContainer\n) => {\n  const app = container.getProvider('app').getImmediate();\n  // Internal FIS instance relies on public FIS instance.\n  const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\n\n  const installationsInternal: _FirebaseInstallationsInternal = {\n    getId: () => getId(installations),\n    getToken: (forceRefresh?: boolean) => getToken(installations, forceRefresh)\n  };\n  return installationsInternal;\n};\n\nexport function registerInstallations(): void {\n  _registerComponent(\n    new Component(INSTALLATIONS_NAME, publicFactory, ComponentType.PUBLIC)\n  );\n  _registerComponent(\n    new Component(\n      INSTALLATIONS_NAME_INTERNAL,\n      internalFactory,\n      ComponentType.PRIVATE\n    )\n  );\n}\n","/**\n * The Firebase Installations Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\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\nimport { registerInstallations } from './functions/config';\nimport { registerVersion } from '@firebase/app';\nimport { name, version } from '../package.json';\n\nexport * from './api';\nexport * from './interfaces/public-types';\n\nregisterInstallations();\nregisterVersion(name, version);\n// BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\nregisterVersion(name, version, '__BUILD_TARGET__');\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 { FirebaseInstallations as FirebaseInstallationsCompat } from '@firebase/installations-types';\nimport { FirebaseApp, _FirebaseService } from '@firebase/app-compat';\nimport {\n  Installations,\n  deleteInstallations,\n  getId,\n  getToken,\n  IdChangeCallbackFn,\n  IdChangeUnsubscribeFn,\n  onIdChange\n} from '@firebase/installations';\n\nexport class InstallationsCompat\n  implements FirebaseInstallationsCompat, _FirebaseService\n{\n  constructor(public app: FirebaseApp, readonly _delegate: Installations) {}\n\n  getId(): Promise<string> {\n    return getId(this._delegate);\n  }\n  getToken(forceRefresh?: boolean): Promise<string> {\n    return getToken(this._delegate, forceRefresh);\n  }\n  delete(): Promise<void> {\n    return deleteInstallations(this._delegate);\n  }\n  onIdChange(callback: IdChangeCallbackFn): IdChangeUnsubscribeFn {\n    return onIdChange(this._delegate, callback);\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\nimport { deleteInstallationRequest } from '../functions/delete-installation-request';\nimport { remove, update } from '../helpers/idb-manager';\nimport { RequestStatus } from '../interfaces/installation-entry';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseInstallationsImpl } from '../interfaces/installation-impl';\nimport { Installations } from '../interfaces/public-types';\n\n/**\n * Deletes the Firebase Installation and all associated data.\n * @param installations - The `Installations` instance.\n *\n * @public\n */\nexport async function deleteInstallations(\n  installations: Installations\n): Promise<void> {\n  const { appConfig } = installations as FirebaseInstallationsImpl;\n\n  const entry = await update(appConfig, oldEntry => {\n    if (oldEntry && oldEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n      // Delete the unregistered entry without sending a deleteInstallation request.\n      return undefined;\n    }\n    return oldEntry;\n  });\n\n  if (entry) {\n    if (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n      // Can't delete while trying to register.\n      throw ERROR_FACTORY.create(ErrorCode.DELETE_PENDING_REGISTRATION);\n    } else if (entry.registrationStatus === RequestStatus.COMPLETED) {\n      if (!navigator.onLine) {\n        throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n      } else {\n        await deleteInstallationRequest(appConfig, entry);\n        await remove(appConfig);\n      }\n    }\n  }\n}\n"],"names":["FirebaseError","Error","constructor","code","message","customData","super","this","name","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","let","ptr","result","length","start","indexOf","substring","end","key","value","String","e","fullMessage","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","instanceOfAny","object","constructors","some","c","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","get","target","prop","receiver","IDBTransaction","objectStoreNames","undefined","objectStore","wrap","set","has","wrapFunction","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","includes","args","apply","unwrap","storeNames","tx","call","sort","transformCachableValue","done","Promise","resolve","reject","unlisten","removeEventListener","complete","error","DOMException","addEventListener","IDBObjectStore","IDBIndex","Proxy","request","newValue","IDBRequest","promise","success","then","catch","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","async","storeName","store","index","shift","all","oldTraps","PENDING_TIMEOUT_MS","PACKAGE_VERSION","version","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","instance","ERROR_FACTORY","missing-app-config-values","not-registered","installation-not-found","request-failed","app-offline","delete-pending-registration","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","token","requestStatus","expiresIn","Number","creationTime","Date","now","getErrorFromResponse","requestName","errorData","await","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Content-Type","Accept","x-goog-api-key","getHeadersWithAuth","appConfig","refreshToken","headers","append","retryIfServerError","fn","sleep","ms","setTimeout","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","fid","self","crypto","msCrypto","getRandomValues","array","btoa","fromCharCode","substr","test","getKey","appName","appId","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","channel","getBroadcastChannel","postMessage","closeBroadcastChannel","callbacks","broadcastChannel","BroadcastChannel","onmessage","size","close","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","createObjectStore","oldValue","put","remove","delete","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","clearTimedOutRequest","registrationStatus","entryWithPromise","inProgressEntry","navigator","onLine","registrationTime","registeredInstallationEntry","heartbeatServiceProvider","endpoint","body","heartbeatService","getImmediate","optional","heartbeatsHeader","getHeartbeatsHeader","authVersion","sdkVersion","JSON","stringify","fetch","ok","responseValue","authToken","registrationPromiseWithError","entry","updateInstallationRequest","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","updateAuthTokenRequest","inProgressAuthToken","requestTime","updatedInstallationEntry","getId","installationsImpl","console","getToken","deleteInstallationRequest","getDeleteEndpoint","onIdChange","addCallback","callbackSet","Set","add","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","app","container","getProvider","options","keyName","_getProvider","_delete","internalFactory","_registerComponent","registerVersion","InstallationsCompat","_delegate","firebase","INTERNAL","registerComponent"],"mappings":"mWAyEaA,UAAsBC,MAIjCC,YAEWC,EACTC,EAEOC,GAEPC,MAAMF,CAAO,EALJG,KAAAJ,KAAAA,EAGFI,KAAAF,WAAAA,EAPAE,KAAAC,KAdQ,gBA6BfC,OAAOC,eAAeH,KAAMP,EAAcW,SAAS,EAI/CV,MAAMW,mBACRX,MAAMW,kBAAkBL,KAAMM,EAAaF,UAAUG,MAAM,CAE/D,CACD,OAEYD,EAIXX,YACmBa,EACAC,EACAC,GAFAV,KAAAQ,QAAAA,EACAR,KAAAS,YAAAA,EACAT,KAAAU,OAAAA,CAChB,CAEHH,OACEX,KACGe,GAEH,IAAMb,EAAca,EAAK,IAAoB,GACvCC,EAAcZ,KAAKQ,QAAR,IAAmBZ,EAC9BiB,EAAWb,KAAKU,OAAOd,GAEvBC,EAAUgB,GAUpB,CAAyBA,EAAkBF,KACzC,IACEG,IAAIC,EAAM,EACNC,EAAS,GACb,KAAOD,EAAMF,EAASI,QAAQ,CAC5B,IAAMC,EAAQL,EAASM,QAAQ,KAAMJ,CAAG,EACxC,GAAc,CAAC,IAAXG,EAAc,CAChBF,GAAUH,EAASO,UAAUL,CAAG,EAChC,KACF,CACA,IAAMM,EAAMR,EAASM,QAAQ,IAAKD,EAAQ,CAAC,EAC3C,GAAY,CAAC,IAATG,EAAY,CACdL,GAAUH,EAASO,UAAUL,CAAG,EAChC,KACF,CACA,IAAMO,EAAMT,EAASO,UAAUF,EAAQ,EAAGG,CAAG,EACvCE,EAAQZ,EAAKW,GACnBN,GACEH,EAASO,UAAUL,EAAKG,CAAK,GACnB,MAATK,EAAgBC,OAAOD,CAAK,MAAQD,OACvCP,EAAMM,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