{"version":3,"sources":["jsdelivr-header.js","/npm/@firebase/remote-config@0.8.1/src/client/remote_config_fetch_client.ts","/npm/@firebase/remote-config@0.8.1/src/constants.ts","/npm/@firebase/remote-config@0.8.1/src/errors.ts","/npm/@firebase/remote-config@0.8.1/src/value.ts","/npm/@firebase/remote-config@0.8.1/src/abt/experiment.ts","/npm/@firebase/remote-config@0.8.1/src/api.ts","/npm/@firebase/remote-config@0.8.1/src/client/caching_client.ts","/npm/@firebase/remote-config@0.8.1/src/language.ts","/npm/@firebase/remote-config@0.8.1/src/client/rest_client.ts","/npm/@firebase/remote-config@0.8.1/src/client/retrying_client.ts","/npm/@firebase/remote-config@0.8.1/src/remote_config.ts","/npm/@firebase/remote-config@0.8.1/src/storage/storage.ts","/npm/@firebase/remote-config@0.8.1/src/storage/storage_cache.ts","/npm/@firebase/remote-config@0.8.1/src/client/eventEmitter.ts","/npm/@firebase/remote-config@0.8.1/src/client/visibility_monitor.ts","/npm/@firebase/remote-config@0.8.1/src/client/realtime_handler.ts","/npm/@firebase/remote-config@0.8.1/src/register.ts","/npm/@firebase/remote-config@0.8.1/src/api2.ts","/npm/@firebase/remote-config@0.8.1/src/index.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;MCwCa,wBAAb,WAAA,GACE,KAAS,UAAsB,E,CAC/B,gBAAA,CAAiB,GACf,KAAK,UAAU,KAAK,E,CAEtB,KAAA,GACE,KAAK,UAAU,SAAQ,GAAY,K;;;;;;;;;;;;;;;;GCnChC,MAAM,kBAAoB,gBACpB,qCAAuC,IACvC,gCAAkC,IAClC,kCAAoC,ICuB3C,sBAAiE,CACrE,sBAAiC,oCACjC,sBACE,kFACF,0BACE,mEACF,uBACE,wDACF,sBACE,+DACF,eACE,8EACF,cACE,mFACF,cACE,iFACF,iBACE,oFACF,uBACE,mHAEF,gBACE,iGAEF,iBACE,mOAGF,qBACE,kFAEF,eACE,0EACF,yBACE,iDACF,oCACE,mEAC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AFA,EAAe,mBAAmB,SAC5B,YAAY,GACX,SAAS,EAClB,CAYO,eAAe,cACpB,IAAK,uBACH,OAAO,EAGT,IAEE,aADoC,2B,CAEpC,MAAO,GACP,OAAO,C,CAEX,CC1BA,8B","file":"/npm/@firebase/remote-config@0.8.1/dist/esm/index.esm.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@firebase/remote-config@0.8.1/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\nimport { CustomSignals, FetchResponse, FetchType } from '../public_types';\n\n/**\n * Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the\n * Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest).\n *\n * <p>Abstracts throttle, response cache and network implementation details.\n *\n * <p>Modeled after the native {@link GlobalFetch} interface, which is relatively modern and\n * convenient, but simplified for Remote Config's use case.\n *\n * Disambiguation: {@link GlobalFetch} interface and the Remote Config service define \"fetch\"\n * methods. The RestClient uses the former to make HTTP calls. This interface abstracts the latter.\n */\nexport interface RemoteConfigFetchClient {\n  /**\n   * @throws if response status is not 200 or 304.\n   */\n  fetch(request: FetchRequest): Promise<FetchResponse>;\n}\n\n/**\n * Shims a minimal AbortSignal.\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class RemoteConfigAbortSignal {\n  listeners: Array<() => void> = [];\n  addEventListener(listener: () => void): void {\n    this.listeners.push(listener);\n  }\n  abort(): void {\n    this.listeners.forEach(listener => listener());\n  }\n}\n\n/**\n * Defines per-request inputs for the Remote Config fetch request.\n *\n * <p>Modeled after the native {@link Request} interface, but simplified for Remote Config's\n * use case.\n */\nexport interface FetchRequest {\n  /**\n   * Uses cached config if it is younger than this age.\n   *\n   * <p>Required because it's defined by settings, which always have a value.\n   *\n   * <p>Comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the native\n   * Fetch API.\n   */\n  cacheMaxAgeMillis: number;\n\n  /**\n   * An event bus for the signal to abort a request.\n   *\n   * <p>Required because all requests should be abortable.\n   *\n   * <p>Comparable to the native\n   * Fetch API's \"signal\" field on its request configuration object\n   * https://fetch.spec.whatwg.org/#dom-requestinit-signal.\n   *\n   * <p>Disambiguation: Remote Config commonly refers to API inputs as\n   * \"signals\". See the private ConfigFetchRequestBody interface for those:\n   * http://google3/firebase/remote_config/web/src/core/rest_client.ts?l=14&rcl=255515243.\n   */\n  signal: RemoteConfigAbortSignal;\n\n  /**\n   * The ETag header value from the last response.\n   *\n   * <p>Optional in case this is the first request.\n   *\n   * <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API.\n   */\n  eTag?: string;\n\n  /** The custom signals stored for the app instance.\n   *\n   * <p>Optional in case no custom signals are set for the instance.\n   */\n  customSignals?: CustomSignals;\n\n  /**\n   * The type of fetch to perform, such as a regular fetch or a real-time fetch.\n   *\n   * Optional as not all fetch requests need to be distinguished.\n   */\n  fetchType?: FetchType;\n\n  /**\n   * The number of fetch attempts made so far for this request.\n   *\n   * Optional as not all fetch requests are part of a retry series.\n   */\n  fetchAttempt?: number;\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\nexport const RC_COMPONENT_NAME = 'remote-config';\nexport const RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 100;\nexport const RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH = 250;\nexport const RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH = 500;\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\n\nexport const enum ErrorCode {\n  ALREADY_INITIALIZED = 'already-initialized',\n  REGISTRATION_WINDOW = 'registration-window',\n  REGISTRATION_PROJECT_ID = 'registration-project-id',\n  REGISTRATION_API_KEY = 'registration-api-key',\n  REGISTRATION_APP_ID = 'registration-app-id',\n  STORAGE_OPEN = 'storage-open',\n  STORAGE_GET = 'storage-get',\n  STORAGE_SET = 'storage-set',\n  STORAGE_DELETE = 'storage-delete',\n  FETCH_NETWORK = 'fetch-client-network',\n  FETCH_TIMEOUT = 'fetch-timeout',\n  FETCH_THROTTLE = 'fetch-throttle',\n  FETCH_PARSE = 'fetch-client-parse',\n  FETCH_STATUS = 'fetch-status',\n  INDEXED_DB_UNAVAILABLE = 'indexed-db-unavailable',\n  CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 'custom-signal-max-allowed-signals',\n  CONFIG_UPDATE_STREAM_ERROR = 'stream-error',\n  CONFIG_UPDATE_UNAVAILABLE = 'realtime-unavailable',\n  CONFIG_UPDATE_MESSAGE_INVALID = 'update-message-invalid',\n  CONFIG_UPDATE_NOT_FETCHED = 'update-not-fetched',\n  ANALYTICS_UNAVAILABLE = 'analytics-unavailable'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n  [ErrorCode.ALREADY_INITIALIZED]: 'Remote Config already initialized',\n  [ErrorCode.REGISTRATION_WINDOW]:\n    'Undefined window object. This SDK only supports usage in a browser environment.',\n  [ErrorCode.REGISTRATION_PROJECT_ID]:\n    'Undefined project identifier. Check Firebase app initialization.',\n  [ErrorCode.REGISTRATION_API_KEY]:\n    'Undefined API key. Check Firebase app initialization.',\n  [ErrorCode.REGISTRATION_APP_ID]:\n    'Undefined app identifier. Check Firebase app initialization.',\n  [ErrorCode.STORAGE_OPEN]:\n    'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n  [ErrorCode.STORAGE_GET]:\n    'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n  [ErrorCode.STORAGE_SET]:\n    'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n  [ErrorCode.STORAGE_DELETE]:\n    'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',\n  [ErrorCode.FETCH_NETWORK]:\n    'Fetch client failed to connect to a network. Check Internet connection.' +\n    ' Original error: {$originalErrorMessage}.',\n  [ErrorCode.FETCH_TIMEOUT]:\n    'The config fetch request timed out. ' +\n    ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.',\n  [ErrorCode.FETCH_THROTTLE]:\n    'The config fetch request timed out while in an exponential backoff state.' +\n    ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.' +\n    ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n  [ErrorCode.FETCH_PARSE]:\n    'Fetch client could not parse response.' +\n    ' Original error: {$originalErrorMessage}.',\n  [ErrorCode.FETCH_STATUS]:\n    'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',\n  [ErrorCode.INDEXED_DB_UNAVAILABLE]:\n    'Indexed DB is not supported by current browser',\n  [ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS]:\n    'Setting more than {$maxSignals} custom signals is not supported.',\n  [ErrorCode.CONFIG_UPDATE_STREAM_ERROR]:\n    'The stream was not able to connect to the backend: {$originalErrorMessage}.',\n  [ErrorCode.CONFIG_UPDATE_UNAVAILABLE]:\n    'The Realtime service is unavailable: {$originalErrorMessage}',\n  [ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID]:\n    'The stream invalidation message was unparsable: {$originalErrorMessage}',\n  [ErrorCode.CONFIG_UPDATE_NOT_FETCHED]:\n    'Unable to fetch the latest config: {$originalErrorMessage}',\n  [ErrorCode.ANALYTICS_UNAVAILABLE]:\n    'Connection to Firebase Analytics failed: {$originalErrorMessage}'\n};\n\n// Note this is effectively a type system binding a code to params. This approach overlaps with the\n// role of TS interfaces, but works well for a few reasons:\n// 1) JS is unaware of TS interfaces, eg we can't test for interface implementation in JS\n// 2) callers should have access to a human-readable summary of the error and this interpolates\n//    params into an error message;\n// 3) callers should be able to programmatically access data associated with an error, which\n//    ErrorData provides.\ninterface ErrorParams {\n  [ErrorCode.STORAGE_OPEN]: { originalErrorMessage: string | undefined };\n  [ErrorCode.STORAGE_GET]: { originalErrorMessage: string | undefined };\n  [ErrorCode.STORAGE_SET]: { originalErrorMessage: string | undefined };\n  [ErrorCode.STORAGE_DELETE]: { originalErrorMessage: string | undefined };\n  [ErrorCode.FETCH_NETWORK]: { originalErrorMessage: string };\n  [ErrorCode.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n  [ErrorCode.FETCH_PARSE]: { originalErrorMessage: string };\n  [ErrorCode.FETCH_STATUS]: { httpStatus: number };\n  [ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS]: { maxSignals: number };\n  [ErrorCode.CONFIG_UPDATE_STREAM_ERROR]: { originalErrorMessage: string };\n  [ErrorCode.CONFIG_UPDATE_UNAVAILABLE]: { originalErrorMessage: string };\n  [ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID]: { originalErrorMessage: string };\n  [ErrorCode.CONFIG_UPDATE_NOT_FETCHED]: { originalErrorMessage: string };\n  [ErrorCode.ANALYTICS_UNAVAILABLE]: { originalErrorMessage: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n  'remoteconfig' /* service */,\n  'Remote Config' /* service name */,\n  ERROR_DESCRIPTION_MAP\n);\n\n// Note how this is like typeof/instanceof, but for ErrorCode.\nexport function hasErrorCode(e: Error, errorCode: ErrorCode): boolean {\n  return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1;\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 { Value as ValueType, ValueSource } from '@firebase/remote-config-types';\n\nconst DEFAULT_VALUE_FOR_BOOLEAN = false;\nconst DEFAULT_VALUE_FOR_STRING = '';\nconst DEFAULT_VALUE_FOR_NUMBER = 0;\n\nconst BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];\n\nexport class Value implements ValueType {\n  constructor(\n    private readonly _source: ValueSource,\n    private readonly _value: string = DEFAULT_VALUE_FOR_STRING\n  ) {}\n\n  asString(): string {\n    return this._value;\n  }\n\n  asBoolean(): boolean {\n    if (this._source === 'static') {\n      return DEFAULT_VALUE_FOR_BOOLEAN;\n    }\n    return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;\n  }\n\n  asNumber(): number {\n    if (this._source === 'static') {\n      return DEFAULT_VALUE_FOR_NUMBER;\n    }\n    let num = Number(this._value);\n    if (isNaN(num)) {\n      num = DEFAULT_VALUE_FOR_NUMBER;\n    }\n    return num;\n  }\n\n  getSource(): ValueSource {\n    return this._source;\n  }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Storage } from '../storage/storage';\nimport { FirebaseExperimentDescription } from '../public_types';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { Logger } from '@firebase/logger';\nimport { RemoteConfig } from '../remote_config';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\n\nexport class Experiment {\n  private storage: Storage;\n  private logger: Logger;\n  private analyticsProvider: Provider<FirebaseAnalyticsInternalName>;\n\n  constructor(rc: RemoteConfig) {\n    this.storage = rc._storage;\n    this.logger = rc._logger;\n    this.analyticsProvider = rc._analyticsProvider;\n  }\n\n  async updateActiveExperiments(\n    latestExperiments: FirebaseExperimentDescription[]\n  ): Promise<void> {\n    const currentActiveExperiments =\n      (await this.storage.getActiveExperiments()) || new Set<string>();\n    const experimentInfoMap = this.createExperimentInfoMap(latestExperiments);\n    this.addActiveExperiments(experimentInfoMap);\n    this.removeInactiveExperiments(currentActiveExperiments, experimentInfoMap);\n    return this.storage.setActiveExperiments(new Set(experimentInfoMap.keys()));\n  }\n\n  private createExperimentInfoMap(\n    latestExperiments: FirebaseExperimentDescription[]\n  ): Map<string, FirebaseExperimentDescription> {\n    const experimentInfoMap = new Map<string, FirebaseExperimentDescription>();\n    for (const experiment of latestExperiments) {\n      experimentInfoMap.set(experiment.experimentId, experiment);\n    }\n    return experimentInfoMap;\n  }\n\n  private addActiveExperiments(\n    experimentInfoMap: Map<string, FirebaseExperimentDescription>\n  ): void {\n    const customProperty: Record<string, string | null> = {};\n    for (const [experimentId, experimentInfo] of experimentInfoMap.entries()) {\n      customProperty[`firebase${experimentId}`] = experimentInfo.variantId;\n    }\n    this.addExperimentToAnalytics(customProperty);\n  }\n\n  private removeInactiveExperiments(\n    currentActiveExperiments: Set<string>,\n    experimentInfoMap: Map<string, FirebaseExperimentDescription>\n  ): void {\n    const customProperty: Record<string, string | null> = {};\n    for (const experimentId of currentActiveExperiments) {\n      if (!experimentInfoMap.has(experimentId)) {\n        customProperty[`firebase${experimentId}`] = null;\n      }\n    }\n    this.addExperimentToAnalytics(customProperty);\n  }\n\n  private addExperimentToAnalytics(\n    customProperty: Record<string, string | null>\n  ): void {\n    if (Object.keys(customProperty).length === 0) {\n      return;\n    }\n    try {\n      const analytics = this.analyticsProvider.getImmediate({ optional: true });\n      if (analytics) {\n        analytics.setUserProperties(customProperty);\n        analytics.logEvent(`set_firebase_experiment_state`);\n      } else {\n        this.logger.warn(\n          `Analytics import failed. Verify if you have imported Firebase Analytics in your app code.`\n        );\n      }\n    } catch (error) {\n      throw ERROR_FACTORY.create(ErrorCode.ANALYTICS_UNAVAILABLE, {\n        originalErrorMessage: (error as Error)?.message\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 { _getProvider, FirebaseApp, getApp } from '@firebase/app';\nimport { deepEqual, getModularInstance } from '@firebase/util';\nimport {\n  CustomSignals,\n  LogLevel as RemoteConfigLogLevel,\n  RemoteConfig,\n  Value,\n  RemoteConfigOptions,\n  ConfigUpdateObserver,\n  Unsubscribe\n} from './public_types';\nimport { RemoteConfigAbortSignal } from './client/remote_config_fetch_client';\nimport {\n  RC_COMPONENT_NAME,\n  RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH,\n  RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH\n} from './constants';\nimport { ERROR_FACTORY, ErrorCode, hasErrorCode } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { Value as ValueImpl } from './value';\nimport { LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { Experiment } from './abt/experiment';\n\n/**\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\n * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the\n *     Remote Config instance.\n * @returns A {@link RemoteConfig} instance.\n *\n * @public\n */\nexport function getRemoteConfig(\n  app: FirebaseApp = getApp(),\n  options: RemoteConfigOptions = {}\n): RemoteConfig {\n  app = getModularInstance(app);\n  const rcProvider = _getProvider(app, RC_COMPONENT_NAME);\n  if (rcProvider.isInitialized()) {\n    const initialOptions = rcProvider.getOptions() as RemoteConfigOptions;\n    if (deepEqual(initialOptions, options)) {\n      return rcProvider.getImmediate();\n    }\n    throw ERROR_FACTORY.create(ErrorCode.ALREADY_INITIALIZED);\n  }\n  rcProvider.initialize({ options });\n  const rc = rcProvider.getImmediate() as RemoteConfigImpl;\n\n  if (options.initialFetchResponse) {\n    // We use these initial writes as the initialization promise since they will hydrate the same\n    // fields that `storageCache.loadFromStorage` would set.\n    rc._initializePromise = Promise.all([\n      rc._storage.setLastSuccessfulFetchResponse(options.initialFetchResponse),\n      rc._storage.setActiveConfigEtag(options.initialFetchResponse?.eTag || ''),\n      rc._storage.setActiveConfigTemplateVersion(\n        options.initialFetchResponse.templateVersion || 0\n      ),\n      rc._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),\n      rc._storageCache.setLastFetchStatus('success'),\n      rc._storageCache.setActiveConfig(\n        options.initialFetchResponse?.config || {}\n      )\n    ]).then();\n    // The `storageCache` methods above set their in-memory fields synchronously, so it's\n    // safe to declare our initialization complete at this point.\n    rc._isInitializationComplete = true;\n  }\n\n  return rc;\n}\n\n/**\n * Makes the last fetched config available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function activate(remoteConfig: RemoteConfig): Promise<boolean> {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([\n    rc._storage.getLastSuccessfulFetchResponse(),\n    rc._storage.getActiveConfigEtag()\n  ]);\n  if (\n    !lastSuccessfulFetchResponse ||\n    !lastSuccessfulFetchResponse.config ||\n    !lastSuccessfulFetchResponse.eTag ||\n    !lastSuccessfulFetchResponse.templateVersion ||\n    lastSuccessfulFetchResponse.eTag === activeConfigEtag\n  ) {\n    // Either there is no successful fetched config, or is the same as current active\n    // config.\n    return false;\n  }\n  const experiment = new Experiment(rc);\n  const updateActiveExperiments = lastSuccessfulFetchResponse.experiments\n    ? experiment.updateActiveExperiments(\n        lastSuccessfulFetchResponse.experiments\n      )\n    : Promise.resolve();\n  await Promise.all([\n    rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n    rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag),\n    rc._storage.setActiveConfigTemplateVersion(\n      lastSuccessfulFetchResponse.templateVersion\n    ),\n    updateActiveExperiments\n  ]);\n  return true;\n}\n\n/**\n * Ensures the last activated config are available to the getters.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` that resolves when the last activated config is available to the getters.\n * @public\n */\nexport function ensureInitialized(remoteConfig: RemoteConfig): Promise<void> {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  if (!rc._initializePromise) {\n    rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {\n      rc._isInitializationComplete = true;\n    });\n  }\n  return rc._initializePromise;\n}\n\n/**\n * Fetches and caches configuration from the Remote Config service.\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @public\n */\nexport async function fetchConfig(remoteConfig: RemoteConfig): Promise<void> {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  // Aborts the request after the given timeout, causing the fetch call to\n  // reject with an `AbortError`.\n  //\n  // <p>Aborting after the request completes is a no-op, so we don't need a\n  // corresponding `clearTimeout`.\n  //\n  // Locating abort logic here because:\n  // * it uses a developer setting (timeout)\n  // * it applies to all retries (like curl's max-time arg)\n  // * it is consistent with the Fetch API's signal input\n  const abortSignal = new RemoteConfigAbortSignal();\n\n  setTimeout(async () => {\n    // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n    abortSignal.abort();\n  }, rc.settings.fetchTimeoutMillis);\n\n  const customSignals = rc._storageCache.getCustomSignals();\n  if (customSignals) {\n    rc._logger.debug(\n      `Fetching config with custom signals: ${JSON.stringify(customSignals)}`\n    );\n  }\n  // Catches *all* errors thrown by client so status can be set consistently.\n  try {\n    await rc._client.fetch({\n      cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,\n      signal: abortSignal,\n      customSignals\n    });\n\n    await rc._storageCache.setLastFetchStatus('success');\n  } catch (e) {\n    const lastFetchStatus = hasErrorCode(e as Error, ErrorCode.FETCH_THROTTLE)\n      ? 'throttle'\n      : 'failure';\n    await rc._storageCache.setLastFetchStatus(lastFetchStatus);\n    throw e;\n  }\n}\n\n/**\n * Gets all config.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @returns All config.\n *\n * @public\n */\nexport function getAll(remoteConfig: RemoteConfig): Record<string, Value> {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  return getAllKeys(\n    rc._storageCache.getActiveConfig(),\n    rc.defaultConfig\n  ).reduce((allConfigs, key) => {\n    allConfigs[key] = getValue(remoteConfig, key);\n    return allConfigs;\n  }, {} as Record<string, Value>);\n}\n\n/**\n * Gets the value for the given key as a boolean.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a boolean.\n * @public\n */\nexport function getBoolean(remoteConfig: RemoteConfig, key: string): boolean {\n  return getValue(getModularInstance(remoteConfig), key).asBoolean();\n}\n\n/**\n * Gets the value for the given key as a number.\n *\n * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a number.\n *\n * @public\n */\nexport function getNumber(remoteConfig: RemoteConfig, key: string): number {\n  return getValue(getModularInstance(remoteConfig), key).asNumber();\n}\n\n/**\n * Gets the value for the given key as a string.\n * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key as a string.\n *\n * @public\n */\nexport function getString(remoteConfig: RemoteConfig, key: string): string {\n  return getValue(getModularInstance(remoteConfig), key).asString();\n}\n\n/**\n * Gets the {@link Value} for the given key.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param key - The name of the parameter.\n *\n * @returns The value for the given key.\n *\n * @public\n */\nexport function getValue(remoteConfig: RemoteConfig, key: string): Value {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  if (!rc._isInitializationComplete) {\n    rc._logger.debug(\n      `A value was requested for key \"${key}\" before SDK initialization completed.` +\n        ' Await on ensureInitialized if the intent was to get a previously activated value.'\n    );\n  }\n  const activeConfig = rc._storageCache.getActiveConfig();\n  if (activeConfig && activeConfig[key] !== undefined) {\n    return new ValueImpl('remote', activeConfig[key]);\n  } else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {\n    return new ValueImpl('default', String(rc.defaultConfig[key]));\n  }\n  rc._logger.debug(\n    `Returning static value for key \"${key}\".` +\n      ' Define a default or remote value if this is unintentional.'\n  );\n  return new ValueImpl('static');\n}\n\n/**\n * Defines the log level to use.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param logLevel - The log level to set.\n *\n * @public\n */\nexport function setLogLevel(\n  remoteConfig: RemoteConfig,\n  logLevel: RemoteConfigLogLevel\n): void {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  switch (logLevel) {\n    case 'debug':\n      rc._logger.logLevel = FirebaseLogLevel.DEBUG;\n      break;\n    case 'silent':\n      rc._logger.logLevel = FirebaseLogLevel.SILENT;\n      break;\n    default:\n      rc._logger.logLevel = FirebaseLogLevel.ERROR;\n  }\n}\n\n/**\n * Dedupes and returns an array of all the keys of the received objects.\n */\nfunction getAllKeys(obj1: {} = {}, obj2: {} = {}): string[] {\n  return Object.keys({ ...obj1, ...obj2 });\n}\n\n/**\n * Sets the custom signals for the app instance.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If\n * a key already exists, the value is overwritten. Setting the value of a custom signal to null\n * unsets the signal. The signals will be persisted locally on the client.\n *\n * @public\n */\nexport async function setCustomSignals(\n  remoteConfig: RemoteConfig,\n  customSignals: CustomSignals\n): Promise<void> {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  if (Object.keys(customSignals).length === 0) {\n    return;\n  }\n\n  // eslint-disable-next-line guard-for-in\n  for (const key in customSignals) {\n    if (key.length > RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH) {\n      rc._logger.error(\n        `Custom signal key ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH}.`\n      );\n      return;\n    }\n    const value = customSignals[key];\n    if (\n      typeof value === 'string' &&\n      value.length > RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH\n    ) {\n      rc._logger.error(\n        `Value supplied for custom signal ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH}.`\n      );\n      return;\n    }\n  }\n\n  try {\n    await rc._storageCache.setCustomSignals(customSignals);\n  } catch (error) {\n    rc._logger.error(\n      `Error encountered while setting custom signals: ${error}`\n    );\n  }\n}\n\n// TODO: Add public document for the Remote Config Realtime API guide on the Web Platform.\n/**\n * Starts listening for real-time config updates from the Remote Config backend and automatically\n * fetches updates from the Remote Config backend when they are available.\n *\n * @remarks\n * If a connection to the Remote Config backend is not already open, calling this method will\n * open it. Multiple listeners can be added by calling this method again, but subsequent calls\n * re-use the same connection to the backend.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates.\n * @returns An {@link Unsubscribe} function to remove the listener.\n *\n * @public\n */\nexport function onConfigUpdate(\n  remoteConfig: RemoteConfig,\n  observer: ConfigUpdateObserver\n): Unsubscribe {\n  const rc = getModularInstance(remoteConfig) as RemoteConfigImpl;\n  rc._realtimeHandler.addObserver(observer);\n  return () => {\n    rc._realtimeHandler.removeObserver(observer);\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 { StorageCache } from '../storage/storage_cache';\nimport { FetchResponse } from '../public_types';\nimport {\n  RemoteConfigFetchClient,\n  FetchRequest\n} from './remote_config_fetch_client';\nimport { Storage } from '../storage/storage';\nimport { Logger } from '@firebase/logger';\n\n/**\n * Implements the {@link RemoteConfigClient} abstraction with success response caching.\n *\n * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service\n * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the\n * Cache API doesn't support matching entries by time.\n */\nexport class CachingClient implements RemoteConfigFetchClient {\n  constructor(\n    private readonly client: RemoteConfigFetchClient,\n    private readonly storage: Storage,\n    private readonly storageCache: StorageCache,\n    private readonly logger: Logger\n  ) {}\n\n  /**\n   * Returns true if the age of the cached fetched configs is less than or equal to\n   * {@link Settings#minimumFetchIntervalInSeconds}.\n   *\n   * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the\n   * native Fetch API.\n   *\n   * <p>Visible for testing.\n   */\n  isCachedDataFresh(\n    cacheMaxAgeMillis: number,\n    lastSuccessfulFetchTimestampMillis: number | undefined\n  ): boolean {\n    // Cache can only be fresh if it's populated.\n    if (!lastSuccessfulFetchTimestampMillis) {\n      this.logger.debug('Config fetch cache check. Cache unpopulated.');\n      return false;\n    }\n\n    // Calculates age of cache entry.\n    const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;\n\n    const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;\n\n    this.logger.debug(\n      'Config fetch cache check.' +\n        ` Cache age millis: ${cacheAgeMillis}.` +\n        ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +\n        ` Is cache hit: ${isCachedDataFresh}.`\n    );\n\n    return isCachedDataFresh;\n  }\n\n  async fetch(request: FetchRequest): Promise<FetchResponse> {\n    // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.\n    const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] =\n      await Promise.all([\n        this.storage.getLastSuccessfulFetchTimestampMillis(),\n        this.storage.getLastSuccessfulFetchResponse()\n      ]);\n\n    // Exits early on cache hit.\n    if (\n      lastSuccessfulFetchResponse &&\n      this.isCachedDataFresh(\n        request.cacheMaxAgeMillis,\n        lastSuccessfulFetchTimestampMillis\n      )\n    ) {\n      return lastSuccessfulFetchResponse;\n    }\n\n    // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API\n    // that allows the caller to pass an ETag.\n    request.eTag =\n      lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;\n\n    // Falls back to service on cache miss.\n    const response = await this.client.fetch(request);\n\n    // Fetch throws for non-success responses, so success is guaranteed here.\n\n    const storageOperations = [\n      // Uses write-through cache for consistency with synchronous public API.\n      this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())\n    ];\n\n    if (response.status === 200) {\n      // Caches response only if it has changed, ie non-304 responses.\n      storageOperations.push(\n        this.storage.setLastSuccessfulFetchResponse(response)\n      );\n    }\n\n    await Promise.all(storageOperations);\n\n    return response;\n  }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Attempts to get the most accurate browser language setting.\n *\n * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.\n *\n * <p>Defers default language specification to server logic for consistency.\n *\n * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.\n */\nexport function getUserLanguage(\n  navigatorLanguage: NavigatorLanguage = navigator\n): string {\n  return (\n    // Most reliable, but only supported in Chrome/Firefox.\n    (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n    // Supported in most browsers, but returns the language of the browser\n    // UI, not the language set in browser settings.\n    navigatorLanguage.language\n    // Polyfill otherwise.\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 {\n  CustomSignals,\n  FetchResponse,\n  FirebaseRemoteConfigObject,\n  FirebaseExperimentDescription\n} from '../public_types';\nimport {\n  RemoteConfigFetchClient,\n  FetchRequest\n} from './remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { getUserLanguage } from '../language';\nimport { _FirebaseInstallationsInternal } from '@firebase/installations';\n\n/**\n * Defines request body parameters required to call the fetch API:\n * https://firebase.google.com/docs/reference/remote-config/rest\n *\n * <p>Not exported because this file encapsulates REST API specifics.\n *\n * <p>Not passing User Properties because Analytics' source of truth on Web is server-side.\n */\ninterface FetchRequestBody {\n  // Disables camelcase linting for request body params.\n  /* eslint-disable camelcase*/\n  sdk_version: string;\n  app_instance_id: string;\n  app_instance_id_token: string;\n  app_id: string;\n  language_code: string;\n  custom_signals?: CustomSignals;\n  /* eslint-enable camelcase */\n}\n\n/**\n * Implements the Client abstraction for the Remote Config REST API.\n */\nexport class RestClient implements RemoteConfigFetchClient {\n  constructor(\n    private readonly firebaseInstallations: _FirebaseInstallationsInternal,\n    private readonly sdkVersion: string,\n    private readonly namespace: string,\n    private readonly projectId: string,\n    private readonly apiKey: string,\n    private readonly appId: string\n  ) {}\n\n  /**\n   * Fetches from the Remote Config REST API.\n   *\n   * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't\n   * connect to the network.\n   * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the\n   * fetch response.\n   * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.\n   */\n  async fetch(request: FetchRequest): Promise<FetchResponse> {\n    const [installationId, installationToken] = await Promise.all([\n      this.firebaseInstallations.getId(),\n      this.firebaseInstallations.getToken()\n    ]);\n\n    const urlBase =\n      window.FIREBASE_REMOTE_CONFIG_URL_BASE ||\n      'https://firebaseremoteconfig.googleapis.com';\n\n    const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;\n\n    const headers = {\n      'Content-Type': 'application/json',\n      'Content-Encoding': 'gzip',\n      // Deviates from pure decorator by not passing max-age header since we don't currently have\n      // service behavior using that header.\n      'If-None-Match': request.eTag || '*'\n      // TODO: Add this header once CORS error is fixed internally.\n      //'X-Firebase-RC-Fetch-Type': `${fetchType}/${fetchAttempt}`\n    };\n\n    const requestBody: FetchRequestBody = {\n      /* eslint-disable camelcase */\n      sdk_version: this.sdkVersion,\n      app_instance_id: installationId,\n      app_instance_id_token: installationToken,\n      app_id: this.appId,\n      language_code: getUserLanguage(),\n      custom_signals: request.customSignals\n      /* eslint-enable camelcase */\n    };\n\n    const options = {\n      method: 'POST',\n      headers,\n      body: JSON.stringify(requestBody)\n    };\n\n    // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.\n    const fetchPromise = fetch(url, options);\n    const timeoutPromise = new Promise((_resolve, reject) => {\n      // Maps async event listener to Promise API.\n      request.signal.addEventListener(() => {\n        // Emulates https://heycam.github.io/webidl/#aborterror\n        const error = new Error('The operation was aborted.');\n        error.name = 'AbortError';\n        reject(error);\n      });\n    });\n\n    let response;\n    try {\n      await Promise.race([fetchPromise, timeoutPromise]);\n      response = await fetchPromise;\n    } catch (originalError) {\n      let errorCode = ErrorCode.FETCH_NETWORK;\n      if ((originalError as Error)?.name === 'AbortError') {\n        errorCode = ErrorCode.FETCH_TIMEOUT;\n      }\n      throw ERROR_FACTORY.create(errorCode, {\n        originalErrorMessage: (originalError as Error)?.message\n      });\n    }\n\n    let status = response.status;\n\n    // Normalizes nullable header to optional.\n    const responseEtag = response.headers.get('ETag') || undefined;\n\n    let config: FirebaseRemoteConfigObject | undefined;\n    let state: string | undefined;\n    let templateVersion: number | undefined;\n    let experiments: FirebaseExperimentDescription[] | undefined;\n\n    // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n    // Requesting application/json and checking for a 200 ensures there's JSON data.\n    if (response.status === 200) {\n      let responseBody;\n      try {\n        responseBody = await response.json();\n      } catch (originalError) {\n        throw ERROR_FACTORY.create(ErrorCode.FETCH_PARSE, {\n          originalErrorMessage: (originalError as Error)?.message\n        });\n      }\n      config = responseBody['entries'];\n      state = responseBody['state'];\n      templateVersion = responseBody['templateVersion'];\n      experiments = responseBody['experimentDescriptions'];\n    }\n\n    // Normalizes based on legacy state.\n    if (state === 'INSTANCE_STATE_UNSPECIFIED') {\n      status = 500;\n    } else if (state === 'NO_CHANGE') {\n      status = 304;\n    } else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {\n      // These cases can be fixed remotely, so normalize to safe value.\n      config = {};\n      experiments = [];\n    }\n\n    // Normalize to exception-based control flow for non-success cases.\n    // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for\n    // differentiating success states (200 from 304; the state body param is undefined in a\n    // standard 304).\n    if (status !== 304 && status !== 200) {\n      throw ERROR_FACTORY.create(ErrorCode.FETCH_STATUS, {\n        httpStatus: status\n      });\n    }\n\n    return { status, eTag: responseEtag, config, templateVersion, experiments };\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 { FetchResponse } from '../public_types';\nimport {\n  RemoteConfigAbortSignal,\n  RemoteConfigFetchClient,\n  FetchRequest\n} from './remote_config_fetch_client';\nimport { ThrottleMetadata, Storage } from '../storage/storage';\nimport { ErrorCode, ERROR_FACTORY } from '../errors';\nimport { FirebaseError, calculateBackoffMillis } from '@firebase/util';\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n *   <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n *   <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n *   <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n *       request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nexport function setAbortableTimeout(\n  signal: RemoteConfigAbortSignal,\n  throttleEndTimeMillis: number\n): Promise<void> {\n  return new Promise((resolve, reject) => {\n    // Derives backoff from given end time, normalizing negative numbers to zero.\n    const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n    const timeout = setTimeout(resolve, backoffMillis);\n\n    // Adds listener, rather than sets onabort, because signal is a shared object.\n    signal.addEventListener(() => {\n      clearTimeout(timeout);\n\n      // If the request completes before this timeout, the rejection has no effect.\n      reject(\n        ERROR_FACTORY.create(ErrorCode.FETCH_THROTTLE, {\n          throttleEndTimeMillis\n        })\n      );\n    });\n  });\n}\n\ntype RetriableError = FirebaseError & { customData: { httpStatus: string } };\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): e is RetriableError {\n  if (!(e instanceof FirebaseError) || !e.customData) {\n    return false;\n  }\n\n  // Uses string index defined by ErrorData, which FirebaseError implements.\n  const httpStatus = Number(e.customData['httpStatus']);\n\n  return (\n    httpStatus === 429 ||\n    httpStatus === 500 ||\n    httpStatus === 503 ||\n    httpStatus === 504\n  );\n}\n\n/**\n * Decorates a Client with retry logic.\n *\n * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache\n * responses (because the SDK has no use for error responses).\n */\nexport class RetryingClient implements RemoteConfigFetchClient {\n  constructor(\n    private readonly client: RemoteConfigFetchClient,\n    private readonly storage: Storage\n  ) {}\n\n  async fetch(request: FetchRequest): Promise<FetchResponse> {\n    const throttleMetadata = (await this.storage.getThrottleMetadata()) || {\n      backoffCount: 0,\n      throttleEndTimeMillis: Date.now()\n    };\n\n    return this.attemptFetch(request, throttleMetadata);\n  }\n\n  /**\n   * A recursive helper for attempting a fetch request repeatedly.\n   *\n   * @throws any non-retriable errors.\n   */\n  async attemptFetch(\n    request: FetchRequest,\n    { throttleEndTimeMillis, backoffCount }: ThrottleMetadata\n  ): Promise<FetchResponse> {\n    // Starts with a (potentially zero) timeout to support resumption from stored state.\n    // Ensures the throttle end time is honored if the last attempt timed out.\n    // Note the SDK will never make a request if the fetch timeout expires at this point.\n    await setAbortableTimeout(request.signal, throttleEndTimeMillis);\n\n    try {\n      const response = await this.client.fetch(request);\n\n      // Note the SDK only clears throttle state if response is success or non-retriable.\n      await this.storage.deleteThrottleMetadata();\n\n      return response;\n    } catch (e) {\n      if (!isRetriableError(e as Error)) {\n        throw e;\n      }\n\n      // Increments backoff state.\n      const throttleMetadata = {\n        throttleEndTimeMillis:\n          Date.now() + calculateBackoffMillis(backoffCount),\n        backoffCount: backoffCount + 1\n      };\n\n      // Persists state.\n      await this.storage.setThrottleMetadata(throttleMetadata);\n\n      return this.attemptFetch(request, throttleMetadata);\n    }\n  }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app';\nimport {\n  RemoteConfig as RemoteConfigType,\n  FetchStatus,\n  RemoteConfigSettings\n} from './public_types';\nimport { StorageCache } from './storage/storage_cache';\nimport { RemoteConfigFetchClient } from './client/remote_config_fetch_client';\nimport { Storage } from './storage/storage';\nimport { Logger } from '@firebase/logger';\nimport { FirebaseAnalyticsInternalName } from '@firebase/analytics-interop-types';\nimport { Provider } from '@firebase/component';\nimport { RealtimeHandler } from './client/realtime_handler';\n\nconst DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute\nconst DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.\n\n/**\n * Encapsulates business logic mapping network and storage dependencies to the public SDK API.\n *\n * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/compat/index.d.ts|interface documentation} for method descriptions.\n */\nexport class RemoteConfig implements RemoteConfigType {\n  /**\n   * Tracks completion of initialization promise.\n   * @internal\n   */\n  _isInitializationComplete = false;\n\n  /**\n   * De-duplicates initialization calls.\n   * @internal\n   */\n  _initializePromise?: Promise<void>;\n\n  settings: RemoteConfigSettings = {\n    fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,\n    minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS\n  };\n\n  defaultConfig: { [key: string]: string | number | boolean } = {};\n\n  get fetchTimeMillis(): number {\n    return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;\n  }\n\n  get lastFetchStatus(): FetchStatus {\n    return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';\n  }\n\n  constructor(\n    // Required by FirebaseServiceFactory interface.\n    readonly app: FirebaseApp,\n    // JS doesn't support private yet\n    // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an\n    // underscore prefix.\n    /**\n     * @internal\n     */\n    readonly _client: RemoteConfigFetchClient,\n    /**\n     * @internal\n     */\n    readonly _storageCache: StorageCache,\n    /**\n     * @internal\n     */\n    readonly _storage: Storage,\n    /**\n     * @internal\n     */\n    readonly _logger: Logger,\n    /**\n     * @internal\n     */\n    readonly _realtimeHandler: RealtimeHandler,\n    /**\n     * @internal\n     */\n    readonly _analyticsProvider: Provider<FirebaseAnalyticsInternalName>\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 { FetchStatus, CustomSignals } from '@firebase/remote-config-types';\nimport { FetchResponse, FirebaseRemoteConfigObject } from '../public_types';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS } from '../constants';\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.\n */\nfunction toFirebaseError(event: Event, errorCode: ErrorCode): FirebaseError {\n  const originalError = (event.target as IDBRequest).error || undefined;\n  return ERROR_FACTORY.create(errorCode, {\n    originalErrorMessage: originalError && (originalError as Error)?.message\n  });\n}\n\n/**\n * A general-purpose store keyed by app + namespace + {@link\n * ProjectNamespaceKeyFieldValue}.\n *\n * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact\n * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys\n * for a set of key-value pairs. See {@link Storage#createCompositeKey}.\n *\n * <p>Visible for testing.\n */\nexport const APP_NAMESPACE_STORE = 'app_namespace_store';\n\nconst DB_NAME = 'firebase_remote_config';\nconst DB_VERSION = 1;\n\n/**\n * Encapsulates metadata concerning throttled fetch requests.\n */\nexport interface ThrottleMetadata {\n  // The number of times fetch has backed off. Used for resuming backoff after a timeout.\n  backoffCount: number;\n  // The Unix timestamp in milliseconds when callers can retry a request.\n  throttleEndTimeMillis: number;\n}\n\nexport interface RealtimeBackoffMetadata {\n  // The number of consecutive connection streams that have failed.\n  numFailedStreams: number;\n  // The Date until which the client should wait before attempting any new real-time connections.\n  backoffEndTimeMillis: Date;\n}\n\n/**\n * Provides type-safety for the \"key\" field used by {@link APP_NAMESPACE_STORE}.\n *\n * <p>This seems like a small price to avoid potentially subtle bugs caused by a typo.\n */\ntype ProjectNamespaceKeyFieldValue =\n  | 'active_config'\n  | 'active_config_etag'\n  | 'active_experiments'\n  | 'last_fetch_status'\n  | 'last_successful_fetch_timestamp_millis'\n  | 'last_successful_fetch_response'\n  | 'settings'\n  | 'throttle_metadata'\n  | 'custom_signals'\n  | 'realtime_backoff_metadata'\n  | 'last_known_template_version';\n\n// Visible for testing.\nexport function openDatabase(): Promise<IDBDatabase> {\n  return new Promise((resolve, reject) => {\n    try {\n      const request = indexedDB.open(DB_NAME, DB_VERSION);\n      request.onerror = event => {\n        reject(toFirebaseError(event, ErrorCode.STORAGE_OPEN));\n      };\n      request.onsuccess = event => {\n        resolve((event.target as IDBOpenDBRequest).result);\n      };\n      request.onupgradeneeded = event => {\n        const db = (event.target as IDBOpenDBRequest).result;\n\n        // We don't use 'break' in this switch statement, the fall-through\n        // behavior is what we want, because if there are multiple versions between\n        // the old version and the current version, we want ALL the migrations\n        // that correspond to those versions to run, not only the last one.\n        // eslint-disable-next-line default-case\n        switch (event.oldVersion) {\n          case 0:\n            db.createObjectStore(APP_NAMESPACE_STORE, {\n              keyPath: 'compositeKey'\n            });\n        }\n      };\n    } catch (error) {\n      reject(\n        ERROR_FACTORY.create(ErrorCode.STORAGE_OPEN, {\n          originalErrorMessage: (error as Error)?.message\n        })\n      );\n    }\n  });\n}\n\n/**\n * Abstracts data persistence.\n */\nexport abstract class Storage {\n  getLastFetchStatus(): Promise<FetchStatus | undefined> {\n    return this.get<FetchStatus>('last_fetch_status');\n  }\n\n  setLastFetchStatus(status: FetchStatus): Promise<void> {\n    return this.set<FetchStatus>('last_fetch_status', status);\n  }\n\n  // This is comparable to a cache entry timestamp. If we need to expire other data, we could\n  // consider adding timestamp to all storage records and an optional max age arg to getters.\n  getLastSuccessfulFetchTimestampMillis(): Promise<number | undefined> {\n    return this.get<number>('last_successful_fetch_timestamp_millis');\n  }\n\n  setLastSuccessfulFetchTimestampMillis(timestamp: number): Promise<void> {\n    return this.set<number>(\n      'last_successful_fetch_timestamp_millis',\n      timestamp\n    );\n  }\n\n  getLastSuccessfulFetchResponse(): Promise<FetchResponse | undefined> {\n    return this.get<FetchResponse>('last_successful_fetch_response');\n  }\n\n  setLastSuccessfulFetchResponse(response: FetchResponse): Promise<void> {\n    return this.set<FetchResponse>('last_successful_fetch_response', response);\n  }\n\n  getActiveConfig(): Promise<FirebaseRemoteConfigObject | undefined> {\n    return this.get<FirebaseRemoteConfigObject>('active_config');\n  }\n\n  setActiveConfig(config: FirebaseRemoteConfigObject): Promise<void> {\n    return this.set<FirebaseRemoteConfigObject>('active_config', config);\n  }\n\n  getActiveConfigEtag(): Promise<string | undefined> {\n    return this.get<string>('active_config_etag');\n  }\n\n  setActiveConfigEtag(etag: string): Promise<void> {\n    return this.set<string>('active_config_etag', etag);\n  }\n\n  getActiveExperiments(): Promise<Set<string> | undefined> {\n    return this.get<Set<string>>('active_experiments');\n  }\n\n  setActiveExperiments(experiments: Set<string>): Promise<void> {\n    return this.set<Set<string>>('active_experiments', experiments);\n  }\n\n  getThrottleMetadata(): Promise<ThrottleMetadata | undefined> {\n    return this.get<ThrottleMetadata>('throttle_metadata');\n  }\n\n  setThrottleMetadata(metadata: ThrottleMetadata): Promise<void> {\n    return this.set<ThrottleMetadata>('throttle_metadata', metadata);\n  }\n\n  deleteThrottleMetadata(): Promise<void> {\n    return this.delete('throttle_metadata');\n  }\n\n  getCustomSignals(): Promise<CustomSignals | undefined> {\n    return this.get<CustomSignals>('custom_signals');\n  }\n\n  abstract setCustomSignals(\n    customSignals: CustomSignals\n  ): Promise<CustomSignals>;\n  abstract get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined>;\n  abstract set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>;\n  abstract delete(key: ProjectNamespaceKeyFieldValue): Promise<void>;\n\n  getRealtimeBackoffMetadata(): Promise<RealtimeBackoffMetadata | undefined> {\n    return this.get<RealtimeBackoffMetadata>('realtime_backoff_metadata');\n  }\n\n  setRealtimeBackoffMetadata(\n    realtimeMetadata: RealtimeBackoffMetadata\n  ): Promise<void> {\n    return this.set<RealtimeBackoffMetadata>(\n      'realtime_backoff_metadata',\n      realtimeMetadata\n    );\n  }\n\n  getActiveConfigTemplateVersion(): Promise<number | undefined> {\n    return this.get<number>('last_known_template_version');\n  }\n\n  setActiveConfigTemplateVersion(version: number): Promise<void> {\n    return this.set<number>('last_known_template_version', version);\n  }\n}\n\nexport class IndexedDbStorage extends Storage {\n  /**\n   * @param appId enables storage segmentation by app (ID + name).\n   * @param appName enables storage segmentation by app (ID + name).\n   * @param namespace enables storage segmentation by namespace.\n   */\n  constructor(\n    private readonly appId: string,\n    private readonly appName: string,\n    private readonly namespace: string,\n    private readonly openDbPromise = openDatabase()\n  ) {\n    super();\n  }\n\n  async setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals> {\n    const db = await this.openDbPromise;\n    const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n    const storedSignals = await this.getWithTransaction<CustomSignals>(\n      'custom_signals',\n      transaction\n    );\n    const updatedSignals = mergeCustomSignals(\n      customSignals,\n      storedSignals || {}\n    );\n    await this.setWithTransaction<CustomSignals>(\n      'custom_signals',\n      updatedSignals,\n      transaction\n    );\n    return updatedSignals;\n  }\n\n  /**\n   * Gets a value from the database using the provided transaction.\n   *\n   * @param key The key of the value to get.\n   * @param transaction The transaction to use for the operation.\n   * @returns The value associated with the key, or undefined if no such value exists.\n   */\n  async getWithTransaction<T>(\n    key: ProjectNamespaceKeyFieldValue,\n    transaction: IDBTransaction\n  ): Promise<T | undefined> {\n    return new Promise((resolve, reject) => {\n      const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n      const compositeKey = this.createCompositeKey(key);\n      try {\n        const request = objectStore.get(compositeKey);\n        request.onerror = event => {\n          reject(toFirebaseError(event, ErrorCode.STORAGE_GET));\n        };\n        request.onsuccess = event => {\n          const result = (event.target as IDBRequest).result;\n          if (result) {\n            resolve(result.value);\n          } else {\n            resolve(undefined);\n          }\n        };\n      } catch (e) {\n        reject(\n          ERROR_FACTORY.create(ErrorCode.STORAGE_GET, {\n            originalErrorMessage: (e as Error)?.message\n          })\n        );\n      }\n    });\n  }\n\n  /**\n   * Sets a value in the database using the provided transaction.\n   *\n   * @param key The key of the value to set.\n   * @param value The value to set.\n   * @param transaction The transaction to use for the operation.\n   * @returns A promise that resolves when the operation is complete.\n   */\n  async setWithTransaction<T>(\n    key: ProjectNamespaceKeyFieldValue,\n    value: T,\n    transaction: IDBTransaction\n  ): Promise<void> {\n    return new Promise((resolve, reject) => {\n      const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n      const compositeKey = this.createCompositeKey(key);\n      try {\n        const request = objectStore.put({\n          compositeKey,\n          value\n        });\n        request.onerror = (event: Event) => {\n          reject(toFirebaseError(event, ErrorCode.STORAGE_SET));\n        };\n        request.onsuccess = () => {\n          resolve();\n        };\n      } catch (e) {\n        reject(\n          ERROR_FACTORY.create(ErrorCode.STORAGE_SET, {\n            originalErrorMessage: (e as Error)?.message\n          })\n        );\n      }\n    });\n  }\n\n  async get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined> {\n    const db = await this.openDbPromise;\n    const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');\n    return this.getWithTransaction<T>(key, transaction);\n  }\n\n  async set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void> {\n    const db = await this.openDbPromise;\n    const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n    return this.setWithTransaction<T>(key, value, transaction);\n  }\n\n  async delete(key: ProjectNamespaceKeyFieldValue): Promise<void> {\n    const db = await this.openDbPromise;\n    return new Promise((resolve, reject) => {\n      const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n      const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n      const compositeKey = this.createCompositeKey(key);\n      try {\n        const request = objectStore.delete(compositeKey);\n        request.onerror = (event: Event) => {\n          reject(toFirebaseError(event, ErrorCode.STORAGE_DELETE));\n        };\n        request.onsuccess = () => {\n          resolve();\n        };\n      } catch (e) {\n        reject(\n          ERROR_FACTORY.create(ErrorCode.STORAGE_DELETE, {\n            originalErrorMessage: (e as Error)?.message\n          })\n        );\n      }\n    });\n  }\n\n  // Facilitates composite key functionality (which is unsupported in IE).\n  createCompositeKey(key: ProjectNamespaceKeyFieldValue): string {\n    return [this.appId, this.appName, this.namespace, key].join();\n  }\n}\n\nexport class InMemoryStorage extends Storage {\n  private storage: { [key: string]: unknown } = {};\n\n  async get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T> {\n    return Promise.resolve(this.storage[key] as T);\n  }\n\n  async set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void> {\n    this.storage[key] = value;\n    return Promise.resolve(undefined);\n  }\n\n  async delete(key: ProjectNamespaceKeyFieldValue): Promise<void> {\n    this.storage[key] = undefined;\n    return Promise.resolve();\n  }\n\n  async setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals> {\n    const storedSignals = (this.storage['custom_signals'] ||\n      {}) as CustomSignals;\n    this.storage['custom_signals'] = mergeCustomSignals(\n      customSignals,\n      storedSignals\n    );\n    return Promise.resolve(this.storage['custom_signals'] as CustomSignals);\n  }\n}\n\nfunction mergeCustomSignals(\n  customSignals: CustomSignals,\n  storedSignals: CustomSignals\n): CustomSignals {\n  const combinedSignals = {\n    ...storedSignals,\n    ...customSignals\n  };\n\n  // Filter out key-value assignments with null values since they are signals being unset\n  const updatedSignals = Object.fromEntries(\n    Object.entries(combinedSignals)\n      .filter(([_, v]) => v !== null)\n      .map(([k, v]) => {\n        // Stringify numbers to store a map of string keys and values which can be sent\n        // as-is in a fetch call.\n        if (typeof v === 'number') {\n          return [k, v.toString()];\n        }\n        return [k, v];\n      })\n  );\n\n  // Throw an error if the number of custom signals to be stored exceeds the limit\n  if (\n    Object.keys(updatedSignals).length > RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS\n  ) {\n    throw ERROR_FACTORY.create(ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS, {\n      maxSignals: RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS\n    });\n  }\n  return updatedSignals;\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 { FetchStatus, CustomSignals } from '@firebase/remote-config-types';\nimport { FirebaseRemoteConfigObject } from '../public_types';\nimport { Storage } from './storage';\n\n/**\n * A memory cache layer over storage to support the SDK's synchronous read requirements.\n */\nexport class StorageCache {\n  constructor(private readonly storage: Storage) {}\n\n  /**\n   * Memory caches.\n   */\n  private lastFetchStatus?: FetchStatus;\n  private lastSuccessfulFetchTimestampMillis?: number;\n  private activeConfig?: FirebaseRemoteConfigObject;\n  private customSignals?: CustomSignals;\n\n  /**\n   * Memory-only getters\n   */\n  getLastFetchStatus(): FetchStatus | undefined {\n    return this.lastFetchStatus;\n  }\n\n  getLastSuccessfulFetchTimestampMillis(): number | undefined {\n    return this.lastSuccessfulFetchTimestampMillis;\n  }\n\n  getActiveConfig(): FirebaseRemoteConfigObject | undefined {\n    return this.activeConfig;\n  }\n\n  getCustomSignals(): CustomSignals | undefined {\n    return this.customSignals;\n  }\n\n  /**\n   * Read-ahead getter\n   */\n  async loadFromStorage(): Promise<void> {\n    const lastFetchStatusPromise = this.storage.getLastFetchStatus();\n    const lastSuccessfulFetchTimestampMillisPromise =\n      this.storage.getLastSuccessfulFetchTimestampMillis();\n    const activeConfigPromise = this.storage.getActiveConfig();\n    const customSignalsPromise = this.storage.getCustomSignals();\n\n    // Note:\n    // 1. we consistently check for undefined to avoid clobbering defined values\n    //   in memory\n    // 2. we defer awaiting to improve readability, as opposed to destructuring\n    //   a Promise.all result, for example\n\n    const lastFetchStatus = await lastFetchStatusPromise;\n    if (lastFetchStatus) {\n      this.lastFetchStatus = lastFetchStatus;\n    }\n\n    const lastSuccessfulFetchTimestampMillis =\n      await lastSuccessfulFetchTimestampMillisPromise;\n    if (lastSuccessfulFetchTimestampMillis) {\n      this.lastSuccessfulFetchTimestampMillis =\n        lastSuccessfulFetchTimestampMillis;\n    }\n\n    const activeConfig = await activeConfigPromise;\n    if (activeConfig) {\n      this.activeConfig = activeConfig;\n    }\n\n    const customSignals = await customSignalsPromise;\n    if (customSignals) {\n      this.customSignals = customSignals;\n    }\n  }\n\n  /**\n   * Write-through setters\n   */\n  setLastFetchStatus(status: FetchStatus): Promise<void> {\n    this.lastFetchStatus = status;\n    return this.storage.setLastFetchStatus(status);\n  }\n\n  setLastSuccessfulFetchTimestampMillis(\n    timestampMillis: number\n  ): Promise<void> {\n    this.lastSuccessfulFetchTimestampMillis = timestampMillis;\n    return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);\n  }\n\n  setActiveConfig(activeConfig: FirebaseRemoteConfigObject): Promise<void> {\n    this.activeConfig = activeConfig;\n    return this.storage.setActiveConfig(activeConfig);\n  }\n\n  async setCustomSignals(customSignals: CustomSignals): Promise<void> {\n    this.customSignals = await this.storage.setCustomSignals(customSignals);\n  }\n}\n","/**\n * @license\n * Copyright 2025 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 { assert } from '@firebase/util';\n\n// TODO: Consolidate the Visibility monitoring API code into a shared utility function in firebase/util to be used by both packages/database and packages/remote-config.\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nexport abstract class EventEmitter {\n  private listeners_: {\n    [eventType: string]: Array<{\n      callback(...args: unknown[]): void;\n      context: unknown;\n    }>;\n  } = {};\n\n  constructor(private allowedEvents_: string[]) {\n    assert(\n      Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n      'Requires a non-empty array'\n    );\n  }\n\n  /**\n   * To be overridden by derived classes in order to fire an initial event when\n   * somebody subscribes for data.\n   *\n   * @returns {Array.<*>} Array of parameters to trigger initial event with.\n   */\n  abstract getInitialEvent(eventType: string): unknown[];\n\n  /**\n   * To be called by derived classes to trigger events.\n   */\n  protected trigger(eventType: string, ...varArgs: unknown[]): void {\n    if (Array.isArray(this.listeners_[eventType])) {\n      // Clone the list, since callbacks could add/remove listeners.\n      const listeners = [...this.listeners_[eventType]];\n\n      for (let i = 0; i < listeners.length; i++) {\n        listeners[i].callback.apply(listeners[i].context, varArgs);\n      }\n    }\n  }\n\n  on(\n    eventType: string,\n    callback: (a: unknown) => void,\n    context: unknown\n  ): void {\n    this.validateEventType_(eventType);\n    this.listeners_[eventType] = this.listeners_[eventType] || [];\n    this.listeners_[eventType].push({ callback, context });\n\n    const eventData = this.getInitialEvent(eventType);\n    if (eventData) {\n      //@ts-ignore\n      callback.apply(context, eventData);\n    }\n  }\n\n  off(\n    eventType: string,\n    callback: (a: unknown) => void,\n    context: unknown\n  ): void {\n    this.validateEventType_(eventType);\n    const listeners = this.listeners_[eventType] || [];\n    for (let i = 0; i < listeners.length; i++) {\n      if (\n        listeners[i].callback === callback &&\n        (!context || context === listeners[i].context)\n      ) {\n        listeners.splice(i, 1);\n        return;\n      }\n    }\n  }\n\n  private validateEventType_(eventType: string): void {\n    assert(\n      this.allowedEvents_.find(et => {\n        return et === eventType;\n      }),\n      'Unknown event: ' + eventType\n    );\n  }\n}\n","/**\n * @license\n * Copyright 2025 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 { assert } from '@firebase/util';\n\nimport { EventEmitter } from './eventEmitter';\n\ndeclare const document: Document;\n\n// TODO: Consolidate the Visibility monitoring API code into a shared utility function in firebase/util to be used by both packages/database and packages/remote-config.\nexport class VisibilityMonitor extends EventEmitter {\n  private visible_: boolean;\n\n  static getInstance(): VisibilityMonitor {\n    return new VisibilityMonitor();\n  }\n\n  constructor() {\n    super(['visible']);\n    let hidden: string;\n    let visibilityChange: string;\n    if (\n      typeof document !== 'undefined' &&\n      typeof document.addEventListener !== 'undefined'\n    ) {\n      if (typeof document['hidden'] !== 'undefined') {\n        // Opera 12.10 and Firefox 18 and later support\n        visibilityChange = 'visibilitychange';\n        hidden = 'hidden';\n      } // @ts-ignore\n      else if (typeof document['mozHidden'] !== 'undefined') {\n        visibilityChange = 'mozvisibilitychange';\n        hidden = 'mozHidden';\n      } // @ts-ignore\n      else if (typeof document['msHidden'] !== 'undefined') {\n        visibilityChange = 'msvisibilitychange';\n        hidden = 'msHidden';\n      } // @ts-ignore\n      else if (typeof document['webkitHidden'] !== 'undefined') {\n        visibilityChange = 'webkitvisibilitychange';\n        hidden = 'webkitHidden';\n      }\n    }\n\n    // Initially, we always assume we are visible. This ensures that in browsers\n    // without page visibility support or in cases where we are never visible\n    // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n    // reconnects\n    this.visible_ = true;\n\n    // @ts-ignore\n    if (visibilityChange) {\n      document.addEventListener(\n        visibilityChange,\n        () => {\n          // @ts-ignore\n          const visible = !document[hidden];\n          if (visible !== this.visible_) {\n            this.visible_ = visible;\n            this.trigger('visible', visible);\n          }\n        },\n        false\n      );\n    }\n  }\n\n  getInitialEvent(eventType: string): boolean[] {\n    assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n    return [this.visible_];\n  }\n}\n","/**\n * @license\n * Copyright 2025 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 { _FirebaseInstallationsInternal } from '@firebase/installations';\nimport { Logger } from '@firebase/logger';\nimport {\n  ConfigUpdate,\n  ConfigUpdateObserver,\n  FetchResponse,\n  FirebaseRemoteConfigObject\n} from '../public_types';\nimport { calculateBackoffMillis, FirebaseError } from '@firebase/util';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { Storage } from '../storage/storage';\nimport { VisibilityMonitor } from './visibility_monitor';\nimport { StorageCache } from '../storage/storage_cache';\nimport {\n  FetchRequest,\n  RemoteConfigAbortSignal\n} from './remote_config_fetch_client';\nimport { CachingClient } from './caching_client';\n\nconst API_KEY_HEADER = 'X-Goog-Api-Key';\nconst INSTALLATIONS_AUTH_TOKEN_HEADER = 'X-Goog-Firebase-Installations-Auth';\nconst ORIGINAL_RETRIES = 8;\nconst MAXIMUM_FETCH_ATTEMPTS = 3;\nconst NO_BACKOFF_TIME_IN_MILLIS = -1;\nconst NO_FAILED_REALTIME_STREAMS = 0;\nconst REALTIME_DISABLED_KEY = 'featureDisabled';\nconst REALTIME_RETRY_INTERVAL = 'retryIntervalSeconds';\nconst TEMPLATE_VERSION_KEY = 'latestTemplateVersionNumber';\n\nexport class RealtimeHandler {\n  constructor(\n    private readonly firebaseInstallations: _FirebaseInstallationsInternal,\n    private readonly storage: Storage,\n    private readonly sdkVersion: string,\n    private readonly namespace: string,\n    private readonly projectId: string,\n    private readonly apiKey: string,\n    private readonly appId: string,\n    private readonly logger: Logger,\n    private readonly storageCache: StorageCache,\n    private readonly cachingClient: CachingClient\n  ) {\n    void this.setRetriesRemaining();\n    void VisibilityMonitor.getInstance().on(\n      'visible',\n      this.onVisibilityChange,\n      this\n    );\n  }\n\n  private observers: Set<ConfigUpdateObserver> =\n    new Set<ConfigUpdateObserver>();\n  private isConnectionActive: boolean = false;\n  private isRealtimeDisabled: boolean = false;\n  private controller?: AbortController;\n  private reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n  private httpRetriesRemaining: number = ORIGINAL_RETRIES;\n  private isInBackground: boolean = false;\n  private readonly decoder = new TextDecoder('utf-8');\n  private isClosingConnection: boolean = false;\n\n  private async setRetriesRemaining(): Promise<void> {\n    // Retrieve number of remaining retries from last session. The minimum retry count being one.\n    const metadata = await this.storage.getRealtimeBackoffMetadata();\n    const numFailedStreams = metadata?.numFailedStreams || 0;\n    this.httpRetriesRemaining = Math.max(\n      ORIGINAL_RETRIES - numFailedStreams,\n      1\n    );\n  }\n\n  private propagateError = (e: FirebaseError): void =>\n    this.observers.forEach(o => o.error?.(e));\n\n  /**\n   * Increment the number of failed stream attempts, increase the backoff duration, set the backoff\n   * end time to \"backoff duration\" after `lastFailedStreamTime` and persist the new\n   * values to storage metadata.\n   */\n  private async updateBackoffMetadataWithLastFailedStreamConnectionTime(\n    lastFailedStreamTime: Date\n  ): Promise<void> {\n    const numFailedStreams =\n      ((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams ||\n        0) + 1;\n    const backoffMillis = calculateBackoffMillis(numFailedStreams, 60000, 2);\n    await this.storage.setRealtimeBackoffMetadata({\n      backoffEndTimeMillis: new Date(\n        lastFailedStreamTime.getTime() + backoffMillis\n      ),\n      numFailedStreams\n    });\n  }\n\n  /**\n   * Increase the backoff duration with a new end time based on Retry Interval.\n   */\n  private async updateBackoffMetadataWithRetryInterval(\n    retryIntervalSeconds: number\n  ): Promise<void> {\n    const currentTime = Date.now();\n    const backoffDurationInMillis = retryIntervalSeconds * 1000;\n    const backoffEndTime = new Date(currentTime + backoffDurationInMillis);\n    const numFailedStreams = 0;\n    await this.storage.setRealtimeBackoffMetadata({\n      backoffEndTimeMillis: backoffEndTime,\n      numFailedStreams\n    });\n    await this.retryHttpConnectionWhenBackoffEnds();\n  }\n\n  /**\n   * HTTP status code that the Realtime client should retry on.\n   */\n  private isStatusCodeRetryable = (statusCode?: number): boolean => {\n    const retryableStatusCodes = [\n      408, // Request Timeout\n      429, // Too Many Requests\n      502, // Bad Gateway\n      503, // Service Unavailable\n      504 // Gateway Timeout\n    ];\n    return !statusCode || retryableStatusCodes.includes(statusCode);\n  };\n\n  /**\n   * Closes the realtime HTTP connection.\n   * Note: This method is designed to be called only once at a time.\n   * If a call is already in progress, subsequent calls will be ignored.\n   */\n  private async closeRealtimeHttpConnection(): Promise<void> {\n    if (this.isClosingConnection) {\n      return;\n    }\n    this.isClosingConnection = true;\n\n    try {\n      if (this.reader) {\n        await this.reader.cancel();\n      }\n    } catch (e) {\n      // The network connection was lost, so cancel() failed.\n      // This is expected in a disconnected state, so we can safely ignore the error.\n      this.logger.debug('Failed to cancel the reader, connection was lost.');\n    } finally {\n      this.reader = undefined;\n    }\n\n    if (this.controller) {\n      await this.controller.abort();\n      this.controller = undefined;\n    }\n\n    this.isClosingConnection = false;\n  }\n\n  private async resetRealtimeBackoff(): Promise<void> {\n    await this.storage.setRealtimeBackoffMetadata({\n      backoffEndTimeMillis: new Date(-1),\n      numFailedStreams: 0\n    });\n  }\n\n  private resetRetryCount(): void {\n    this.httpRetriesRemaining = ORIGINAL_RETRIES;\n  }\n\n  /**\n   * Assembles the request headers and body and executes the fetch request to\n   * establish the real-time streaming connection. This is the \"worker\" method\n   * that performs the actual network communication.\n   */\n  private async establishRealtimeConnection(\n    url: URL,\n    installationId: string,\n    installationTokenResult: string,\n    signal: AbortSignal\n  ): Promise<Response> {\n    const eTagValue = await this.storage.getActiveConfigEtag();\n    const lastKnownVersionNumber =\n      await this.storage.getActiveConfigTemplateVersion();\n\n    const headers = {\n      [API_KEY_HEADER]: this.apiKey,\n      [INSTALLATIONS_AUTH_TOKEN_HEADER]: installationTokenResult,\n      'Content-Type': 'application/json',\n      'Accept': 'application/json',\n      'If-None-Match': eTagValue || '*',\n      'Content-Encoding': 'gzip'\n    };\n\n    const requestBody = {\n      project: this.projectId,\n      namespace: this.namespace,\n      lastKnownVersionNumber,\n      appId: this.appId,\n      sdkVersion: this.sdkVersion,\n      appInstanceId: installationId\n    };\n\n    const response = await fetch(url, {\n      method: 'POST',\n      headers,\n      body: JSON.stringify(requestBody),\n      signal\n    });\n    return response;\n  }\n\n  private getRealtimeUrl(): URL {\n    const urlBase =\n      window.FIREBASE_REMOTE_CONFIG_URL_BASE ||\n      'https://firebaseremoteconfigrealtime.googleapis.com';\n\n    const urlString = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;\n    return new URL(urlString);\n  }\n\n  private async createRealtimeConnection(): Promise<Response> {\n    const [installationId, installationTokenResult] = await Promise.all([\n      this.firebaseInstallations.getId(),\n      this.firebaseInstallations.getToken(false)\n    ]);\n    this.controller = new AbortController();\n    const url = this.getRealtimeUrl();\n    const realtimeConnection = await this.establishRealtimeConnection(\n      url,\n      installationId,\n      installationTokenResult,\n      this.controller.signal\n    );\n    return realtimeConnection;\n  }\n\n  /**\n   * Retries HTTP stream connection asyncly in random time intervals.\n   */\n  private async retryHttpConnectionWhenBackoffEnds(): Promise<void> {\n    let backoffMetadata = await this.storage.getRealtimeBackoffMetadata();\n    if (!backoffMetadata) {\n      backoffMetadata = {\n        backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS),\n        numFailedStreams: NO_FAILED_REALTIME_STREAMS\n      };\n    }\n    const backoffEndTime = new Date(\n      backoffMetadata.backoffEndTimeMillis\n    ).getTime();\n    const currentTime = Date.now();\n    const retryMillis = Math.max(0, backoffEndTime - currentTime);\n    await this.makeRealtimeHttpConnection(retryMillis);\n  }\n\n  private setIsHttpConnectionRunning(connectionRunning: boolean): void {\n    this.isConnectionActive = connectionRunning;\n  }\n\n  /**\n   * Combines the check and set operations to prevent multiple asynchronous\n   * calls from redundantly starting an HTTP connection. This ensures that\n   * only one attempt is made at a time.\n   */\n  private checkAndSetHttpConnectionFlagIfNotRunning(): boolean {\n    const canMakeConnection = this.canEstablishStreamConnection();\n    if (canMakeConnection) {\n      this.setIsHttpConnectionRunning(true);\n    }\n    return canMakeConnection;\n  }\n\n  private fetchResponseIsUpToDate(\n    fetchResponse: FetchResponse,\n    lastKnownVersion: number\n  ): boolean {\n    // If there is a config, make sure its version is >= the last known version.\n    if (fetchResponse.config != null && fetchResponse.templateVersion) {\n      return fetchResponse.templateVersion >= lastKnownVersion;\n    }\n    // If there isn't a config, return true if the fetch was successful and backend had no update.\n    // Else, it returned an out of date config.\n    return this.storageCache.getLastFetchStatus() === 'success';\n  }\n\n  private parseAndValidateConfigUpdateMessage(message: string): string {\n    const left = message.indexOf('{');\n    const right = message.indexOf('}', left);\n\n    if (left < 0 || right < 0) {\n      return '';\n    }\n    return left >= right ? '' : message.substring(left, right + 1);\n  }\n\n  private isEventListenersEmpty(): boolean {\n    return this.observers.size === 0;\n  }\n\n  private getRandomInt(max: number): number {\n    return Math.floor(Math.random() * max);\n  }\n\n  private executeAllListenerCallbacks(configUpdate: ConfigUpdate): void {\n    this.observers.forEach(observer => observer.next(configUpdate));\n  }\n\n  /**\n   * Compares two configuration objects and returns a set of keys that have changed.\n   * A key is considered changed if it's new, removed, or has a different value.\n   */\n  private getChangedParams(\n    newConfig: FirebaseRemoteConfigObject,\n    oldConfig: FirebaseRemoteConfigObject\n  ): Set<string> {\n    const changedKeys = new Set<string>();\n    const newKeys = new Set(Object.keys(newConfig || {}));\n    const oldKeys = new Set(Object.keys(oldConfig || {}));\n\n    for (const key of newKeys) {\n      if (!oldKeys.has(key) || newConfig[key] !== oldConfig[key]) {\n        changedKeys.add(key);\n      }\n    }\n\n    for (const key of oldKeys) {\n      if (!newKeys.has(key)) {\n        changedKeys.add(key);\n      }\n    }\n\n    return changedKeys;\n  }\n\n  private async fetchLatestConfig(\n    remainingAttempts: number,\n    targetVersion: number\n  ): Promise<void> {\n    const remainingAttemptsAfterFetch = remainingAttempts - 1;\n    const currentAttempt = MAXIMUM_FETCH_ATTEMPTS - remainingAttemptsAfterFetch;\n    const customSignals = this.storageCache.getCustomSignals();\n    if (customSignals) {\n      this.logger.debug(\n        `Fetching config with custom signals: ${JSON.stringify(customSignals)}`\n      );\n    }\n    const abortSignal = new RemoteConfigAbortSignal();\n    try {\n      const fetchRequest: FetchRequest = {\n        cacheMaxAgeMillis: 0,\n        signal: abortSignal,\n        customSignals,\n        fetchType: 'REALTIME',\n        fetchAttempt: currentAttempt\n      };\n\n      const fetchResponse: FetchResponse = await this.cachingClient.fetch(\n        fetchRequest\n      );\n      let activatedConfigs = await this.storage.getActiveConfig();\n\n      if (!this.fetchResponseIsUpToDate(fetchResponse, targetVersion)) {\n        this.logger.debug(\n          \"Fetched template version is the same as SDK's current version.\" +\n            ' Retrying fetch.'\n        );\n        // Continue fetching until template version number is greater than current.\n        await this.autoFetch(remainingAttemptsAfterFetch, targetVersion);\n        return;\n      }\n\n      if (fetchResponse.config == null) {\n        this.logger.debug(\n          'The fetch succeeded, but the backend had no updates.'\n        );\n        return;\n      }\n\n      if (activatedConfigs == null) {\n        activatedConfigs = {};\n      }\n\n      const updatedKeys = this.getChangedParams(\n        fetchResponse.config,\n        activatedConfigs\n      );\n\n      if (updatedKeys.size === 0) {\n        this.logger.debug('Config was fetched, but no params changed.');\n        return;\n      }\n\n      const configUpdate: ConfigUpdate = {\n        getUpdatedKeys(): Set<string> {\n          return new Set(updatedKeys);\n        }\n      };\n      this.executeAllListenerCallbacks(configUpdate);\n    } catch (e: unknown) {\n      const errorMessage = e instanceof Error ? e.message : String(e);\n      const error = ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_NOT_FETCHED, {\n        originalErrorMessage: `Failed to auto-fetch config update: ${errorMessage}`\n      });\n      this.propagateError(error);\n    }\n  }\n\n  private async autoFetch(\n    remainingAttempts: number,\n    targetVersion: number\n  ): Promise<void> {\n    if (remainingAttempts === 0) {\n      const error = ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_NOT_FETCHED, {\n        originalErrorMessage:\n          'Unable to fetch the latest version of the template.'\n      });\n      this.propagateError(error);\n      return;\n    }\n\n    const timeTillFetchSeconds = this.getRandomInt(4);\n    const timeTillFetchInMiliseconds = timeTillFetchSeconds * 1000;\n\n    await new Promise(resolve =>\n      setTimeout(resolve, timeTillFetchInMiliseconds)\n    );\n    await this.fetchLatestConfig(remainingAttempts, targetVersion);\n  }\n\n  /**\n   * Processes a stream of real-time messages for configuration updates.\n   * This method reassembles fragmented messages, validates and parses the JSON,\n   * and automatically fetches a new config if a newer template version is available.\n   * It also handles server-specified retry intervals and propagates errors for\n   * invalid messages or when real-time updates are disabled.\n   */\n  private async handleNotifications(\n    reader: ReadableStreamDefaultReader<Uint8Array>\n  ): Promise<void> {\n    let partialConfigUpdateMessage: string;\n    let currentConfigUpdateMessage = '';\n\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) {\n        break;\n      }\n\n      partialConfigUpdateMessage = this.decoder.decode(value, { stream: true });\n      currentConfigUpdateMessage += partialConfigUpdateMessage;\n\n      if (partialConfigUpdateMessage.includes('}')) {\n        currentConfigUpdateMessage = this.parseAndValidateConfigUpdateMessage(\n          currentConfigUpdateMessage\n        );\n\n        if (currentConfigUpdateMessage.length === 0) {\n          continue;\n        }\n\n        try {\n          const jsonObject = JSON.parse(currentConfigUpdateMessage);\n\n          if (this.isEventListenersEmpty()) {\n            break;\n          }\n\n          if (\n            REALTIME_DISABLED_KEY in jsonObject &&\n            jsonObject[REALTIME_DISABLED_KEY] === true\n          ) {\n            const error = ERROR_FACTORY.create(\n              ErrorCode.CONFIG_UPDATE_UNAVAILABLE,\n              {\n                originalErrorMessage:\n                  'The server is temporarily unavailable. Try again in a few minutes.'\n              }\n            );\n            this.propagateError(error);\n            break;\n          }\n\n          if (TEMPLATE_VERSION_KEY in jsonObject) {\n            const oldTemplateVersion =\n              await this.storage.getActiveConfigTemplateVersion();\n            const targetTemplateVersion = Number(\n              jsonObject[TEMPLATE_VERSION_KEY]\n            );\n            if (\n              oldTemplateVersion &&\n              targetTemplateVersion > oldTemplateVersion\n            ) {\n              await this.autoFetch(\n                MAXIMUM_FETCH_ATTEMPTS,\n                targetTemplateVersion\n              );\n            }\n          }\n\n          // This field in the response indicates that the realtime request should retry after the\n          // specified interval to establish a long-lived connection. This interval extends the\n          // backoff duration without affecting the number of retries, so it will not enter an\n          // exponential backoff state.\n          if (REALTIME_RETRY_INTERVAL in jsonObject) {\n            const retryIntervalSeconds = Number(\n              jsonObject[REALTIME_RETRY_INTERVAL]\n            );\n            await this.updateBackoffMetadataWithRetryInterval(\n              retryIntervalSeconds\n            );\n          }\n        } catch (e: unknown) {\n          this.logger.debug('Unable to parse latest config update message.', e);\n          const errorMessage = e instanceof Error ? e.message : String(e);\n          this.propagateError(\n            ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID, {\n              originalErrorMessage: errorMessage\n            })\n          );\n        }\n        currentConfigUpdateMessage = '';\n      }\n    }\n  }\n\n  private async listenForNotifications(\n    reader: ReadableStreamDefaultReader\n  ): Promise<void> {\n    try {\n      await this.handleNotifications(reader);\n    } catch (e) {\n      // If the real-time connection is at an unexpected lifecycle state when the app is\n      // backgrounded, it's expected closing the connection will throw an exception.\n      if (!this.isInBackground) {\n        // Otherwise, the real-time server connection was closed due to a transient issue.\n        this.logger.debug(\n          'Real-time connection was closed due to an exception.'\n        );\n      }\n    }\n  }\n\n  /**\n   * Open the real-time connection, begin listening for updates, and auto-fetch when an update is\n   * received.\n   *\n   * If the connection is successful, this method will block on its thread while it reads the\n   * chunk-encoded HTTP body. When the connection closes, it attempts to reestablish the stream.\n   */\n  private async prepareAndBeginRealtimeHttpStream(): Promise<void> {\n    if (!this.checkAndSetHttpConnectionFlagIfNotRunning()) {\n      return;\n    }\n\n    let backoffMetadata = await this.storage.getRealtimeBackoffMetadata();\n    if (!backoffMetadata) {\n      backoffMetadata = {\n        backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS),\n        numFailedStreams: NO_FAILED_REALTIME_STREAMS\n      };\n    }\n    const backoffEndTime = backoffMetadata.backoffEndTimeMillis.getTime();\n    if (Date.now() < backoffEndTime) {\n      await this.retryHttpConnectionWhenBackoffEnds();\n      return;\n    }\n\n    let response: Response | undefined;\n    let responseCode: number | undefined;\n    try {\n      response = await this.createRealtimeConnection();\n      responseCode = response.status;\n      if (response.ok && response.body) {\n        this.resetRetryCount();\n        await this.resetRealtimeBackoff();\n        const reader = response.body.getReader();\n        this.reader = reader;\n        // Start listening for realtime notifications.\n        await this.listenForNotifications(reader);\n      }\n    } catch (error) {\n      if (this.isInBackground) {\n        // It's possible the app was backgrounded while the connection was open, which\n        // threw an exception trying to read the response. No real error here, so treat\n        // this as a success, even if we haven't read a 200 response code yet.\n        this.resetRetryCount();\n      } else {\n        //there might have been a transient error so the client will retry the connection.\n        this.logger.debug(\n          'Exception connecting to real-time RC backend. Retrying the connection...:',\n          error\n        );\n      }\n    } finally {\n      // Close HTTP connection and associated streams.\n      await this.closeRealtimeHttpConnection();\n      this.setIsHttpConnectionRunning(false);\n\n      // Update backoff metadata if the connection failed in the foreground.\n      const connectionFailed =\n        !this.isInBackground &&\n        (responseCode === undefined ||\n          this.isStatusCodeRetryable(responseCode));\n\n      if (connectionFailed) {\n        await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(\n          new Date()\n        );\n      }\n      // If responseCode is null then no connection was made to server and the SDK should still retry.\n      if (connectionFailed || response?.ok) {\n        await this.retryHttpConnectionWhenBackoffEnds();\n      } else {\n        const errorMessage = `Unable to connect to the server. HTTP status code: ${responseCode}`;\n        const firebaseError = ERROR_FACTORY.create(\n          ErrorCode.CONFIG_UPDATE_STREAM_ERROR,\n          {\n            originalErrorMessage: errorMessage\n          }\n        );\n        this.propagateError(firebaseError);\n      }\n    }\n  }\n\n  /**\n   * Checks whether connection can be made or not based on some conditions\n   * @returns booelean\n   */\n  private canEstablishStreamConnection(): boolean {\n    const hasActiveListeners = this.observers.size > 0;\n    const isNotDisabled = !this.isRealtimeDisabled;\n    const isNoConnectionActive = !this.isConnectionActive;\n    const inForeground = !this.isInBackground;\n    return (\n      hasActiveListeners &&\n      isNotDisabled &&\n      isNoConnectionActive &&\n      inForeground\n    );\n  }\n\n  private async makeRealtimeHttpConnection(delayMillis: number): Promise<void> {\n    if (!this.canEstablishStreamConnection()) {\n      return;\n    }\n    if (this.httpRetriesRemaining > 0) {\n      this.httpRetriesRemaining--;\n      await new Promise(resolve => setTimeout(resolve, delayMillis));\n      void this.prepareAndBeginRealtimeHttpStream();\n    } else if (!this.isInBackground) {\n      const error = ERROR_FACTORY.create(ErrorCode.CONFIG_UPDATE_STREAM_ERROR, {\n        originalErrorMessage:\n          'Unable to connect to the server. Check your connection and try again.'\n      });\n      this.propagateError(error);\n    }\n  }\n\n  private async beginRealtime(): Promise<void> {\n    if (this.observers.size > 0) {\n      await this.makeRealtimeHttpConnection(0);\n    }\n  }\n\n  /**\n   * Adds an observer to the realtime updates.\n   * @param observer The observer to add.\n   */\n  addObserver(observer: ConfigUpdateObserver): void {\n    this.observers.add(observer);\n    void this.beginRealtime();\n  }\n\n  /**\n   * Removes an observer from the realtime updates.\n   * @param observer The observer to remove.\n   */\n  removeObserver(observer: ConfigUpdateObserver): void {\n    if (this.observers.has(observer)) {\n      this.observers.delete(observer);\n    }\n  }\n\n  /**\n   * Handles changes to the application's visibility state, managing the real-time connection.\n   *\n   * When the application is moved to the background, this method closes the existing\n   * real-time connection to save resources. When the application returns to the\n   * foreground, it attempts to re-establish the connection.\n   */\n  private async onVisibilityChange(visible: unknown): Promise<void> {\n    this.isInBackground = !visible;\n    if (!visible) {\n      await this.closeRealtimeHttpConnection();\n    } else if (visible) {\n      await this.beginRealtime();\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 */\nimport {\n  _registerComponent,\n  registerVersion,\n  SDK_VERSION\n} from '@firebase/app';\nimport { isIndexedDBAvailable } from '@firebase/util';\nimport {\n  Component,\n  ComponentType,\n  ComponentContainer\n} from '@firebase/component';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { RemoteConfig, RemoteConfigOptions } from './public_types';\nimport { name as packageName, version } from '../package.json';\nimport { ensureInitialized } from './api';\nimport { CachingClient } from './client/caching_client';\nimport { RestClient } from './client/rest_client';\nimport { RetryingClient } from './client/retrying_client';\nimport { RC_COMPONENT_NAME } from './constants';\nimport { ErrorCode, ERROR_FACTORY } from './errors';\nimport { RemoteConfig as RemoteConfigImpl } from './remote_config';\nimport { IndexedDbStorage, InMemoryStorage } from './storage/storage';\nimport { StorageCache } from './storage/storage_cache';\nimport { RealtimeHandler } from './client/realtime_handler';\n// This needs to be in the same file that calls `getProvider()` on the component\n// or it will get tree-shaken out.\nimport '@firebase/installations';\n\nexport function registerRemoteConfig(): void {\n  _registerComponent(\n    new Component(\n      RC_COMPONENT_NAME,\n      remoteConfigFactory,\n      ComponentType.PUBLIC\n    ).setMultipleInstances(true)\n  );\n\n  registerVersion(packageName, version);\n  // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation\n  registerVersion(packageName, version, '__BUILD_TARGET__');\n\n  function remoteConfigFactory(\n    container: ComponentContainer,\n    { options }: { options?: RemoteConfigOptions }\n  ): RemoteConfig {\n    /* Dependencies */\n    // getImmediate for FirebaseApp will always succeed\n    const app = container.getProvider('app').getImmediate();\n    // The following call will always succeed because rc has `import '@firebase/installations'`\n    const installations = container\n      .getProvider('installations-internal')\n      .getImmediate();\n    const analyticsProvider = container.getProvider('analytics-internal');\n\n    // Normalizes optional inputs.\n    const { projectId, apiKey, appId } = app.options;\n    if (!projectId) {\n      throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_PROJECT_ID);\n    }\n    if (!apiKey) {\n      throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_API_KEY);\n    }\n    if (!appId) {\n      throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_APP_ID);\n    }\n    const namespace = options?.templateId || 'firebase';\n\n    const storage = isIndexedDBAvailable()\n      ? new IndexedDbStorage(appId, app.name, namespace)\n      : new InMemoryStorage();\n    const storageCache = new StorageCache(storage);\n\n    const logger = new Logger(packageName);\n\n    // Sets ERROR as the default log level.\n    // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.\n    logger.logLevel = FirebaseLogLevel.ERROR;\n\n    const restClient = new RestClient(\n      installations,\n      // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.\n      SDK_VERSION,\n      namespace,\n      projectId,\n      apiKey,\n      appId\n    );\n    const retryingClient = new RetryingClient(restClient, storage);\n    const cachingClient = new CachingClient(\n      retryingClient,\n      storage,\n      storageCache,\n      logger\n    );\n\n    const realtimeHandler = new RealtimeHandler(\n      installations,\n      storage,\n      SDK_VERSION,\n      namespace,\n      projectId,\n      apiKey,\n      appId,\n      logger,\n      storageCache,\n      cachingClient\n    );\n\n    const remoteConfigInstance = new RemoteConfigImpl(\n      app,\n      cachingClient,\n      storageCache,\n      storage,\n      logger,\n      realtimeHandler,\n      analyticsProvider\n    );\n\n    // Starts warming cache.\n    // eslint-disable-next-line @typescript-eslint/no-floating-promises\n    ensureInitialized(remoteConfigInstance);\n\n    return remoteConfigInstance;\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 { RemoteConfig } from './public_types';\nimport { activate, fetchConfig } from './api';\nimport {\n  getModularInstance,\n  isIndexedDBAvailable,\n  validateIndexedDBOpenable\n} from '@firebase/util';\n\n// This API is put in a separate file, so we can stub fetchConfig and activate in tests.\n// It's not possible to stub standalone functions from the same module.\n/**\n *\n * Performs fetch and activate operations, as a convenience.\n *\n * @param remoteConfig - The {@link RemoteConfig} instance.\n *\n * @returns A `Promise` which resolves to true if the current call activated the fetched configs.\n * If the fetched configs were already activated, the `Promise` will resolve to false.\n *\n * @public\n */\nexport async function fetchAndActivate(\n  remoteConfig: RemoteConfig\n): Promise<boolean> {\n  remoteConfig = getModularInstance(remoteConfig);\n  await fetchConfig(remoteConfig);\n  return activate(remoteConfig);\n}\n\n/**\n * This method provides two different checks:\n *\n * 1. Check if IndexedDB exists in the browser environment.\n * 2. Check if the current browser context allows IndexedDB `open()` calls.\n *\n * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance\n * can be initialized in this environment, or false if it cannot.\n * @public\n */\nexport async function isSupported(): Promise<boolean> {\n  if (!isIndexedDBAvailable()) {\n    return false;\n  }\n\n  try {\n    const isDBOpenable: boolean = await validateIndexedDBOpenable();\n    return isDBOpenable;\n  } catch (error) {\n    return false;\n  }\n}\n","/**\n * The Firebase Remote Config Web SDK.\n * This SDK does not work in a Node.js environment.\n *\n * @packageDocumentation\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 { registerRemoteConfig } from './register';\n\n// Facilitates debugging by enabling settings changes without rebuilding asset.\n// Note these debug options are not part of a documented, supported API and can change at any time.\n// Consolidates debug options for easier discovery.\n// Uses transient variables on window to avoid lingering state causing panic.\ndeclare global {\n  interface Window {\n    FIREBASE_REMOTE_CONFIG_URL_BASE: string;\n  }\n}\n\nexport * from './api';\nexport * from './api2';\nexport * from './public_types';\n\n/** register component and version */\nregisterRemoteConfig();\n"]}