{"version":3,"sources":["jsdelivr-header.js","/npm/@firebase/messaging@0.13.3/src/util/constants.ts","/npm/@firebase/messaging@0.13.3/src/interfaces/internal-message-payload.ts","/npm/@firebase/messaging@0.13.3/src/helpers/array-base64-translator.ts","/npm/@firebase/messaging@0.13.3/src/helpers/migrate-old-database.ts","/npm/@firebase/messaging@0.13.3/src/util/errors.ts","/npm/@firebase/messaging@0.13.3/src/internals/idb-manager.ts","/npm/@firebase/messaging@0.13.3/src/internals/requests.ts","/npm/@firebase/messaging@0.13.3/src/internals/token-manager.ts","/npm/@firebase/messaging@0.13.3/src/helpers/registerDefaultSw.ts","/npm/@firebase/messaging@0.13.3/src/helpers/updateSwReg.ts","/npm/@firebase/messaging@0.13.3/src/helpers/updateVapidKey.ts","/npm/@firebase/messaging@0.13.3/src/internals/register-fid.ts","/npm/@firebase/messaging@0.13.3/src/api/register.ts","/npm/@firebase/messaging@0.13.3/src/helpers/fid-change-registration.ts","/npm/@firebase/messaging@0.13.3/src/helpers/externalizePayload.ts","/npm/@firebase/messaging@0.13.3/src/helpers/is-console-message.ts","/npm/@firebase/messaging@0.13.3/src/helpers/extract-app-config.ts","/npm/@firebase/messaging@0.13.3/src/messaging-service.ts","/npm/@firebase/messaging@0.13.3/src/api/getToken.ts","/npm/@firebase/messaging@0.13.3/src/helpers/logToScion.ts","/npm/@firebase/messaging@0.13.3/src/listeners/window-listener.ts","/npm/@firebase/messaging@0.13.3/src/helpers/register.ts","/npm/@firebase/messaging@0.13.3/src/api/isSupported.ts","/npm/@firebase/messaging@0.13.3/src/api/deleteToken.ts","/npm/@firebase/messaging@0.13.3/src/api/onMessage.ts","/npm/@firebase/messaging@0.13.3/src/api/onRegistered.ts","/npm/@firebase/messaging@0.13.3/src/api/onUnregistered.ts","/npm/@firebase/messaging@0.13.3/src/api/unregister.ts","/npm/@firebase/messaging@0.13.3/src/api.ts","/npm/@firebase/messaging@0.13.3/src/index.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AAC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M,4BAI5B,MAAM,QAAe,qBACnB,EAAU,sBACV,MAAM,QACF,EACJ,GAAQ,WAAc,EAAU,qBAAqB,cAAc,cAE/D,0BAA0B,EAAU,qBAAsB,GAGhE,UACQ,wBAAwB,EAAU,qBAC1C,CAAE,MAEF,CAGA,UACQ,SAAS,EAAU,qBAC3B,CAAE,MAEF,CAEA,MAAM,EAAU,EAAU,sBACrB,IAIkB,mBAAZ,EACT,EAAQ,GAER,EAAQ,KAAK,GAEjB;;;;;;;;;;;;;;;;GCpBM,SAAU,qBAAqB,EAAmB,UAiBtD,OAZA,oBAAoB,KAClB,IAEE,IAAK,EACH,MAAM,cAAc,OAAM,wBAG9B,IAEE,MAAM,cAAc,OAAM,4BAGvB,aAAa,mBAAmB,GAAM,aAAa,cAC5D,CA+CO,eAAe,SACpB,EACA,GAGA,OAAO,WADP,EAAY,mBAAmB,GACiB,EAClD,CAoBM,SAAU,YAAY,GAE1B,OAAO,cADP,EAAY,mBAAmB,GAEjC,CAeM,SAAU,UACd,EACA,GAGA,OAAO,YADP,EAAY,mBAAmB,GACkB,EACnD,CAmCO,eAAe,SACpB,EACA,GAGA,OAAO,WADP,EAAY,mBAAmB,GACiB,EAClD,CAUO,eAAe,WAAW,GAE/B,OAAO,aADP,EAAY,mBAAmB,GAEjC,CAaM,SAAU,aACd,EACA,GAGA,OAAO,eADP,EAAY,mBAAmB,GACqB,EACtD,CAYM,SAAU,eACd,EACA,GAGA,OAAO,iBADP,EAAY,mBAAmB,GACuB,EACxD;;;;;;;;;;;;;;;;GCjNA,mC","file":"/npm/@firebase/messaging@0.13.3/dist/esm/index.esm.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.48.0.\n * Original file: /npm/@firebase/messaging@0.13.3/dist/esm/index.esm.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\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 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 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 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 { 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 { 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 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> | Observer<MessagePayload> | 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 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 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 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 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 * @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 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 * 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"]}