{"version":3,"file":"firebase-messaging.js","sources":["../util/src/errors.ts","../util/src/compat.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/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-token.ts","../installations/src/api/on-id-change.ts","../installations/src/helpers/extract-app-config.ts","../installations/src/functions/config.ts","../installations/src/api/get-id.ts","../installations/src/index.ts","../messaging/src/util/constants.ts","../messaging/src/interfaces/internal-message-payload.ts","../messaging/src/helpers/array-base64-translator.ts","../messaging/src/helpers/migrate-old-database.ts","../messaging/src/util/errors.ts","../messaging/src/internals/idb-manager.ts","../messaging/src/internals/requests.ts","../messaging/src/internals/token-manager.ts","../messaging/src/helpers/registerDefaultSw.ts","../messaging/src/helpers/updateSwReg.ts","../messaging/src/helpers/updateVapidKey.ts","../messaging/src/internals/register-fid.ts","../messaging/src/api/register.ts","../messaging/src/helpers/externalizePayload.ts","../messaging/src/helpers/extract-app-config.ts","../messaging/src/messaging-service.ts","../messaging/src/api/getToken.ts","../messaging/src/helpers/logToScion.ts","../messaging/src/listeners/window-listener.ts","../messaging/src/helpers/is-console-message.ts","../messaging/src/helpers/register.ts","../messaging/src/helpers/fid-change-registration.ts","../messaging/src/api/isSupported.ts","../util/src/environment.ts","../messaging/src/api.ts","../messaging/src/api/deleteToken.ts","../messaging/src/api/onMessage.ts","../messaging/src/api/unregister.ts","../messaging/src/api/onRegistered.ts","../messaging/src/api/onUnregistered.ts","../messaging/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/**\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 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 * @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 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 * 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 { 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 * @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 * 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 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 const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\nexport const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\nexport const DEFAULT_VAPID_KEY =\n  'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\n\nexport const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\n\n/** Key of FCM Payload in Notification's data field. */\nexport const FCM_MSG = 'FCM_MSG';\n\nexport const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\nexport const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\nexport const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\n/** Set to '1' if Analytics is enabled for the campaign */\nexport const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\nexport const TAG = 'FirebaseMessaging: ';\nexport const MAX_NUMBER_OF_EVENTS_PER_LOG_REQUEST = 1000;\nexport const MAX_RETRIES = 3;\nexport const LOG_INTERVAL_IN_MS = 86400000; //24 hour\nexport const DEFAULT_BACKOFF_TIME_MS = 5000;\nexport const DEFAULT_REGISTRATION_TIMEOUT = 10000;\n\n// FCM log source name registered at Firelog: 'FCM_CLIENT_EVENT_LOGGING'. It uniquely identifies\n// FCM's logging configuration.\nexport const FCM_LOG_SOURCE = 1249;\n\n// Defined as in proto/messaging_event.proto. Neglecting fields that are supported.\nexport const SDK_PLATFORM_WEB = 3;\nexport const EVENT_MESSAGE_DELIVERED = 1;\n\nexport enum MessageType {\n  DATA_MESSAGE = 1,\n  DISPLAY_NOTIFICATION = 3\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. 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 distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport {\n  CONSOLE_CAMPAIGN_ANALYTICS_ENABLED,\n  CONSOLE_CAMPAIGN_ID,\n  CONSOLE_CAMPAIGN_NAME,\n  CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\n\nexport interface MessagePayloadInternal {\n  notification?: NotificationPayloadInternal;\n  data?: unknown;\n  fcmOptions?: FcmOptionsInternal;\n  messageType?: MessageType;\n  isFirebaseMessaging?: boolean;\n  from: string;\n  fcmMessageId: string;\n  productId: number;\n  // eslint-disable-next-line camelcase\n  collapse_key: string;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Notification/actions\ninterface NotificationAction {\n  action: string;\n  icon?: string;\n  title: string;\n}\n\n/**\n * This interface defines experimental properties of NotificationOptions, that are not part of\n * the interface in the generated DOM types at https://github.com/microsoft/TypeScript-DOM-lib-generator/blob/179bdd84a944933a3103f29c2274c9f5a857b693/baselines/dom.generated.d.ts#L1012\n * https://developer.mozilla.org/en-US/docs/Web/API/Notification\n */\ninterface NotificationOptionsExperimental extends NotificationOptions {\n  readonly maxActions?: number;\n  readonly actions?: NotificationAction[];\n  readonly image?: string;\n  readonly renotify?: boolean;\n  readonly timestamp?: EpochTimeStamp;\n  readonly vibrate?: VibratePattern;\n}\n\nexport interface NotificationPayloadInternal\n  extends NotificationOptionsExperimental {\n  title: string;\n  // Supported in the Legacy Send API.\n  // See:https://firebase.google.com/docs/cloud-messaging/xmpp-server-ref.\n  // eslint-disable-next-line camelcase\n  click_action?: string;\n  icon?: string;\n}\n\n// Defined in\n// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushfcmoptions. Note\n// that the keys are sent to the clients in snake cases which we need to convert to camel so it can\n// be exposed as a type to match the Firebase API convention.\nexport interface FcmOptionsInternal {\n  link?: string;\n\n  // eslint-disable-next-line camelcase\n  analytics_label?: string;\n}\n\nexport enum MessageType {\n  PUSH_RECEIVED = 'push-received',\n  NOTIFICATION_CLICKED = 'notification-clicked',\n  FID_REGISTERED = 'fid-registered'\n}\n\n/** Additional data of a message sent from the FN Console. */\nexport interface ConsoleMessageData {\n  [CONSOLE_CAMPAIGN_ID]: string;\n  [CONSOLE_CAMPAIGN_TIME]: string;\n  [CONSOLE_CAMPAIGN_NAME]?: string;\n  [CONSOLE_CAMPAIGN_ANALYTICS_ENABLED]?: '1';\n}\n\nexport interface FidRegisteredPayload {\n  isFirebaseMessaging: boolean;\n  messageType: MessageType.FID_REGISTERED;\n  fid: string;\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 function arrayToBase64(array: Uint8Array | ArrayBuffer): string {\n  const uint8Array = new Uint8Array(array);\n  const base64String = btoa(String.fromCharCode(...uint8Array));\n  return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n\nexport function base64ToArray(base64String: string): Uint8Array {\n  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n  const base64 = (base64String + padding)\n    .replace(/\\-/g, '+')\n    .replace(/_/g, '/');\n\n  const rawData = atob(base64);\n  const outputArray = new Uint8Array(rawData.length);\n\n  for (let i = 0; i < rawData.length; ++i) {\n    outputArray[i] = rawData.charCodeAt(i);\n  }\n  return outputArray;\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 { deleteDB, openDB } from 'idb';\n\nimport { TokenDetails } from '../interfaces/registration-details';\nimport { arrayToBase64 } from './array-base64-translator';\n\n// https://github.com/firebase/firebase-js-sdk/blob/7857c212f944a2a9eb421fd4cb7370181bc034b5/packages/messaging/src/interfaces/token-details.ts\nexport interface V2TokenDetails {\n  fcmToken: string;\n  swScope: string;\n  vapidKey: string | Uint8Array;\n  subscription: PushSubscription;\n  fcmSenderId: string;\n  fcmPushSet: string;\n  createTime?: number;\n  endpoint?: string;\n  auth?: string;\n  p256dh?: string;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/6b5b15ce4ea3df5df5df8a8b33a4e41e249c7715/packages/messaging/src/interfaces/registration-details.ts\nexport interface V3TokenDetails {\n  fcmToken: string;\n  swScope: string;\n  vapidKey: Uint8Array;\n  fcmSenderId: string;\n  fcmPushSet: string;\n  endpoint: string;\n  auth: ArrayBuffer;\n  p256dh: ArrayBuffer;\n  createTime: number;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/9567dba664732f681fa7fe60f5b7032bb1daf4c9/packages/messaging/src/interfaces/registration-details.ts\nexport interface V4TokenDetails {\n  fcmToken: string;\n  swScope: string;\n  vapidKey: Uint8Array;\n  fcmSenderId: string;\n  endpoint: string;\n  auth: ArrayBufferLike;\n  p256dh: ArrayBufferLike;\n  createTime: number;\n}\n\nconst OLD_DB_NAME = 'fcm_token_details_db';\n/**\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\n * callback is called for all versions of the old DB.\n */\nconst OLD_DB_VERSION = 5;\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\n\nexport async function migrateOldDatabase(\n  senderId: string\n): Promise<TokenDetails | null> {\n  if ('databases' in indexedDB) {\n    // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove\n    // typecast when it lands in TS types.\n    const databases = await (\n      indexedDB as {\n        databases(): Promise<Array<{ name: string; version: number }>>;\n      }\n    ).databases();\n    const dbNames = databases.map(db => db.name);\n\n    if (!dbNames.includes(OLD_DB_NAME)) {\n      // old DB didn't exist, no need to open.\n      return null;\n    }\n  }\n\n  let tokenDetails: TokenDetails | null = null;\n\n  const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {\n    upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {\n      if (oldVersion < 2) {\n        // Database too old, skip migration.\n        return;\n      }\n\n      if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n        // Database did not exist. Nothing to do.\n        return;\n      }\n\n      const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);\n      const value = await objectStore.index('fcmSenderId').get(senderId);\n      await objectStore.clear();\n\n      if (!value) {\n        // No entry in the database, nothing to migrate.\n        return;\n      }\n\n      if (oldVersion === 2) {\n        const oldDetails = value as V2TokenDetails;\n\n        if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\n          return;\n        }\n\n        tokenDetails = {\n          token: oldDetails.fcmToken,\n          createTime: oldDetails.createTime ?? Date.now(),\n          subscriptionOptions: {\n            auth: oldDetails.auth,\n            p256dh: oldDetails.p256dh,\n            endpoint: oldDetails.endpoint,\n            swScope: oldDetails.swScope,\n            vapidKey:\n              typeof oldDetails.vapidKey === 'string'\n                ? oldDetails.vapidKey\n                : arrayToBase64(oldDetails.vapidKey)\n          }\n        };\n      } else if (oldVersion === 3) {\n        const oldDetails = value as V3TokenDetails;\n\n        tokenDetails = {\n          token: oldDetails.fcmToken,\n          createTime: oldDetails.createTime,\n          subscriptionOptions: {\n            auth: arrayToBase64(oldDetails.auth),\n            p256dh: arrayToBase64(oldDetails.p256dh),\n            endpoint: oldDetails.endpoint,\n            swScope: oldDetails.swScope,\n            vapidKey: arrayToBase64(oldDetails.vapidKey)\n          }\n        };\n      } else if (oldVersion === 4) {\n        const oldDetails = value as V4TokenDetails;\n\n        tokenDetails = {\n          token: oldDetails.fcmToken,\n          createTime: oldDetails.createTime,\n          subscriptionOptions: {\n            auth: arrayToBase64(oldDetails.auth),\n            p256dh: arrayToBase64(oldDetails.p256dh),\n            endpoint: oldDetails.endpoint,\n            swScope: oldDetails.swScope,\n            vapidKey: arrayToBase64(oldDetails.vapidKey)\n          }\n        };\n      }\n    }\n  });\n  db.close();\n\n  // Delete all old databases.\n  await deleteDB(OLD_DB_NAME);\n  await deleteDB('fcm_vapid_details_db');\n  await deleteDB('undefined');\n\n  return checkTokenDetails(tokenDetails) ? tokenDetails : null;\n}\n\nfunction checkTokenDetails(\n  tokenDetails: TokenDetails | null\n): tokenDetails is TokenDetails {\n  if (!tokenDetails || !tokenDetails.subscriptionOptions) {\n    return false;\n  }\n  const { subscriptionOptions } = tokenDetails;\n  return (\n    typeof tokenDetails.createTime === 'number' &&\n    tokenDetails.createTime > 0 &&\n    typeof tokenDetails.token === 'string' &&\n    tokenDetails.token.length > 0 &&\n    typeof subscriptionOptions.auth === 'string' &&\n    subscriptionOptions.auth.length > 0 &&\n    typeof subscriptionOptions.p256dh === 'string' &&\n    subscriptionOptions.p256dh.length > 0 &&\n    typeof subscriptionOptions.endpoint === 'string' &&\n    subscriptionOptions.endpoint.length > 0 &&\n    typeof subscriptionOptions.swScope === 'string' &&\n    subscriptionOptions.swScope.length > 0 &&\n    typeof subscriptionOptions.vapidKey === 'string' &&\n    subscriptionOptions.vapidKey.length > 0\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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum ErrorCode {\n  MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n  AVAILABLE_IN_WINDOW = 'only-available-in-window',\n  AVAILABLE_IN_SW = 'only-available-in-sw',\n  PERMISSION_DEFAULT = 'permission-default',\n  PERMISSION_BLOCKED = 'permission-blocked',\n  UNSUPPORTED_BROWSER = 'unsupported-browser',\n  INDEXED_DB_UNSUPPORTED = 'indexed-db-unsupported',\n  FAILED_DEFAULT_REGISTRATION = 'failed-service-worker-registration',\n  TOKEN_SUBSCRIBE_FAILED = 'token-subscribe-failed',\n  TOKEN_SUBSCRIBE_NO_TOKEN = 'token-subscribe-no-token',\n  FID_REGISTRATION_FAILED = 'fid-registration-failed',\n  FID_UNREGISTER_FAILED = 'fid-unregister-failed',\n  FID_REGISTRATION_IDB_SCHEMA_UNAVAILABLE = 'fid-registration-idb-schema-unavailable',\n  TOKEN_UNSUBSCRIBE_FAILED = 'token-unsubscribe-failed',\n  TOKEN_UPDATE_FAILED = 'token-update-failed',\n  TOKEN_UPDATE_NO_TOKEN = 'token-update-no-token',\n  INVALID_BG_HANDLER = 'invalid-bg-handler',\n  USE_SW_AFTER_GET_TOKEN = 'use-sw-after-get-token',\n  INVALID_SW_REGISTRATION = 'invalid-sw-registration',\n  USE_VAPID_KEY_AFTER_GET_TOKEN = 'use-vapid-key-after-get-token',\n  INVALID_VAPID_KEY = 'invalid-vapid-key',\n  INVALID_ON_REGISTERED_HANDLER = 'invalid-on-registered-handler'\n}\n\nexport const ERROR_MAP: ErrorMap<ErrorCode> = {\n  [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n    'Missing App configuration value: \"{$valueName}\"',\n  [ErrorCode.AVAILABLE_IN_WINDOW]:\n    'This method is available in a Window context.',\n  [ErrorCode.AVAILABLE_IN_SW]:\n    'This method is available in a service worker context.',\n  [ErrorCode.PERMISSION_DEFAULT]:\n    'The notification permission was not granted and dismissed instead.',\n  [ErrorCode.PERMISSION_BLOCKED]:\n    'The notification permission was not granted and blocked instead.',\n  [ErrorCode.UNSUPPORTED_BROWSER]:\n    \"This browser doesn't support the API's required to use the Firebase SDK.\",\n  [ErrorCode.INDEXED_DB_UNSUPPORTED]:\n    \"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)\",\n  [ErrorCode.FAILED_DEFAULT_REGISTRATION]:\n    'We are unable to register the default service worker. {$browserErrorMessage}',\n  [ErrorCode.TOKEN_SUBSCRIBE_FAILED]:\n    'A problem occurred while subscribing the user to FCM: {$errorInfo}',\n  [ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN]:\n    'FCM returned no token when subscribing the user to push.',\n  [ErrorCode.FID_REGISTRATION_FAILED]:\n    'A problem occurred while creating an FCM registration via FID: {$errorInfo}',\n  [ErrorCode.FID_UNREGISTER_FAILED]:\n    'A problem occurred while unregistering the FCM registration via FID: {$errorInfo}',\n  [ErrorCode.FID_REGISTRATION_IDB_SCHEMA_UNAVAILABLE]:\n    'Unable to read or persist FID registration metadata because the messaging ' +\n    'IndexedDB schema is unavailable (for example, the database could not be ' +\n    'upgraded to the latest version).',\n  [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]:\n    'A problem occurred while unsubscribing the ' +\n    'user from FCM: {$errorInfo}',\n  [ErrorCode.TOKEN_UPDATE_FAILED]:\n    'A problem occurred while updating the user from FCM: {$errorInfo}',\n  [ErrorCode.TOKEN_UPDATE_NO_TOKEN]:\n    'FCM returned no token when updating the user to push.',\n  [ErrorCode.USE_SW_AFTER_GET_TOKEN]:\n    'The useServiceWorker() method may only be called once and must be ' +\n    'called before calling getToken() to ensure your service worker is used.',\n  [ErrorCode.INVALID_SW_REGISTRATION]:\n    'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\n  [ErrorCode.INVALID_BG_HANDLER]:\n    'The input to setBackgroundMessageHandler() must be a function.',\n  [ErrorCode.INVALID_VAPID_KEY]: 'The public VAPID key must be a string.',\n  [ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN]:\n    'The usePublicVapidKey() method may only be called once and must be ' +\n    'called before calling getToken() to ensure your VAPID key is used.',\n  [ErrorCode.INVALID_ON_REGISTERED_HANDLER]:\n    'No onRegistered callback handler was provided or registered. Implement onRegistered() before register().'\n};\n\ninterface ErrorParams {\n  [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n    valueName: string;\n  };\n  [ErrorCode.FAILED_DEFAULT_REGISTRATION]: { browserErrorMessage: string };\n  [ErrorCode.TOKEN_SUBSCRIBE_FAILED]: { errorInfo: string };\n  [ErrorCode.FID_REGISTRATION_FAILED]: { errorInfo: string };\n  [ErrorCode.FID_UNREGISTER_FAILED]: { errorInfo: string };\n  [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]: { errorInfo: string };\n  [ErrorCode.TOKEN_UPDATE_FAILED]: { errorInfo: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n  'messaging',\n  'Messaging',\n  ERROR_MAP\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 { deleteDB, openDB } from 'idb';\nimport type { DBSchema, IDBPDatabase, OpenDBCallbacks } from 'idb';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { TokenDetails } from '../interfaces/registration-details';\nimport { migrateOldDatabase } from '../helpers/migrate-old-database';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport const DATABASE_NAME = 'firebase-messaging-database';\nconst DATABASE_VERSION = 2;\nconst TOKEN_OBJECT_STORE_NAME = 'firebase-messaging-store';\nconst FID_REGISTRATION_OBJECT_STORE_NAME =\n  'firebase-messaging-fid-registration-store';\n\ninterface MessagingDB extends DBSchema {\n  'firebase-messaging-store': {\n    key: string;\n    value: TokenDetails;\n  };\n  'firebase-messaging-fid-registration-store': {\n    key: string;\n    value: FidRegistrationDetails;\n  };\n}\n\nexport interface FidRegistrationDetails {\n  fid: string;\n  lastRegisterTime: number;\n  vapidKey?: string;\n}\n\ninterface IdbImpl {\n  openDB: typeof openDB;\n  deleteDB: typeof deleteDB;\n}\n\nconst defaultIdb: IdbImpl = { openDB, deleteDB };\nlet idbImpl: IdbImpl = defaultIdb;\n\n// Exported for tests.\nexport function _setIdbForTests(impl: IdbImpl): void {\n  idbImpl = impl;\n}\n\nexport function _resetIdbForTests(): void {\n  idbImpl = defaultIdb;\n}\n\n// Open v2, but fall back to v1 if upgrade/open fails. Cache as `unknown` and guard store access.\nlet dbPromise: Promise<IDBPDatabase<unknown>> | null = null;\n\nfunction migrateMessagingDb(\n  upgradeDb: IDBPDatabase<unknown>,\n  oldVersion: number,\n  targetSchemaVersion: 1 | 2\n): void {\n  // Intentional fall-through for v2: run all intermediate migrations.\n  // eslint-disable-next-line default-case\n  switch (oldVersion) {\n    case 0:\n      upgradeDb.createObjectStore(TOKEN_OBJECT_STORE_NAME);\n      if (targetSchemaVersion === 1) {\n        break;\n      }\n    // fall through\n    case 1:\n      if (targetSchemaVersion === 2) {\n        upgradeDb.createObjectStore(FID_REGISTRATION_OBJECT_STORE_NAME);\n      }\n  }\n}\n\nfunction createOpenDbOptions(\n  targetSchemaVersion: 1 | 2\n): OpenDBCallbacks<unknown> {\n  return {\n    upgrade: (upgradeDb: IDBPDatabase<unknown>, oldVersion: number) => {\n      migrateMessagingDb(upgradeDb, oldVersion, targetSchemaVersion);\n    },\n    blocked: () => {\n      /* no-op */\n    },\n    blocking: (\n      _currentVersion: number,\n      _blockedVersion: number | null,\n      event: IDBVersionChangeEvent\n    ) => {\n      dbPromise = null;\n      (event.target as IDBDatabase | null)?.close();\n    },\n    terminated: () => {\n      dbPromise = null;\n    }\n  };\n}\n\nfunction getDbPromise(): Promise<IDBPDatabase<MessagingDB>> {\n  if (!dbPromise) {\n    const openLatest = idbImpl.openDB(\n      DATABASE_NAME,\n      DATABASE_VERSION,\n      createOpenDbOptions(2)\n    );\n\n    // Assign synchronously to avoid concurrent openDB() calls.\n    dbPromise = (openLatest as unknown as Promise<IDBPDatabase<unknown>>).catch(\n      () =>\n        idbImpl.openDB(\n          DATABASE_NAME,\n          DATABASE_VERSION - 1,\n          createOpenDbOptions(1)\n        ) as unknown as Promise<IDBPDatabase<unknown>>\n    );\n  }\n  return dbPromise as Promise<IDBPDatabase<MessagingDB>>;\n}\n\nfunction hasObjectStore(db: IDBPDatabase<unknown>, storeName: string): boolean {\n  return db.objectStoreNames.contains(storeName);\n}\n\nfunction assertFidRegistrationObjectStore(db: IDBPDatabase<MessagingDB>): void {\n  if (\n    !hasObjectStore(\n      db as unknown as IDBPDatabase<unknown>,\n      FID_REGISTRATION_OBJECT_STORE_NAME\n    )\n  ) {\n    throw ERROR_FACTORY.create(\n      ErrorCode.FID_REGISTRATION_IDB_SCHEMA_UNAVAILABLE\n    );\n  }\n}\n\nexport async function dbGet(\n  firebaseDependencies: FirebaseInternalDependencies\n): Promise<TokenDetails | undefined> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n  const tokenDetails = (await db\n    .transaction(TOKEN_OBJECT_STORE_NAME)\n    .objectStore(TOKEN_OBJECT_STORE_NAME)\n    .get(key)) as TokenDetails;\n\n  if (tokenDetails) {\n    return tokenDetails;\n  } else {\n    const oldTokenDetails = await migrateOldDatabase(\n      firebaseDependencies.appConfig.senderId\n    );\n    if (oldTokenDetails) {\n      await dbSet(firebaseDependencies, oldTokenDetails);\n      return oldTokenDetails;\n    }\n  }\n}\n\nexport async function dbSet(\n  firebaseDependencies: FirebaseInternalDependencies,\n  tokenDetails: TokenDetails\n): Promise<TokenDetails> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n\n  const stores: Array<\n    typeof TOKEN_OBJECT_STORE_NAME | typeof FID_REGISTRATION_OBJECT_STORE_NAME\n  > = [TOKEN_OBJECT_STORE_NAME];\n  const hasFidStore = hasObjectStore(\n    db as unknown as IDBPDatabase<unknown>,\n    FID_REGISTRATION_OBJECT_STORE_NAME\n  );\n  if (hasFidStore) {\n    stores.push(FID_REGISTRATION_OBJECT_STORE_NAME);\n  }\n\n  const tx = db.transaction(stores, 'readwrite');\n  await tx.objectStore(TOKEN_OBJECT_STORE_NAME).put(tokenDetails, key);\n  if (hasFidStore) {\n    await tx.objectStore(FID_REGISTRATION_OBJECT_STORE_NAME).delete(key);\n  }\n  await tx.done;\n\n  return tokenDetails;\n}\n\nexport async function dbRemove(\n  firebaseDependencies: FirebaseInternalDependencies\n): Promise<void> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n  const tx = db.transaction(TOKEN_OBJECT_STORE_NAME, 'readwrite');\n  await tx.objectStore(TOKEN_OBJECT_STORE_NAME).delete(key);\n  await tx.done;\n}\n\nexport async function dbGetFidRegistration(\n  firebaseDependencies: FirebaseInternalDependencies\n): Promise<FidRegistrationDetails | undefined> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n  assertFidRegistrationObjectStore(db);\n  return (await db\n    .transaction(FID_REGISTRATION_OBJECT_STORE_NAME)\n    .objectStore(FID_REGISTRATION_OBJECT_STORE_NAME)\n    .get(key)) as FidRegistrationDetails | undefined;\n}\n\nexport async function dbSetFidRegistration(\n  firebaseDependencies: FirebaseInternalDependencies,\n  details: FidRegistrationDetails\n): Promise<FidRegistrationDetails> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n  assertFidRegistrationObjectStore(db);\n\n  const tx = db.transaction(\n    [TOKEN_OBJECT_STORE_NAME, FID_REGISTRATION_OBJECT_STORE_NAME],\n    'readwrite'\n  );\n  await tx.objectStore(FID_REGISTRATION_OBJECT_STORE_NAME).put(details, key);\n  await tx.objectStore(TOKEN_OBJECT_STORE_NAME).delete(key);\n  await tx.done;\n\n  return details;\n}\n\nexport async function dbRemoveFidRegistration(\n  firebaseDependencies: FirebaseInternalDependencies\n): Promise<void> {\n  const key = getKey(firebaseDependencies);\n  const db = await getDbPromise();\n  assertFidRegistrationObjectStore(db);\n  const tx = db.transaction(FID_REGISTRATION_OBJECT_STORE_NAME, 'readwrite');\n  await tx.objectStore(FID_REGISTRATION_OBJECT_STORE_NAME).delete(key);\n  await tx.done;\n}\n\n/** Deletes the DB. Useful for tests. */\nexport async function dbDelete(): Promise<void> {\n  const promise = dbPromise;\n  dbPromise = null;\n\n  try {\n    if (promise) {\n      (await promise).close();\n    }\n  } catch {\n    // Ignore open failures; deleting the DB is the recovery mechanism.\n  } finally {\n    await idbImpl.deleteDB(DATABASE_NAME);\n  }\n}\n\nfunction getKey({ appConfig }: FirebaseInternalDependencies): string {\n  return 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 { DEFAULT_VAPID_KEY, ENDPOINT } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport {\n  SubscriptionOptions,\n  TokenDetails\n} from '../interfaces/registration-details';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { version as fcmSdkVersion } from '../../package.json';\n\n/** Max attempts (initial fetch + retries) when CreateRegistration `fetch()` throws. */\nexport const FID_REGISTRATION_FETCH_MAX_ATTEMPTS = 3;\n\n/** Base delay in ms; backoff is `BASE * 2^attempt` after each failed attempt. */\nexport const FID_REGISTRATION_FETCH_BASE_BACKOFF_MS = 1000;\n\nexport interface ApiResponse {\n  token?: string;\n  /**\n   * CreateRegistration resource name, e.g. `projects/{projectId}/registrations/{fid}`.\n   */\n  name?: string;\n  error?: { message: string };\n}\n\nexport interface ApiRequestBody {\n  // eslint-disable-next-line camelcase\n  fcm_sdk_version?: string;\n  web: {\n    /**\n     * Client identifier for the registration: the site host (e.g. `www.example.com`) when the\n     * service worker scope is a URL, otherwise the app name.\n     */\n    origin: string;\n    endpoint: string;\n    p256dh: string;\n    auth: string;\n    applicationPubKey?: string;\n  };\n}\n\nexport async function requestGetToken(\n  firebaseDependencies: FirebaseInternalDependencies,\n  subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n  const headers = await getHeaders(firebaseDependencies);\n  const body = getBody(\n    subscriptionOptions,\n    firebaseDependencies.appConfig.appName,\n    /* includeSdkVersion= */ false\n  );\n\n  const subscribeOptions = {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body)\n  };\n\n  let responseData: ApiResponse;\n  try {\n    const response = await fetch(\n      getEndpoint(firebaseDependencies.appConfig),\n      subscribeOptions\n    );\n    responseData = await response.json();\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n      errorInfo: (err as Error)?.toString()\n    });\n  }\n\n  if (responseData.error) {\n    const message = responseData.error.message;\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n      errorInfo: message\n    });\n  }\n\n  if (!responseData.token) {\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN);\n  }\n\n  return responseData.token;\n}\n\n/**\n * Creates (or refreshes) an FCM Web registration via CreateRegistration.\n *\n * This is used by the FID-based register path, where we don't require the returned FCM token, but\n * we do require a non-empty `name` (echoing the Firebase Installation ID) in the success response body.\n */\nexport interface CreateRegistrationResult {\n  /** Firebase Installation ID parsed from the CreateRegistration response `name` field. */\n  responseFid: string;\n}\n\nexport async function requestCreateRegistration(\n  firebaseDependencies: FirebaseInternalDependencies,\n  subscriptionOptions: SubscriptionOptions\n): Promise<CreateRegistrationResult> {\n  const headers = await getHeaders(firebaseDependencies);\n  const body = getBody(\n    subscriptionOptions,\n    firebaseDependencies.appConfig.appName,\n    /* includeSdkVersion= */ true\n  );\n\n  const subscribeOptions = {\n    method: 'POST',\n    headers,\n    body: JSON.stringify(body)\n  };\n\n  let response: Response;\n  try {\n    response = await fetchWithExponentialRetry(\n      () =>\n        fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions),\n      FID_REGISTRATION_FETCH_MAX_ATTEMPTS,\n      FID_REGISTRATION_FETCH_BASE_BACKOFF_MS\n    );\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n      errorInfo: (err as Error)?.toString()\n    });\n  }\n\n  if (response.ok) {\n    const responseFid = await parseCreateRegistrationSuccessFid(response);\n    return { responseFid };\n  }\n\n  // `fetch()` succeeded, but the backend returned a non-2xx response.\n  // Best-effort parse the body to extract `error.message`, but always fail with\n  // `FID_REGISTRATION_FAILED` to keep the error surface uniform.\n  // Best-effort extraction of error details; the main signal is response.ok / status.\n  let responseData: ApiResponse;\n  try {\n    responseData = (await response.json()) as ApiResponse;\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n      errorInfo: response.statusText\n    });\n  }\n  const message = responseData.error?.message ?? response.statusText;\n  throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n    errorInfo: message\n  });\n}\n\n/**\n * Deletes an FCM Web registration via DeleteRegistration using the Firebase Installation ID (FID).\n */\nexport async function requestDeleteRegistration(\n  firebaseDependencies: FirebaseInternalDependencies,\n  fid: string\n): Promise<void> {\n  const headers = await getHeaders(firebaseDependencies);\n\n  const options: RequestInit = {\n    method: 'DELETE',\n    headers\n  };\n\n  let response: Response;\n  try {\n    response = await fetch(\n      `${getEndpoint(firebaseDependencies.appConfig)}/${fid}`,\n      options\n    );\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.FID_UNREGISTER_FAILED, {\n      errorInfo: (err as Error)?.toString()\n    });\n  }\n\n  if (response.ok) {\n    return;\n  }\n\n  // Best-effort parse error details; surface uniform error code.\n  try {\n    const responseData = (await response.json()) as ApiResponse;\n    const message = responseData.error?.message ?? response.statusText;\n    throw message;\n  } catch (err) {\n    // If parsing failed, fall back to status text.\n    throw ERROR_FACTORY.create(ErrorCode.FID_UNREGISTER_FAILED, {\n      errorInfo:\n        (typeof err === 'string' && err) ||\n        response.statusText ||\n        (err as Error)?.toString()\n    });\n  }\n}\n\n/**\n * Parses a successful CreateRegistration body. The backend must return JSON with a non-empty\n * string `name`: a resource name `projects/{projectId}/registrations/{fid}`\n */\nasync function parseCreateRegistrationSuccessFid(\n  response: Response\n): Promise<string> {\n  const text = await response.text();\n  if (!text.trim()) {\n    throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n      errorInfo: 'CreateRegistration succeeded but response body is empty'\n    });\n  }\n  let data: ApiResponse;\n  try {\n    data = JSON.parse(text) as ApiResponse;\n  } catch {\n    throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n      errorInfo:\n        'CreateRegistration succeeded but response body is not valid JSON'\n    });\n  }\n  const name = data.name;\n  if (typeof name !== 'string' || name.length === 0) {\n    throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n      errorInfo:\n        'CreateRegistration succeeded but response did not include a non-empty name'\n    });\n  }\n  return parseFidFromRegistrationResourceName(name);\n}\n\nconst REGISTRATIONS_NAME_SEGMENT = '/registrations/';\n\n/** Extracts the Firebase Installation ID from CreateRegistration `name` (resource path). */\nfunction parseFidFromRegistrationResourceName(name: string): string {\n  const segmentIndex = name.indexOf(REGISTRATIONS_NAME_SEGMENT);\n  if (segmentIndex !== -1) {\n    const fid = name.slice(segmentIndex + REGISTRATIONS_NAME_SEGMENT.length);\n    if (fid.length > 0) {\n      return fid;\n    }\n  }\n  throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n    errorInfo:\n      'CreateRegistration succeeded but response name is not a valid registration resource name'\n  });\n}\n\nexport async function requestUpdateToken(\n  firebaseDependencies: FirebaseInternalDependencies,\n  tokenDetails: TokenDetails\n): Promise<string> {\n  const headers = await getHeaders(firebaseDependencies);\n  const body = getBody(\n    tokenDetails.subscriptionOptions!,\n    firebaseDependencies.appConfig.appName,\n    /* includeSdkVersion= */ false\n  );\n\n  const updateOptions = {\n    method: 'PATCH',\n    headers,\n    body: JSON.stringify(body)\n  };\n\n  let responseData: ApiResponse;\n  try {\n    const response = await fetch(\n      `${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`,\n      updateOptions\n    );\n    responseData = await response.json();\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n      errorInfo: (err as Error)?.toString()\n    });\n  }\n\n  if (responseData.error) {\n    const message = responseData.error.message;\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n      errorInfo: message\n    });\n  }\n\n  if (!responseData.token) {\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_NO_TOKEN);\n  }\n\n  return responseData.token;\n}\n\nexport async function requestDeleteToken(\n  firebaseDependencies: FirebaseInternalDependencies,\n  token: string\n): Promise<void> {\n  const headers = await getHeaders(firebaseDependencies);\n\n  const unsubscribeOptions = {\n    method: 'DELETE',\n    headers\n  };\n\n  try {\n    const response = await fetch(\n      `${getEndpoint(firebaseDependencies.appConfig)}/${token}`,\n      unsubscribeOptions\n    );\n    const responseData: ApiResponse = await response.json();\n    if (responseData.error) {\n      const message = responseData.error.message;\n      throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n        errorInfo: message\n      });\n    }\n  } catch (err) {\n    throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n      errorInfo: (err as Error)?.toString()\n    });\n  }\n}\n\n/**\n * Re-runs `operation` when it throws, with exponential backoff between attempts.\n * Rethrows the last error if all attempts fail.\n */\nasync function fetchWithExponentialRetry(\n  operation: () => Promise<Response>,\n  maxAttempts: number,\n  baseBackoffMs: number\n): Promise<Response> {\n  let lastError: unknown;\n  for (let attempt = 0; attempt < maxAttempts; attempt++) {\n    try {\n      return await operation();\n    } catch (err) {\n      lastError = err;\n      if (attempt < maxAttempts - 1) {\n        const delayMs = baseBackoffMs * Math.pow(2, attempt);\n        await new Promise<void>(resolve => setTimeout(resolve, delayMs));\n      }\n    }\n  }\n  throw lastError;\n}\n\nfunction getEndpoint({ projectId }: AppConfig): string {\n  return `${ENDPOINT}/projects/${projectId!}/registrations`;\n}\n\nasync function getHeaders({\n  appConfig,\n  installations\n}: FirebaseInternalDependencies): Promise<Headers> {\n  const authToken = await installations.getToken();\n\n  return new Headers({\n    'Content-Type': 'application/json',\n    Accept: 'application/json',\n    'x-goog-api-key': appConfig.apiKey!,\n    'x-goog-firebase-installations-auth': `FIS ${authToken}`\n  });\n}\n\n/**\n * Hostname for the registering web client (e.g. `www.example.com`), or the app name\n * (`appNameFallback`) when the scope cannot be resolved (e.g. some test environments).\n */\nexport function getRegistrationOrigin(\n  swScope: string,\n  appNameFallback: string\n): string {\n  try {\n    if (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.test(swScope)) {\n      return new URL(swScope).host;\n    }\n  } catch {\n    // Fall through to relative-scope handling.\n  }\n  try {\n    if (typeof self !== 'undefined' && self.location?.href) {\n      return new URL(swScope, self.location.origin).host;\n    }\n  } catch {\n    // Fall through.\n  }\n  if (typeof self !== 'undefined' && self.location?.host) {\n    return self.location.host;\n  }\n  return appNameFallback;\n}\n\nfunction getBody(\n  { p256dh, auth, endpoint, vapidKey, swScope }: SubscriptionOptions,\n  appNameFallback: string,\n  includeSdkVersion: boolean\n): ApiRequestBody {\n  const body: ApiRequestBody = {\n    web: {\n      origin: getRegistrationOrigin(swScope, appNameFallback),\n      endpoint,\n      auth,\n      p256dh\n    }\n  };\n\n  if (includeSdkVersion) {\n    // eslint-disable-next-line camelcase\n    body.fcm_sdk_version = fcmSdkVersion;\n  }\n\n  if (vapidKey !== DEFAULT_VAPID_KEY) {\n    body.web.applicationPubKey = vapidKey;\n  }\n\n  return body;\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 {\n  SubscriptionOptions,\n  TokenDetails\n} from '../interfaces/registration-details';\nimport {\n  arrayToBase64,\n  base64ToArray\n} from '../helpers/array-base64-translator';\nimport {\n  dbGet,\n  dbGetFidRegistration,\n  dbRemove,\n  dbRemoveFidRegistration,\n  dbSet\n} from './idb-manager';\nimport {\n  requestDeleteRegistration,\n  requestDeleteToken,\n  requestGetToken,\n  requestUpdateToken\n} from './requests';\n\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { MessagingService } from '../messaging-service';\n\n// UpdateRegistration will be called once every week.\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport async function getTokenInternal(\n  messaging: MessagingService\n): Promise<string> {\n  const pushSubscription = await getPushSubscription(\n    messaging.swRegistration!,\n    messaging.vapidKey!\n  );\n\n  const subscriptionOptions: SubscriptionOptions = {\n    vapidKey: messaging.vapidKey!,\n    swScope: messaging.swRegistration!.scope,\n    endpoint: pushSubscription.endpoint,\n    auth: arrayToBase64(pushSubscription.getKey('auth')!),\n    p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n  };\n\n  const tokenDetails = await dbGet(messaging.firebaseDependencies);\n  if (!tokenDetails) {\n    // No token, get a new one.\n    return getNewToken(messaging.firebaseDependencies, subscriptionOptions);\n  } else if (\n    !isTokenValid(tokenDetails.subscriptionOptions!, subscriptionOptions)\n  ) {\n    // Invalid token, get a new one.\n    try {\n      await requestDeleteToken(\n        messaging.firebaseDependencies!,\n        tokenDetails.token\n      );\n    } catch (e) {\n      // Suppress errors because of #2364\n      console.warn(e);\n    }\n\n    return getNewToken(messaging.firebaseDependencies!, subscriptionOptions);\n  } else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\n    // Weekly token refresh\n    return updateToken(messaging, {\n      token: tokenDetails.token,\n      createTime: Date.now(),\n      subscriptionOptions\n    });\n  } else {\n    // Valid token, nothing to do.\n    return tokenDetails.token;\n  }\n}\n\n/**\n * Legacy getToken() path: there is a token row in IndexedDB. Revoke it with FCM, drop the row, and\n * clear any leftover FID registration metadata (apps may mix APIs).\n */\nasync function revokeLegacyFcmTokenAndClearCaches(\n  messaging: MessagingService,\n  tokenDetails: TokenDetails\n): Promise<void> {\n  await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);\n  await dbRemove(messaging.firebaseDependencies);\n  await removeFidRegistrationBestEffort(messaging.firebaseDependencies);\n}\n\n/**\n * No legacy token row: the client may only have FID-based registration (register() flow). If so,\n * delete that registration on the server, always scrub local FID metadata, then surface\n * onUnregistered when we actually had an FID.\n */\nasync function revokeFidRegistrationIfStored(\n  messaging: MessagingService\n): Promise<void> {\n  const stored = await dbGetFidRegistration(\n    messaging.firebaseDependencies\n  ).catch(() => undefined);\n  const fid = stored?.fid;\n\n  if (fid) {\n    await requestDeleteRegistration(messaging.firebaseDependencies, fid);\n  }\n\n  await removeFidRegistrationBestEffort(messaging.firebaseDependencies);\n\n  if (fid) {\n    notifyOnUnregistered(messaging, fid);\n  }\n}\n\n/**\n * Revokes the app's FCM registration: legacy token (getToken/deleteToken) and/or FID-based\n * registration (register/unregister), clears local caches, notifies onUnregistered when a stored\n * FID existed, then unsubscribes the push subscription when present.\n */\nexport async function revokeRegistrationInternal(\n  messaging: MessagingService\n): Promise<boolean> {\n  const tokenDetails = await dbGet(messaging.firebaseDependencies);\n  if (tokenDetails) {\n    await revokeLegacyFcmTokenAndClearCaches(messaging, tokenDetails);\n  } else {\n    await revokeFidRegistrationIfStored(messaging);\n  }\n\n  // Unsubscribe from the push subscription.\n  const pushSubscription =\n    await messaging.swRegistration!.pushManager.getSubscription();\n  if (pushSubscription) {\n    return pushSubscription.unsubscribe();\n  }\n\n  // If there's no SW, consider it a success.\n  return true;\n}\n\nasync function updateToken(\n  messaging: MessagingService,\n  tokenDetails: TokenDetails\n): Promise<string> {\n  try {\n    const updatedToken = await requestUpdateToken(\n      messaging.firebaseDependencies,\n      tokenDetails\n    );\n\n    const updatedTokenDetails: TokenDetails = {\n      ...tokenDetails,\n      token: updatedToken,\n      createTime: Date.now()\n    };\n\n    await dbSet(messaging.firebaseDependencies, updatedTokenDetails);\n    return updatedToken;\n  } catch (e) {\n    throw e;\n  }\n}\n\nasync function getNewToken(\n  firebaseDependencies: FirebaseInternalDependencies,\n  subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n  const token = await requestGetToken(\n    firebaseDependencies,\n    subscriptionOptions\n  );\n  const tokenDetails: TokenDetails = {\n    token,\n    createTime: Date.now(),\n    subscriptionOptions\n  };\n  await dbSet(firebaseDependencies, tokenDetails);\n  return tokenDetails.token;\n}\n\n/**\n * Gets a PushSubscription for the current user.\n */\nasync function getPushSubscription(\n  swRegistration: ServiceWorkerRegistration,\n  vapidKey: string\n): Promise<PushSubscription> {\n  const subscription = await swRegistration.pushManager.getSubscription();\n  if (subscription) {\n    return subscription;\n  }\n\n  return swRegistration.pushManager.subscribe({\n    userVisibleOnly: true,\n    // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\n    // submitted to pushManager#subscribe must be of type Uint8Array.\n    applicationServerKey: base64ToArray(vapidKey)\n  });\n}\n\n/**\n * Checks if the saved tokenDetails object matches the configuration provided.\n */\nfunction isTokenValid(\n  dbOptions: SubscriptionOptions,\n  currentOptions: SubscriptionOptions\n): boolean {\n  const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\n  const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\n  const isAuthEqual = currentOptions.auth === dbOptions.auth;\n  const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\n\n  return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\n}\n\n/** Clears FID registration metadata; apps may mix legacy getToken() with FID register/unregister. */\nasync function removeFidRegistrationBestEffort(\n  firebaseDependencies: FirebaseInternalDependencies\n): Promise<void> {\n  try {\n    await dbRemoveFidRegistration(firebaseDependencies);\n  } catch {\n    // Ignore.\n  }\n}\n\nexport function notifyOnRegistered(\n  messaging: MessagingService,\n  fid: string\n): void {\n  const handler = messaging.onRegisteredHandler;\n  if (!handler) {\n    return;\n  }\n  if (typeof handler === 'function') {\n    handler(fid);\n  } else {\n    handler.next(fid);\n  }\n}\n\nexport function notifyOnUnregistered(\n  messaging: MessagingService,\n  fid: string\n): void {\n  const handler = messaging.onUnregisteredHandler;\n  if (!handler) {\n    return;\n  }\n  if (typeof handler === 'function') {\n    handler(fid);\n  } else {\n    handler.next(fid);\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 {\n  DEFAULT_REGISTRATION_TIMEOUT,\n  DEFAULT_SW_PATH,\n  DEFAULT_SW_SCOPE\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function registerDefaultSw(\n  messaging: MessagingService\n): Promise<void> {\n  try {\n    messaging.swRegistration = await navigator.serviceWorker.register(\n      DEFAULT_SW_PATH,\n      {\n        scope: DEFAULT_SW_SCOPE\n      }\n    );\n\n    // The timing when browser updates sw when sw has an update is unreliable from experiment. It\n    // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\n    // is stuck with the old version. For example,\n    // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\n    // sw if there was an update.\n    messaging.swRegistration.update().catch(() => {\n      /* it is non blocking and we don't care if it failed */\n    });\n    await waitForRegistrationActive(messaging.swRegistration);\n  } catch (e) {\n    throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {\n      browserErrorMessage: (e as Error)?.message\n    });\n  }\n}\n\n/**\n * Waits for registration to become active. MDN documentation claims that\n * a service worker registration should be ready to use after awaiting\n * navigator.serviceWorker.register() but that doesn't seem to be the case in\n * practice, causing the SDK to throw errors when calling\n * swRegistration.pushManager.subscribe() too soon after register(). The only\n * solution seems to be waiting for the service worker registration `state`\n * to become \"active\".\n */\nasync function waitForRegistrationActive(\n  registration: ServiceWorkerRegistration\n): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    const rejectTimeout = setTimeout(\n      () =>\n        reject(\n          new Error(\n            `Service worker not registered after ${DEFAULT_REGISTRATION_TIMEOUT} ms`\n          )\n        ),\n      DEFAULT_REGISTRATION_TIMEOUT\n    );\n    const incomingSw = registration.installing || registration.waiting;\n    if (registration.active) {\n      clearTimeout(rejectTimeout);\n      resolve();\n    } else if (incomingSw) {\n      incomingSw.onstatechange = ev => {\n        if ((ev.target as ServiceWorker)?.state === 'activated') {\n          incomingSw.onstatechange = null;\n          clearTimeout(rejectTimeout);\n          resolve();\n        }\n      };\n    } else {\n      clearTimeout(rejectTimeout);\n      reject(new Error('No incoming service worker found.'));\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { registerDefaultSw } from './registerDefaultSw';\n\nexport async function updateSwReg(\n  messaging: MessagingService,\n  swRegistration?: ServiceWorkerRegistration | undefined\n): Promise<void> {\n  if (!swRegistration && !messaging.swRegistration) {\n    await registerDefaultSw(messaging);\n  }\n\n  if (!swRegistration && !!messaging.swRegistration) {\n    return;\n  }\n\n  if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n    throw ERROR_FACTORY.create(ErrorCode.INVALID_SW_REGISTRATION);\n  }\n\n  messaging.swRegistration = swRegistration;\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 { DEFAULT_VAPID_KEY } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\n\nexport async function updateVapidKey(\n  messaging: MessagingService,\n  vapidKey?: string | undefined\n): Promise<void> {\n  if (!!vapidKey) {\n    messaging.vapidKey = vapidKey;\n  } else if (!messaging.vapidKey) {\n    messaging.vapidKey = DEFAULT_VAPID_KEY;\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 { SubscriptionOptions } from '../interfaces/registration-details';\nimport { MessagingService } from '../messaging-service';\nimport {\n  base64ToArray,\n  arrayToBase64\n} from '../helpers/array-base64-translator';\nimport { requestCreateRegistration } from './requests';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\n/** Retries when CreateRegistration echoes an FID that does not match Installations.getId(). */\nconst FID_REGISTRATION_FID_MATCH_MAX_ATTEMPTS = 3;\n\n/**\n * For the new FID-based register path:\n * - Create (or refresh) an FCM Web registration in the backend via CreateRegistration.\n * - Use the FIS auth token produced by the installations instance (implicitly associated with FID).\n * - CreateRegistration must echo the installation in `name` (e.g.\n *   `projects/{projectId}/registrations/{fid}`); it must match `expectedFid` from\n *   Installations.getId(). On mismatch we refresh the auth token and retry, then fail with\n *   `fid-registration-failed`.\n */\nexport async function registerFcmRegistrationWithFid(\n  messaging: MessagingService,\n  expectedFid: string\n): Promise<void> {\n  const pushSubscription = await getPushSubscription(\n    messaging.swRegistration!,\n    messaging.vapidKey!\n  );\n\n  const subscriptionOptions: SubscriptionOptions = {\n    vapidKey: messaging.vapidKey!,\n    swScope: messaging.swRegistration!.scope,\n    endpoint: pushSubscription.endpoint,\n    auth: arrayToBase64(pushSubscription.getKey('auth')!),\n    p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n  };\n\n  const installations = messaging.firebaseDependencies.installations;\n\n  for (\n    let attempt = 0;\n    attempt < FID_REGISTRATION_FID_MATCH_MAX_ATTEMPTS;\n    attempt++\n  ) {\n    const { responseFid } = await requestCreateRegistration(\n      messaging.firebaseDependencies,\n      subscriptionOptions\n    );\n\n    if (responseFid === expectedFid) {\n      return;\n    }\n    // If CreateRegistration echoes an unexpected FID, the FIS auth token used for the request may\n    // be stale relative to the installation the backend associates with the call. Force-refresh\n    // the token before retrying so the next attempt uses credentials aligned with Installations.\n    if (attempt < FID_REGISTRATION_FID_MATCH_MAX_ATTEMPTS - 1) {\n      await installations.getToken(true);\n    }\n  }\n\n  throw ERROR_FACTORY.create(ErrorCode.FID_REGISTRATION_FAILED, {\n    errorInfo:\n      'CreateRegistration response FID does not match Firebase Installation ID'\n  });\n}\n\nasync function getPushSubscription(\n  swRegistration: ServiceWorkerRegistration,\n  vapidKey: string\n): Promise<PushSubscription> {\n  const subscription = await swRegistration.pushManager.getSubscription();\n  if (subscription) {\n    return subscription;\n  }\n\n  // Chrome/Firefox require applicationServerKey to be of type Uint8Array.\n  return swRegistration.pushManager.subscribe({\n    userVisibleOnly: true,\n    // `PushManager.subscribe` expects a `BufferSource`; `base64ToArray` produces a typed array.\n    // Cast to satisfy the lib typing differences across TS DOM versions.\n    applicationServerKey: base64ToArray(vapidKey) as unknown as BufferSource\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { MessagingService } from '../messaging-service';\nimport { updateSwReg } from '../helpers/updateSwReg';\nimport { updateVapidKey } from '../helpers/updateVapidKey';\nimport { RegisterOptions } from '../interfaces/public-types';\nimport { registerFcmRegistrationWithFid } from '../internals/register-fid';\nimport {\n  dbGetFidRegistration,\n  dbSetFidRegistration\n} from '../internals/idb-manager';\nimport { notifyOnRegistered } from '../internals/token-manager';\n\nconst FID_REGISTRATION_REFRESH_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\n/**\n * Registers the app instance with FCM using its Firebase Installation ID (FID). The FID is\n * delivered via the `onRegistered` callback. Call this to establish an FID-based identity.\n * Once `onRegistered` provides an FID, instruct your backend to remove any legacy token\n * previously associated with this instance. The backend send API supports FID as a target.\n *\n * When called multiple times, `onRegistered` is invoked on each call with the current FID.\n * Backend registration sync runs on first register, when the FID changes, or on weekly refresh.\n *\n * @param messaging - The MessagingService instance.\n * @param options - Optional. Same options as getToken (vapidKey, serviceWorkerRegistration).\n */\nexport async function register(\n  messaging: MessagingService,\n  options?: RegisterOptions\n): Promise<void> {\n  if (!navigator) {\n    throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n  }\n\n  if (Notification.permission === 'default') {\n    await Notification.requestPermission();\n  }\n\n  if (Notification.permission !== 'granted') {\n    throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n  }\n\n  if (!messaging.onRegisteredHandler) {\n    throw ERROR_FACTORY.create(ErrorCode.INVALID_ON_REGISTERED_HANDLER);\n  }\n\n  await updateVapidKey(messaging, options?.vapidKey);\n  await updateSwReg(messaging, options?.serviceWorkerRegistration);\n\n  // Keep the queue alive after a failed register() so future calls can retry.\n  const prev = messaging._registerNotifyChain.catch(() => {});\n  messaging._registerNotifyChain = prev.then(async () => {\n    const fid = await messaging.firebaseDependencies.installations.getId();\n\n    const stored = await dbGetFidRegistration(messaging.firebaseDependencies);\n    const now = Date.now();\n    const shouldRefresh =\n      !stored ||\n      stored.fid !== fid ||\n      now >= stored.lastRegisterTime + FID_REGISTRATION_REFRESH_MS;\n\n    if (shouldRefresh) {\n      await registerFcmRegistrationWithFid(messaging, fid);\n      await dbSetFidRegistration(messaging.firebaseDependencies, {\n        fid,\n        lastRegisterTime: now,\n        vapidKey: messaging.vapidKey\n      });\n    }\n\n    const handler = messaging.onRegisteredHandler;\n    if (!handler) {\n      throw ERROR_FACTORY.create(ErrorCode.INVALID_ON_REGISTERED_HANDLER);\n    }\n\n    notifyOnRegistered(messaging, fid);\n  });\n  return messaging._registerNotifyChain;\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 { MessagePayload } from '../interfaces/public-types';\nimport { MessagePayloadInternal } from '../interfaces/internal-message-payload';\n\nexport function externalizePayload(\n  internalPayload: MessagePayloadInternal\n): MessagePayload {\n  const payload: MessagePayload = {\n    from: internalPayload.from,\n    // eslint-disable-next-line camelcase\n    collapseKey: internalPayload.collapse_key,\n    // eslint-disable-next-line camelcase\n    messageId: internalPayload.fcmMessageId\n  } as MessagePayload;\n\n  propagateNotificationPayload(payload, internalPayload);\n  propagateDataPayload(payload, internalPayload);\n  propagateFcmOptions(payload, internalPayload);\n\n  return payload;\n}\n\nfunction propagateNotificationPayload(\n  payload: MessagePayload,\n  messagePayloadInternal: MessagePayloadInternal\n): void {\n  if (!messagePayloadInternal.notification) {\n    return;\n  }\n\n  payload.notification = {};\n\n  const title = messagePayloadInternal.notification!.title;\n  if (!!title) {\n    payload.notification!.title = title;\n  }\n\n  const body = messagePayloadInternal.notification!.body;\n  if (!!body) {\n    payload.notification!.body = body;\n  }\n\n  const image = messagePayloadInternal.notification!.image;\n  if (!!image) {\n    payload.notification!.image = image;\n  }\n\n  const icon = messagePayloadInternal.notification!.icon;\n  if (!!icon) {\n    payload.notification!.icon = icon;\n  }\n}\n\nfunction propagateDataPayload(\n  payload: MessagePayload,\n  messagePayloadInternal: MessagePayloadInternal\n): void {\n  if (!messagePayloadInternal.data) {\n    return;\n  }\n\n  payload.data = messagePayloadInternal.data as { [key: string]: string };\n}\n\nfunction propagateFcmOptions(\n  payload: MessagePayload,\n  messagePayloadInternal: MessagePayloadInternal\n): void {\n  // fcmOptions.link value is written into notification.click_action. see more in b/232072111\n  if (\n    !messagePayloadInternal.fcmOptions &&\n    !messagePayloadInternal.notification?.click_action\n  ) {\n    return;\n  }\n\n  payload.fcmOptions = {};\n\n  const link =\n    messagePayloadInternal.fcmOptions?.link ??\n    messagePayloadInternal.notification?.click_action;\n\n  if (!!link) {\n    payload.fcmOptions!.link = link;\n  }\n\n  // eslint-disable-next-line camelcase\n  const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;\n  if (!!analyticsLabel) {\n    payload.fcmOptions!.analyticsLabel = analyticsLabel;\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { FirebaseApp, FirebaseOptions } from '@firebase/app';\n\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseError } from '@firebase/util';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n  if (!app || !app.options) {\n    throw getMissingValueError('App Configuration Object');\n  }\n\n  if (!app.name) {\n    throw getMissingValueError('App Name');\n  }\n\n  // Required app config keys\n  const configKeys: ReadonlyArray<keyof FirebaseOptions> = [\n    'projectId',\n    'apiKey',\n    'appId',\n    'messagingSenderId'\n  ];\n\n  const { options } = app;\n  for (const keyName of configKeys) {\n    if (!options[keyName]) {\n      throw getMissingValueError(keyName);\n    }\n  }\n\n  return {\n    appName: app.name,\n    projectId: options.projectId!,\n    apiKey: options.apiKey!,\n    appId: options.appId!,\n    senderId: options.messagingSenderId!\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 { FirebaseApp, _FirebaseService } from '@firebase/app';\nimport { MessagePayload, NextFn, Observer } from './interfaces/public-types';\n\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { FirebaseInternalDependencies } from './interfaces/internal-dependencies';\nimport { LogEvent } from './interfaces/logging-types';\nimport { Provider } from '@firebase/component';\nimport {\n  _FirebaseInstallationsInternal,\n  IdChangeUnsubscribeFn\n} from '@firebase/installations';\nimport { extractAppConfig } from './helpers/extract-app-config';\n\nexport class MessagingService implements _FirebaseService {\n  readonly app!: FirebaseApp;\n  readonly firebaseDependencies!: FirebaseInternalDependencies;\n\n  swRegistration?: ServiceWorkerRegistration;\n  vapidKey?: string;\n  // logging is only done with end user consent. Default to false.\n  deliveryMetricsExportedToBigQueryEnabled: boolean = false;\n\n  onBackgroundMessageHandler:\n    | NextFn<MessagePayload>\n    | Observer<MessagePayload>\n    | null = null;\n\n  onMessageHandler: NextFn<MessagePayload> | Observer<MessagePayload> | null =\n    null;\n\n  /** Observer for the event that the app instance is registered with FCM via Firebase Installation ID (FID). */\n  onRegisteredHandler: NextFn<string> | Observer<string> | null = null;\n\n  /** Observer for the event that the app instance is unregistered from FCM (FID no longer active). */\n  onUnregisteredHandler: NextFn<string> | Observer<string> | null = null;\n\n  /**\n   * Serializes the FID get + compare + notify step so concurrent register() calls\n   * do not race each other.\n   */\n  _registerNotifyChain: Promise<void> = Promise.resolve();\n\n  /** Unsubscribe from Installations `onIdChange` when messaging is deleted. */\n  _fidChangeUnsubscribe: IdChangeUnsubscribeFn | null = null;\n\n  logEvents: LogEvent[] = [];\n  /**\n   * Single source of truth for the logging loop lifecycle.\n   *\n   * `scheduled` holds the active timer id; `flushing` indicates an async dispatch\n   * is in progress (prevents duplicate starts); `stopped` means idle.\n   */\n  logQueue: LogQueueState = { state: 'stopped' };\n\n  constructor(\n    app: FirebaseApp,\n    installations: _FirebaseInstallationsInternal,\n    analyticsProvider: Provider<FirebaseAnalyticsInternalName>\n  ) {\n    const appConfig = extractAppConfig(app);\n    this.firebaseDependencies = {\n      app,\n      appConfig,\n      installations,\n      analyticsProvider\n    };\n  }\n\n  _delete(): Promise<void> {\n    if (this._fidChangeUnsubscribe) {\n      this._fidChangeUnsubscribe();\n      this._fidChangeUnsubscribe = null;\n    }\n    if (this.logQueue.state === 'scheduled') {\n      clearTimeout(this.logQueue.timerId);\n    }\n    this.logQueue = { state: 'stopped' };\n    return Promise.resolve();\n  }\n}\n\nexport type LogQueueState =\n  | { state: 'stopped' }\n  | { state: 'scheduled'; timerId: ReturnType<typeof setTimeout> }\n  | { state: 'flushing' };\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { getTokenInternal } from '../internals/token-manager';\nimport { updateSwReg } from '../helpers/updateSwReg';\nimport { updateVapidKey } from '../helpers/updateVapidKey';\nimport { GetTokenOptions } from '../interfaces/public-types';\n\nexport async function getToken(\n  messaging: MessagingService,\n  options?: GetTokenOptions\n): Promise<string> {\n  if (!navigator) {\n    throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n  }\n\n  if (Notification.permission === 'default') {\n    await Notification.requestPermission();\n  }\n\n  if (Notification.permission !== 'granted') {\n    throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n  }\n\n  await updateVapidKey(messaging, options?.vapidKey);\n  await updateSwReg(messaging, options?.serviceWorkerRegistration);\n\n  return getTokenInternal(messaging);\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 {\n  CONSOLE_CAMPAIGN_ID,\n  CONSOLE_CAMPAIGN_NAME,\n  CONSOLE_CAMPAIGN_TIME\n} from '../util/constants';\nimport {\n  ConsoleMessageData,\n  MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { MessagingService } from '../messaging-service';\n\nexport async function logToScion(\n  messaging: MessagingService,\n  messageType: MessageType,\n  data: ConsoleMessageData\n): Promise<void> {\n  const eventType = getEventType(messageType);\n  const analytics =\n    await messaging.firebaseDependencies.analyticsProvider.get();\n  analytics.logEvent(eventType, {\n    /* eslint-disable camelcase */\n    message_id: data[CONSOLE_CAMPAIGN_ID],\n    message_name: data[CONSOLE_CAMPAIGN_NAME],\n    message_time: data[CONSOLE_CAMPAIGN_TIME],\n    message_device_time: Math.floor(Date.now() / 1000)\n    /* eslint-enable camelcase */\n  });\n}\n\nfunction getEventType(messageType: MessageType): string {\n  switch (messageType) {\n    case MessageType.NOTIFICATION_CLICKED:\n      return 'notification_open';\n    case MessageType.PUSH_RECEIVED:\n      return 'notification_foreground';\n    default:\n      throw new Error();\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 {\n  FidRegisteredPayload,\n  MessagePayloadInternal,\n  MessageType\n} from '../interfaces/internal-message-payload';\n\nimport { CONSOLE_CAMPAIGN_ANALYTICS_ENABLED } from '../util/constants';\nimport { MessagingService } from '../messaging-service';\nimport { externalizePayload } from '../helpers/externalizePayload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { logToScion } from '../helpers/logToScion';\n\nexport async function messageEventListener(\n  messaging: MessagingService,\n  event: MessageEvent\n): Promise<void> {\n  const internalPayload = event.data as MessagePayloadInternal;\n\n  if (!internalPayload.isFirebaseMessaging) {\n    return;\n  }\n\n  if (\n    messaging.onMessageHandler &&\n    internalPayload.messageType === MessageType.PUSH_RECEIVED\n  ) {\n    if (typeof messaging.onMessageHandler === 'function') {\n      messaging.onMessageHandler(externalizePayload(internalPayload));\n    } else {\n      messaging.onMessageHandler.next(externalizePayload(internalPayload));\n    }\n  }\n\n  if (\n    messaging.onRegisteredHandler &&\n    internalPayload.messageType === MessageType.FID_REGISTERED\n  ) {\n    const fid = (internalPayload as unknown as FidRegisteredPayload).fid;\n    if (typeof messaging.onRegisteredHandler === 'function') {\n      messaging.onRegisteredHandler(fid);\n    } else {\n      messaging.onRegisteredHandler.next(fid);\n    }\n  }\n\n  // Log to Scion if applicable\n  const dataPayload = internalPayload.data;\n  if (\n    isConsoleMessage(dataPayload) &&\n    dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1'\n  ) {\n    await logToScion(messaging, internalPayload.messageType!, dataPayload);\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 { CONSOLE_CAMPAIGN_ID } from '../util/constants';\nimport { ConsoleMessageData } from '../interfaces/internal-message-payload';\n\nexport function isConsoleMessage(data: unknown): data is ConsoleMessageData {\n  // This message has a campaign ID, meaning it was sent using the Firebase Console.\n  return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\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  Component,\n  ComponentContainer,\n  ComponentType,\n  InstanceFactory\n} from '@firebase/component';\nimport {\n  onNotificationClick,\n  onPush,\n  onSubChange\n} from '../listeners/sw-listeners';\n\nimport { GetTokenOptions, RegisterOptions } from '../interfaces/public-types';\nimport { MessagingInternal } from '@firebase/messaging-interop-types';\nimport { MessagingService } from '../messaging-service';\nimport { ServiceWorkerGlobalScope } from '../util/sw-types';\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport { getToken } from '../api/getToken';\nimport { register } from '../api/register';\nimport { subscribeFidChangeRegistration } from './fid-change-registration';\nimport { messageEventListener } from '../listeners/window-listener';\n\nimport { name, version } from '../../package.json';\n\nconst WindowMessagingFactory: InstanceFactory<'messaging'> = (\n  container: ComponentContainer\n) => {\n  const messaging = new MessagingService(\n    container.getProvider('app').getImmediate(),\n    container.getProvider('installations-internal').getImmediate(),\n    container.getProvider('analytics-internal')\n  );\n\n  navigator.serviceWorker.addEventListener('message', e =>\n    messageEventListener(messaging as MessagingService, e)\n  );\n\n  messaging._fidChangeUnsubscribe = subscribeFidChangeRegistration(\n    messaging as MessagingService,\n    container.getProvider('installations').getImmediate()\n  );\n\n  return messaging;\n};\n\nconst WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (\n  container: ComponentContainer\n) => {\n  const messaging = container\n    .getProvider('messaging')\n    .getImmediate() as MessagingService;\n\n  const messagingInternal: MessagingInternal = {\n    getToken: (options?: GetTokenOptions) => getToken(messaging, options),\n    register: (options?: RegisterOptions) => register(messaging, options)\n  };\n\n  return messagingInternal;\n};\n\ndeclare const self: ServiceWorkerGlobalScope;\nconst SwMessagingFactory: InstanceFactory<'messaging'> = (\n  container: ComponentContainer\n) => {\n  const messaging = new MessagingService(\n    container.getProvider('app').getImmediate(),\n    container.getProvider('installations-internal').getImmediate(),\n    container.getProvider('analytics-internal')\n  );\n\n  self.addEventListener('push', e => {\n    e.waitUntil(onPush(e, messaging as MessagingService));\n  });\n  self.addEventListener('pushsubscriptionchange', e => {\n    e.waitUntil(onSubChange(e, messaging as MessagingService));\n  });\n  self.addEventListener('notificationclick', e => {\n    e.waitUntil(onNotificationClick(e));\n  });\n\n  return messaging;\n};\n\nexport function registerMessagingInWindow(): void {\n  _registerComponent(\n    new Component('messaging', WindowMessagingFactory, ComponentType.PUBLIC)\n  );\n\n  _registerComponent(\n    new Component(\n      'messaging-internal',\n      WindowMessagingInternalFactory,\n      ComponentType.PRIVATE\n    )\n  );\n\n  registerVersion(name, version);\n  // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n  registerVersion(name, version, '__BUILD_TARGET__');\n}\n\n/**\n * The messaging instance registered in sw is named differently than that of in client. This is\n * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in\n * `messaging-compat` and component with the same name can only be registered once.\n */\nexport function registerMessagingInSw(): void {\n  _registerComponent(\n    new Component('messaging-sw', SwMessagingFactory, ComponentType.PUBLIC)\n  );\n}\n","/**\n * @license\n * Copyright 2026 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  IdChangeUnsubscribeFn,\n  Installations,\n  onIdChange\n} from '@firebase/installations';\nimport { register } from '../api/register';\nimport {\n  dbGetFidRegistration,\n  dbSetFidRegistration\n} from '../internals/idb-manager';\nimport { registerFcmRegistrationWithFid } from '../internals/register-fid';\nimport { notifyOnRegistered } from '../internals/token-manager';\nimport { MessagingService } from '../messaging-service';\nimport { updateVapidKey } from './updateVapidKey';\n\n/**\n * Re-runs FCM FID registration when push subscription keys change (e.g. `pushsubscriptionchange`\n * in the service worker). No-op if the app instance was never registered via `register()`.\n * Best-effort: callers should catch failures when permission or push may be unavailable.\n */\nexport async function refreshFidRegistrationIfStored(\n  messaging: MessagingService\n): Promise<string | undefined> {\n  const stored = await dbGetFidRegistration(\n    messaging.firebaseDependencies\n  ).catch(() => undefined);\n  if (!stored) {\n    return undefined;\n  }\n\n  await updateVapidKey(messaging, stored.vapidKey);\n\n  const fid = await messaging.firebaseDependencies.installations.getId();\n  await registerFcmRegistrationWithFid(messaging, fid);\n  await dbSetFidRegistration(messaging.firebaseDependencies, {\n    fid,\n    lastRegisterTime: Date.now(),\n    vapidKey: messaging.vapidKey\n  });\n  notifyOnRegistered(messaging, fid);\n  return fid;\n}\n\n/**\n * When the Firebase Installation ID changes, re-run `register()` so FCM registration and\n * onRegistered run for the new FID. No-op if no onRegistered handler is set or the app\n * instance was never registered with FCM.\n */\nexport function subscribeFidChangeRegistration(\n  messaging: MessagingService,\n  installations: Installations\n): IdChangeUnsubscribeFn {\n  return onIdChange(installations, () => {\n    void (async () => {\n      if (!messaging.onRegisteredHandler) {\n        return;\n      }\n      const stored = await dbGetFidRegistration(messaging.firebaseDependencies);\n      if (!stored) {\n        return;\n      }\n      await register(messaging).catch(() => {\n        // Best-effort: permission may be revoked or SW unavailable after FID rotation.\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 {\n  areCookiesEnabled,\n  isIndexedDBAvailable,\n  validateIndexedDBOpenable\n} from '@firebase/util';\n\n/**\n * Checks if all required APIs exist in the browser.\n * @returns a Promise that resolves to a boolean.\n *\n * @public\n */\nexport async function isWindowSupported(): Promise<boolean> {\n  try {\n    // This throws if open() is unsupported, so adding it to the conditional\n    // statement below can cause an uncaught error.\n    await validateIndexedDBOpenable();\n  } catch (e) {\n    return false;\n  }\n  // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\n  // might be prohibited to run. In these contexts, an error would be thrown during the messaging\n  // instantiating phase, informing the developers to import/call isSupported for special handling.\n  return (\n    typeof window !== 'undefined' &&\n    isIndexedDBAvailable() &&\n    areCookiesEnabled() &&\n    'serviceWorker' in navigator &&\n    'PushManager' in window &&\n    'Notification' in window &&\n    'fetch' in window &&\n    ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n    PushSubscription.prototype.hasOwnProperty('getKey')\n  );\n}\n\n/**\n * Checks whether all required APIs exist within SW Context\n * @returns a Promise that resolves to a boolean.\n *\n * @public\n */\nexport async function isSwSupported(): Promise<boolean> {\n  // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing\n  // might be prohibited to run. In these contexts, an error would be thrown during the messaging\n  // instantiating phase, informing the developers to import/call isSupported for special handling.\n  return (\n    isIndexedDBAvailable() &&\n    (await validateIndexedDBOpenable()) &&\n    'PushManager' in self &&\n    'Notification' in self &&\n    ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n    PushSubscription.prototype.hasOwnProperty('getKey')\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\nimport { ERROR_FACTORY, ErrorCode } from './util/errors';\nimport { FirebaseApp, _getProvider, getApp } from '@firebase/app';\nimport {\n  GetTokenOptions,\n  MessagePayload,\n  Messaging,\n  RegisterOptions\n} from './interfaces/public-types';\nimport {\n  NextFn,\n  Observer,\n  Unsubscribe,\n  getModularInstance\n} from '@firebase/util';\nimport { isSwSupported, isWindowSupported } from './api/isSupported';\n\nimport { MessagingService } from './messaging-service';\nimport { deleteToken as _deleteToken } from './api/deleteToken';\nimport { getToken as _getToken } from './api/getToken';\nimport { onBackgroundMessage as _onBackgroundMessage } from './api/onBackgroundMessage';\nimport { onMessage as _onMessage } from './api/onMessage';\nimport { onRegistered as _onRegistered } from './api/onRegistered';\nimport { onUnregistered as _onUnregistered } from './api/onUnregistered';\nimport { register as _register } from './api/register';\nimport { unregister as _unregister } from './api/unregister';\nimport { _setDeliveryMetricsExportedToBigQueryEnabled } from './api/setDeliveryMetricsExportedToBigQueryEnabled';\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInWindow(app: FirebaseApp = getApp()): Messaging {\n  // Conscious decision to make this async check non-blocking during the messaging instance\n  // initialization phase for performance consideration. An error would be thrown latter for\n  // developer's information. Developers can then choose to import and call `isSupported` for\n  // special handling.\n  isWindowSupported().then(\n    isSupported => {\n      // If `isWindowSupported()` resolved, but returned false.\n      if (!isSupported) {\n        throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n      }\n    },\n    _ => {\n      // If `isWindowSupported()` rejected.\n      throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n    }\n  );\n  return _getProvider(getModularInstance(app), 'messaging').getImmediate();\n}\n\n/**\n * Retrieves a Firebase Cloud Messaging instance.\n *\n * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.\n *\n * @public\n */\nexport function getMessagingInSw(app: FirebaseApp = getApp()): Messaging {\n  // Conscious decision to make this async check non-blocking during the messaging instance\n  // initialization phase for performance consideration. An error would be thrown latter for\n  // developer's information. Developers can then choose to import and call `isSupported` for\n  // special handling.\n  isSwSupported().then(\n    isSupported => {\n      // If `isSwSupported()` resolved, but returned false.\n      if (!isSupported) {\n        throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n      }\n    },\n    _ => {\n      // If `isSwSupported()` rejected.\n      throw ERROR_FACTORY.create(ErrorCode.INDEXED_DB_UNSUPPORTED);\n    }\n  );\n  return _getProvider(getModularInstance(app), 'messaging-sw').getImmediate();\n}\n\n/**\n * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud\n * Messaging registration token that can be used to send push messages to that {@link Messaging}\n * instance.\n *\n * If notification permission isn't already granted, this method asks the user for permission. The\n * returned promise rejects if the user does not allow the app to show notifications.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param options - Provides an optional vapid key and an optional service worker registration.\n *\n * @returns The promise resolves with an FCM registration token.\n *\n * @deprecated Use {@link register} together with {@link onRegistered} for Firebase\n * Installation ID-based messaging instead of retrieving an FCM registration token with this API.\n *\n * @public\n */\nexport async function getToken(\n  messaging: Messaging,\n  options?: GetTokenOptions\n): Promise<string> {\n  messaging = getModularInstance(messaging);\n  return _getToken(messaging as MessagingService, options);\n}\n\n/**\n * Deletes the registration token associated with this {@link Messaging} instance and unsubscribes\n * the {@link Messaging} instance from the push subscription.\n *\n * If there is no legacy registration token but the client has FID-based registration metadata\n * (from {@link register}), this deletes that registration on the server, clears local metadata, and\n * invokes {@link onUnregistered} with the removed FID when successful.\n *\n * @param messaging - The {@link Messaging} instance.\n *\n * @returns The promise resolves when the token has been successfully deleted.\n *\n * @deprecated Use {@link onUnregistered} to observe when the client is no longer\n * registered and update your backend accordingly, instead of explicitly deleting the\n * registration token with this API.\n *\n * @public\n */\nexport function deleteToken(messaging: Messaging): Promise<boolean> {\n  messaging = getModularInstance(messaging);\n  return _deleteToken(messaging as MessagingService);\n}\n\n/**\n * When a push message is received and the user is currently on a page for your origin, the\n * message is passed to the page and an `onMessage()` event is dispatched with the payload of\n * the push message.\n *\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined,\n *     is called when a message is received and the user is currently viewing your page.\n * @returns To stop listening for messages execute this returned function.\n *\n * @public\n */\nexport function onMessage(\n  messaging: Messaging,\n  nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n  messaging = getModularInstance(messaging);\n  return _onMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Called when a message is received while the app is in the background. An app is considered to be\n * in the background if no active window is displayed.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - This function, or observer object with `next` defined, is called when a\n * message is received and the app is currently in the background.\n *\n * @returns To stop listening for messages execute this returned function.\n *\n * @public\n */\nexport function onBackgroundMessage(\n  messaging: Messaging,\n  nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n  messaging = getModularInstance(messaging);\n  return _onBackgroundMessage(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Registers the app instance with FCM using its Firebase Installation ID (FID). The FID is\n * delivered via the {@link onRegistered} callback, not as a return value. Call this to establish\n * an FID-based identity; once {@link onRegistered} provides an FID, instruct your backend to\n * remove any legacy token previously associated with this instance. The backend send API\n * supports FID as a target.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param options - Optional. VAPID key and/or service worker registration (same as getToken).\n * @returns Promise that resolves when registration has been initiated; FID is delivered via onRegistered.\n *\n * @public\n */\nexport async function register(\n  messaging: Messaging,\n  options?: RegisterOptions\n): Promise<void> {\n  messaging = getModularInstance(messaging);\n  return _register(messaging as MessagingService, options);\n}\n\n/**\n * Unregisters the app instance from FCM by deleting its FID-based registration.\n * On success, triggers {@link onUnregistered} (if registered) with the unregistered FID.\n *\n * @param messaging - The {@link Messaging} instance.\n *\n * @public\n */\nexport async function unregister(messaging: Messaging): Promise<void> {\n  messaging = getModularInstance(messaging);\n  return _unregister(messaging as MessagingService);\n}\n\n/**\n * Subscribes to an event that the app instance is registered with FCM via Firebase Installation ID (FID).\n * Use the FID passed to the callback to upload it to your application server. When you receive an FID\n * after calling {@link register}, instruct your backend to remove any legacy token for this instance.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - A function or observer object called when an FID is registered.\n * @returns Unsubscribe function to stop listening.\n *\n * @public\n */\nexport function onRegistered(\n  messaging: Messaging,\n  nextOrObserver: NextFn<string> | Observer<string>\n): Unsubscribe {\n  messaging = getModularInstance(messaging);\n  return _onRegistered(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Subscribes to an event that the app instance is unregistered from FCM (FID no longer active).\n * Use this to notify your backend to remove this FID to prevent 404 errors on send.\n *\n * @param messaging - The {@link Messaging} instance.\n * @param nextOrObserver - A function or observer object called with the unregistered FID.\n * @returns Unsubscribe function to stop listening.\n *\n * @public\n */\nexport function onUnregistered(\n  messaging: Messaging,\n  nextOrObserver: NextFn<string> | Observer<string>\n): Unsubscribe {\n  messaging = getModularInstance(messaging);\n  return _onUnregistered(messaging as MessagingService, nextOrObserver);\n}\n\n/**\n * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By\n * default, message delivery metrics are not exported to BigQuery. Use this method to enable or\n * disable the export at runtime.\n *\n * @param messaging - The `FirebaseMessaging` instance.\n * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to\n * BigQuery.\n *\n * @public\n */\nexport function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(\n  messaging: Messaging,\n  enable: boolean\n): void {\n  messaging = getModularInstance(messaging);\n  return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport { MessagingService } from '../messaging-service';\nimport { revokeRegistrationInternal } from '../internals/token-manager';\nimport { registerDefaultSw } from '../helpers/registerDefaultSw';\n\nexport async function deleteToken(\n  messaging: MessagingService\n): Promise<boolean> {\n  if (!navigator) {\n    throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n  }\n\n  if (!messaging.swRegistration) {\n    await registerDefaultSw(messaging);\n  }\n\n  return revokeRegistrationInternal(messaging);\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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nimport {\n  MessagePayload,\n  NextFn,\n  Observer,\n  Unsubscribe\n} from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\nexport function onMessage(\n  messaging: MessagingService,\n  nextOrObserver: NextFn<MessagePayload> | Observer<MessagePayload>\n): Unsubscribe {\n  if (!navigator) {\n    throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n  }\n\n  messaging.onMessageHandler = nextOrObserver;\n\n  return () => {\n    messaging.onMessageHandler = null;\n  };\n}\n","/**\n * @license\n * Copyright 2026 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 { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { MessagingService } from '../messaging-service';\nimport {\n  dbRemove,\n  dbGetFidRegistration,\n  dbRemoveFidRegistration\n} from '../internals/idb-manager';\nimport { requestDeleteRegistration } from '../internals/requests';\n\n/**\n * Unregisters the app instance from FCM by deleting its FID-based registration.\n *\n * On success, triggers the `onUnregistered` callback (if set) with the unregistered FID.\n *\n * @param messaging - The MessagingService instance.\n */\nexport async function unregister(messaging: MessagingService): Promise<void> {\n  if (!navigator) {\n    throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n  }\n\n  // Prefer the last successfully registered FID from local metadata when available.\n  const stored = await dbGetFidRegistration(\n    messaging.firebaseDependencies\n  ).catch(() => undefined);\n  const fid =\n    stored?.fid ?? (await messaging.firebaseDependencies.installations.getId());\n\n  await requestDeleteRegistration(messaging.firebaseDependencies, fid);\n\n  // Best-effort local cleanup; still resolve even if schema is unavailable.\n  try {\n    await dbRemoveFidRegistration(messaging.firebaseDependencies);\n  } catch {\n    // Ignore.\n  }\n\n  // Best-effort cleanup of legacy token details created via getToken().\n  try {\n    await dbRemove(messaging.firebaseDependencies);\n  } catch {\n    // Ignore.\n  }\n\n  const handler = messaging.onUnregisteredHandler;\n  if (!handler) {\n    return;\n  }\n\n  if (typeof handler === 'function') {\n    handler(fid);\n  } else {\n    handler.next(fid);\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 { NextFn, Observer, Unsubscribe } from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\n/**\n * Subscribes to an event that the app instance is registered with FCM via Firebase Installation ID (FID).\n * Use the FID passed to the callback to upload it to your application server.\n *\n * @param messaging - The {@link MessagingService} instance.\n * @param nextOrObserver - A function or observer object called when an FID is registered.\n * @returns Unsubscribe function to stop listening.\n */\nexport function onRegistered(\n  messaging: MessagingService,\n  nextOrObserver: NextFn<string> | Observer<string>\n): Unsubscribe {\n  messaging.onRegisteredHandler = nextOrObserver;\n\n  return () => {\n    if (messaging.onRegisteredHandler === nextOrObserver) {\n      messaging.onRegisteredHandler = null;\n    }\n  };\n}\n","/**\n * @license\n * Copyright 2026 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 { NextFn, Observer, Unsubscribe } from '../interfaces/public-types';\nimport { MessagingService } from '../messaging-service';\n\n/**\n * Subscribes to an event that the app instance is unregistered from FCM so the FID is no longer active.\n * Use this to notify your backend to remove this FID to prevent 404 errors on send.\n *\n * @param messaging - The {@link MessagingService} instance.\n * @param nextOrObserver - A function or observer object called with the unregistered FID.\n * @returns Unsubscribe function to stop listening.\n */\nexport function onUnregistered(\n  messaging: MessagingService,\n  nextOrObserver: NextFn<string> | Observer<string>\n): Unsubscribe {\n  messaging.onUnregisteredHandler = nextOrObserver;\n\n  return () => {\n    if (messaging.onUnregisteredHandler === nextOrObserver) {\n      messaging.onUnregisteredHandler = null;\n    }\n  };\n}\n","/**\n * The Firebase Cloud Messaging Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\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 '@firebase/installations';\n\nimport { Messaging } from './interfaces/public-types';\nimport { registerMessagingInWindow } from './helpers/register';\n\nexport {\n  getToken,\n  deleteToken,\n  register,\n  unregister,\n  onMessage,\n  onRegistered,\n  onUnregistered,\n  getMessagingInWindow as getMessaging\n} from './api';\nexport { isWindowSupported as isSupported } from './api/isSupported';\nexport * from './interfaces/public-types';\n\ndeclare module '@firebase/component' {\n  interface NameServiceMapping {\n    'messaging': Messaging;\n  }\n}\n\nregisterMessagingInWindow();\n"],"names":["FirebaseError","Error","constructor","code","message","customData","super","this","name","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","ptr","result","length","start","indexOf","substring","end","key","value","String","e","fullMessage","getModularInstance","_delegate","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","get","target","prop","receiver","IDBTransaction","objectStoreNames","undefined","objectStore","wrap","set","has","wrapFunction","func","IDBDatabase","transaction","getCursorAdvanceMethods","IDBCursor","advance","continue","continuePrimaryKey","includes","args","apply","unwrap","storeNames","tx","call","sort","transformCachableValue","cacheDonePromiseForTransaction","done","Promise","resolve","reject","unlisten","removeEventListener","complete","error","DOMException","addEventListener","object","getIdbProxyableTypes","IDBObjectStore","IDBIndex","some","c","Proxy","IDBRequest","promisifyRequest","request","promise","success","then","catch","newValue","openDB","version","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","deleteDB","deleteDatabase","readMethods","writeMethods","cachedMethods","Map","getMethod","targetFuncName","replace","useIndex","isWrite","method","async","storeName","store","index","shift","all","replaceTraps","oldTraps","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","TOKEN_EXPIRATION_BUFFER","ERROR_FACTORY","isServerError","getInstallationsEndpoint","projectId","extractAuthTokenInfoFromResponse","response","token","requestStatus","expiresIn","responseExpiresIn","Number","creationTime","Date","now","getErrorFromResponse","requestName","errorData","json","serverCode","serverMessage","serverStatus","status","getHeaders","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","fn","sleep","ms","setTimeout","VALID_FID_PATTERN","generateFid","fidByteArray","Uint8Array","self","crypto","msCrypto","getRandomValues","fid","encode","b64String","bufferToBase64UrlSafe","array","btoa","fromCharCode","substr","test","getKey","appName","appId","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","broadcastFidChange","channel","getBroadcastChannel","postMessage","closeBroadcastChannel","callbacks","broadcastChannel","BroadcastChannel","onmessage","size","close","OBJECT_STORE_NAME","dbPromise","getDbPromise","createObjectStore","oldValue","put","remove","delete","update","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","updateOrCreateInstallationEntry","entry","registrationStatus","clearTimedOutRequest","entryWithPromise","triggerRegistrationIfNecessary","navigator","onLine","inProgressEntry","registrationTime","registerInstallation","registeredInstallationEntry","createInstallationRequest","heartbeatServiceProvider","endpoint","heartbeatService","getImmediate","optional","heartbeatsHeader","getHeartbeatsHeader","body","authVersion","sdkVersion","JSON","stringify","fetch","ok","responseValue","authToken","waitUntilFidRegistration","updateInstallationRequest","hasInstallationRequestTimedOut","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","refreshAuthToken","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenValid","isAuthTokenExpired","waitUntilAuthTokenRequest","updateAuthTokenRequest","makeAuthTokenRequestInProgressEntry","inProgressAuthToken","requestTime","fetchAuthTokenFromServer","updatedInstallationEntry","hasAuthTokenRequestTimedOut","getToken","installationsImpl","completeInstallationRegistration","onIdChange","addCallback","callbackSet","Set","add","removeCallback","getMissingValueError","valueName","INSTALLATIONS_NAME","publicFactory","container","app","getProvider","extractAppConfig","options","configKeys","keyName","_getProvider","_delete","internalFactory","getId","console","registerInstallations","_registerComponent","registerVersion","DEFAULT_VAPID_KEY","CONSOLE_CAMPAIGN_ID","DEFAULT_REGISTRATION_TIMEOUT","MessageType","arrayToBase64","uint8Array","base64ToArray","base64String","base64","repeat","rawData","atob","outputArray","i","charCodeAt","OLD_DB_NAME","OLD_OBJECT_STORE_NAME","DATABASE_NAME","TOKEN_OBJECT_STORE_NAME","FID_REGISTRATION_OBJECT_STORE_NAME","idbImpl","createOpenDbOptions","targetSchemaVersion","upgradeDb","migrateMessagingDb","_currentVersion","_blockedVersion","openLatest","DATABASE_VERSION","hasObjectStore","contains","assertFidRegistrationObjectStore","dbGet","firebaseDependencies","tokenDetails","oldTokenDetails","migrateOldDatabase","senderId","dbNames","databases","map","upgradeTransaction","clear","oldDetails","auth","p256dh","fcmToken","createTime","subscriptionOptions","swScope","vapidKey","checkTokenDetails","dbSet","stores","hasFidStore","push","dbRemove","dbGetFidRegistration","dbRemoveFidRegistration","requestCreateRegistration","getBody","subscribeOptions","responseData","fetchWithExponentialRetry","operation","maxAttempts","baseBackoffMs","lastError","attempt","err","delayMs","Math","pow","getEndpoint","errorInfo","toString","responseFid","parseCreateRegistrationSuccessFid","text","trim","parse","parseFidFromRegistrationResourceName","segmentIndex","REGISTRATIONS_NAME_SEGMENT","slice","statusText","requestDeleteRegistration","requestDeleteToken","unsubscribeOptions","getRegistrationOrigin","appNameFallback","URL","host","location","href","origin","includeSdkVersion","web","fcm_sdk_version","fcmSdkVersion","applicationPubKey","getTokenInternal","messaging","pushSubscription","getPushSubscription","swRegistration","subscription","pushManager","getSubscription","subscribe","userVisibleOnly","applicationServerKey","scope","isTokenValid","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","updateToken","updatedToken","requestUpdateToken","updateOptions","updatedTokenDetails","warn","getNewToken","revokeRegistrationInternal","revokeLegacyFcmTokenAndClearCaches","removeFidRegistrationBestEffort","revokeFidRegistrationIfStored","stored","notifyOnUnregistered","handler","onUnregisteredHandler","next","unsubscribe","requestGetToken","registerDefaultSw","serviceWorker","register","waitForRegistrationActive","registration","rejectTimeout","incomingSw","installing","waiting","active","clearTimeout","onstatechange","ev","state","browserErrorMessage","updateSwReg","ServiceWorkerRegistration","updateVapidKey","registerFcmRegistrationWithFid","expectedFid","FID_REGISTRATION_FID_MATCH_MAX_ATTEMPTS","Notification","permission","requestPermission","onRegisteredHandler","serviceWorkerRegistration","prev","_registerNotifyChain","lastRegisterTime","dbSetFidRegistration","details","notifyOnRegistered","externalizePayload","internalPayload","payload","from","collapseKey","collapse_key","messageId","fcmMessageId","propagateNotificationPayload","messagePayloadInternal","notification","title","image","icon","propagateDataPayload","propagateFcmOptions","fcmOptions","click_action","link","analyticsLabel","analytics_label","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","_fidChangeUnsubscribe","logEvents","logQueue","messagingSenderId","timerId","logToScion","messageType","eventType","getEventType","NOTIFICATION_CLICKED","PUSH_RECEIVED","logEvent","message_id","message_name","message_time","message_device_time","floor","messageEventListener","isFirebaseMessaging","FID_REGISTERED","dataPayload","isConsoleMessage","WindowMessagingFactory","subscribeFidChangeRegistration","WindowMessagingInternalFactory","isWindowSupported","validateIndexedDBOpenable","preExist","DB_CHECK_NAME","onsuccess","onupgradeneeded","onerror","window","isIndexedDBAvailable","areCookiesEnabled","cookieEnabled","hasOwnProperty","PushSubscription","getMessagingInWindow","getApp","isSupported","_","_getToken","deleteToken","_deleteToken","onMessage","nextOrObserver","_onMessage","_register","unregister","_unregister","onRegistered","_onRegistered","onUnregistered","_onUnregistered","registerMessagingInWindow"],"mappings":"iGAyEM,MAAOA,sBAAsBC,MAIjC,WAAAC,CAEWC,EACTC,EAEOC,GAEPC,MAAMF,GALGG,KAAAJ,KAAAA,EAGFI,KAAAF,WAAAA,EAPAE,KAAAC,KAdQ,gBA6BfC,OAAOC,eAAeH,KAAMP,cAAcW,WAItCV,MAAMW,mBACRX,MAAMW,kBAAkBL,KAAMM,aAAaF,UAAUG,OAEzD,EAGW,MAAAD,aAIX,WAAAX,CACmBa,EACAC,EACAC,GAFAV,KAAAQ,QAAAA,EACAR,KAAAS,YAAAA,EACAT,KAAAU,OAAAA,CAChB,CAEH,MAAAH,CACEX,KACGe,GAEH,MAAMb,EAAca,EAAK,IAAoB,CAAA,EACvCC,EAAW,GAAGZ,KAAKQ,WAAWZ,IAC9BiB,EAAWb,KAAKU,OAAOd,GAEvBC,EAAUgB,EAUpB,SAASC,gBAAgBD,EAAkBF,GACzC,IACE,IAAII,EAAM,EACNC,EAAS,GACb,KAAOD,EAAMF,EAASI,QAAQ,CAC5B,MAAMC,EAAQL,EAASM,QAAQ,KAAMJ,GACrC,IAAe,IAAXG,EAAc,CAChBF,GAAUH,EAASO,U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