diff options
Diffstat (limited to 'frontend-old/node_modules/@firebase/remote-config')
51 files changed, 8519 insertions, 0 deletions
diff --git a/frontend-old/node_modules/@firebase/remote-config/README.md b/frontend-old/node_modules/@firebase/remote-config/README.md new file mode 100644 index 0000000..1b21bbe --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/README.md @@ -0,0 +1,27 @@ +# @firebase/remote-config + +This is the [Remote Config](https://firebase.google.com/docs/remote-config/) component of the +[Firebase JS SDK](https://www.npmjs.com/package/firebase). + +**This package is not intended for direct usage, and should only be used via the officially +supported [firebase](https://www.npmjs.com/package/firebase) package.** + +## Contributing + +Setup: + +1. Run `yarn` in repo root + +Format: + +1. Run `yarn prettier` in RC package + +Unit test: + +1. Run `yarn test` in RC package + +End-to-end test: + +1. Run `yarn build` in RC package +1. Run `yarn build` in Firebase package +1. Open test_app/index.html in a browser diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js b/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js new file mode 100644 index 0000000..efaf7cb --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js @@ -0,0 +1,2120 @@ +import { _getProvider, getApp, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app'; +import { ErrorFactory, FirebaseError, getModularInstance, deepEqual, calculateBackoffMillis, assert, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util'; +import { Component } from '@firebase/component'; +import { LogLevel, Logger } from '@firebase/logger'; +import '@firebase/installations'; + +const name = "@firebase/remote-config"; +const version = "0.7.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Shims a minimal AbortSignal. + * + * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects + * of networking, such as retries. Firebase doesn't use AbortController enough to justify a + * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be + * swapped out if/when we do. + */ +class RemoteConfigAbortSignal { + constructor() { + this.listeners = []; + } + addEventListener(listener) { + this.listeners.push(listener); + } + abort() { + this.listeners.forEach(listener => listener()); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RC_COMPONENT_NAME = 'remote-config'; +const RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 100; +const RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH = 250; +const RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH = 500; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ERROR_DESCRIPTION_MAP = { + ["already-initialized" /* ErrorCode.ALREADY_INITIALIZED */]: 'Remote Config already initialized', + ["registration-window" /* ErrorCode.REGISTRATION_WINDOW */]: 'Undefined window object. This SDK only supports usage in a browser environment.', + ["registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */]: 'Undefined project identifier. Check Firebase app initialization.', + ["registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */]: 'Undefined API key. Check Firebase app initialization.', + ["registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */]: 'Undefined app identifier. Check Firebase app initialization.', + ["storage-open" /* ErrorCode.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.', + ["storage-get" /* ErrorCode.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.', + ["storage-set" /* ErrorCode.STORAGE_SET */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.', + ["storage-delete" /* ErrorCode.STORAGE_DELETE */]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.', + ["fetch-client-network" /* ErrorCode.FETCH_NETWORK */]: 'Fetch client failed to connect to a network. Check Internet connection.' + + ' Original error: {$originalErrorMessage}.', + ["fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */]: 'The config fetch request timed out. ' + + ' Configure timeout using "fetchTimeoutMillis" SDK setting.', + ["fetch-throttle" /* ErrorCode.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' + + ' Configure timeout using "fetchTimeoutMillis" SDK setting.' + + ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.', + ["fetch-client-parse" /* ErrorCode.FETCH_PARSE */]: 'Fetch client could not parse response.' + + ' Original error: {$originalErrorMessage}.', + ["fetch-status" /* ErrorCode.FETCH_STATUS */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.', + ["indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */]: 'Indexed DB is not supported by current browser', + ["custom-signal-max-allowed-signals" /* ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS */]: 'Setting more than {$maxSignals} custom signals is not supported.', + ["stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */]: 'The stream was not able to connect to the backend: {$originalErrorMessage}.', + ["realtime-unavailable" /* ErrorCode.CONFIG_UPDATE_UNAVAILABLE */]: 'The Realtime service is unavailable: {$originalErrorMessage}', + ["update-message-invalid" /* ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID */]: 'The stream invalidation message was unparsable: {$originalErrorMessage}', + ["update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */]: 'Unable to fetch the latest config: {$originalErrorMessage}' +}; +const ERROR_FACTORY = new ErrorFactory('remoteconfig' /* service */, 'Remote Config' /* service name */, ERROR_DESCRIPTION_MAP); +// Note how this is like typeof/instanceof, but for ErrorCode. +function hasErrorCode(e, errorCode) { + return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_VALUE_FOR_BOOLEAN = false; +const DEFAULT_VALUE_FOR_STRING = ''; +const DEFAULT_VALUE_FOR_NUMBER = 0; +const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on']; +class Value { + constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) { + this._source = _source; + this._value = _value; + } + asString() { + return this._value; + } + asBoolean() { + if (this._source === 'static') { + return DEFAULT_VALUE_FOR_BOOLEAN; + } + return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0; + } + asNumber() { + if (this._source === 'static') { + return DEFAULT_VALUE_FOR_NUMBER; + } + let num = Number(this._value); + if (isNaN(num)) { + num = DEFAULT_VALUE_FOR_NUMBER; + } + return num; + } + getSource() { + return this._source; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +function getRemoteConfig(app = getApp(), options = {}) { + app = getModularInstance(app); + const rcProvider = _getProvider(app, RC_COMPONENT_NAME); + if (rcProvider.isInitialized()) { + const initialOptions = rcProvider.getOptions(); + if (deepEqual(initialOptions, options)) { + return rcProvider.getImmediate(); + } + throw ERROR_FACTORY.create("already-initialized" /* ErrorCode.ALREADY_INITIALIZED */); + } + rcProvider.initialize({ options }); + const rc = rcProvider.getImmediate(); + if (options.initialFetchResponse) { + // We use these initial writes as the initialization promise since they will hydrate the same + // fields that `storageCache.loadFromStorage` would set. + rc._initializePromise = Promise.all([ + rc._storage.setLastSuccessfulFetchResponse(options.initialFetchResponse), + rc._storage.setActiveConfigEtag(options.initialFetchResponse?.eTag || ''), + rc._storage.setActiveConfigTemplateVersion(options.initialFetchResponse.templateVersion || 0), + rc._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()), + rc._storageCache.setLastFetchStatus('success'), + rc._storageCache.setActiveConfig(options.initialFetchResponse?.config || {}) + ]).then(); + // The `storageCache` methods above set their in-memory fields synchronously, so it's + // safe to declare our initialization complete at this point. + rc._isInitializationComplete = true; + } + return rc; +} +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +async function activate(remoteConfig) { + const rc = getModularInstance(remoteConfig); + const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([ + rc._storage.getLastSuccessfulFetchResponse(), + rc._storage.getActiveConfigEtag() + ]); + if (!lastSuccessfulFetchResponse || + !lastSuccessfulFetchResponse.config || + !lastSuccessfulFetchResponse.eTag || + !lastSuccessfulFetchResponse.templateVersion || + lastSuccessfulFetchResponse.eTag === activeConfigEtag) { + // Either there is no successful fetched config, or is the same as current active + // config. + return false; + } + await Promise.all([ + rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config), + rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag), + rc._storage.setActiveConfigTemplateVersion(lastSuccessfulFetchResponse.templateVersion) + ]); + return true; +} +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +function ensureInitialized(remoteConfig) { + const rc = getModularInstance(remoteConfig); + if (!rc._initializePromise) { + rc._initializePromise = rc._storageCache.loadFromStorage().then(() => { + rc._isInitializationComplete = true; + }); + } + return rc._initializePromise; +} +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +async function fetchConfig(remoteConfig) { + const rc = getModularInstance(remoteConfig); + // Aborts the request after the given timeout, causing the fetch call to + // reject with an `AbortError`. + // + // <p>Aborting after the request completes is a no-op, so we don't need a + // corresponding `clearTimeout`. + // + // Locating abort logic here because: + // * it uses a developer setting (timeout) + // * it applies to all retries (like curl's max-time arg) + // * it is consistent with the Fetch API's signal input + const abortSignal = new RemoteConfigAbortSignal(); + setTimeout(async () => { + // Note a very low delay, eg < 10ms, can elapse before listeners are initialized. + abortSignal.abort(); + }, rc.settings.fetchTimeoutMillis); + const customSignals = rc._storageCache.getCustomSignals(); + if (customSignals) { + rc._logger.debug(`Fetching config with custom signals: ${JSON.stringify(customSignals)}`); + } + // Catches *all* errors thrown by client so status can be set consistently. + try { + await rc._client.fetch({ + cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis, + signal: abortSignal, + customSignals + }); + await rc._storageCache.setLastFetchStatus('success'); + } + catch (e) { + const lastFetchStatus = hasErrorCode(e, "fetch-throttle" /* ErrorCode.FETCH_THROTTLE */) + ? 'throttle' + : 'failure'; + await rc._storageCache.setLastFetchStatus(lastFetchStatus); + throw e; + } +} +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +function getAll(remoteConfig) { + const rc = getModularInstance(remoteConfig); + return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => { + allConfigs[key] = getValue(remoteConfig, key); + return allConfigs; + }, {}); +} +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +function getBoolean(remoteConfig, key) { + return getValue(getModularInstance(remoteConfig), key).asBoolean(); +} +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +function getNumber(remoteConfig, key) { + return getValue(getModularInstance(remoteConfig), key).asNumber(); +} +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +function getString(remoteConfig, key) { + return getValue(getModularInstance(remoteConfig), key).asString(); +} +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +function getValue(remoteConfig, key) { + const rc = getModularInstance(remoteConfig); + if (!rc._isInitializationComplete) { + rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` + + ' Await on ensureInitialized if the intent was to get a previously activated value.'); + } + const activeConfig = rc._storageCache.getActiveConfig(); + if (activeConfig && activeConfig[key] !== undefined) { + return new Value('remote', activeConfig[key]); + } + else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) { + return new Value('default', String(rc.defaultConfig[key])); + } + rc._logger.debug(`Returning static value for key "${key}".` + + ' Define a default or remote value if this is unintentional.'); + return new Value('static'); +} +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +function setLogLevel(remoteConfig, logLevel) { + const rc = getModularInstance(remoteConfig); + switch (logLevel) { + case 'debug': + rc._logger.logLevel = LogLevel.DEBUG; + break; + case 'silent': + rc._logger.logLevel = LogLevel.SILENT; + break; + default: + rc._logger.logLevel = LogLevel.ERROR; + } +} +/** + * Dedupes and returns an array of all the keys of the received objects. + */ +function getAllKeys(obj1 = {}, obj2 = {}) { + return Object.keys({ ...obj1, ...obj2 }); +} +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +async function setCustomSignals(remoteConfig, customSignals) { + const rc = getModularInstance(remoteConfig); + if (Object.keys(customSignals).length === 0) { + return; + } + // eslint-disable-next-line guard-for-in + for (const key in customSignals) { + if (key.length > RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH) { + rc._logger.error(`Custom signal key ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH}.`); + return; + } + const value = customSignals[key]; + if (typeof value === 'string' && + value.length > RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH) { + rc._logger.error(`Value supplied for custom signal ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH}.`); + return; + } + } + try { + await rc._storageCache.setCustomSignals(customSignals); + } + catch (error) { + rc._logger.error(`Error encountered while setting custom signals: ${error}`); + } +} +// TODO: Add public document for the Remote Config Realtime API guide on the Web Platform. +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +function onConfigUpdate(remoteConfig, observer) { + const rc = getModularInstance(remoteConfig); + rc._realtimeHandler.addObserver(observer); + return () => { + rc._realtimeHandler.removeObserver(observer); + }; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implements the {@link RemoteConfigClient} abstraction with success response caching. + * + * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service + * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the + * Cache API doesn't support matching entries by time. + */ +class CachingClient { + constructor(client, storage, storageCache, logger) { + this.client = client; + this.storage = storage; + this.storageCache = storageCache; + this.logger = logger; + } + /** + * Returns true if the age of the cached fetched configs is less than or equal to + * {@link Settings#minimumFetchIntervalInSeconds}. + * + * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the + * native Fetch API. + * + * <p>Visible for testing. + */ + isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) { + // Cache can only be fresh if it's populated. + if (!lastSuccessfulFetchTimestampMillis) { + this.logger.debug('Config fetch cache check. Cache unpopulated.'); + return false; + } + // Calculates age of cache entry. + const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis; + const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis; + this.logger.debug('Config fetch cache check.' + + ` Cache age millis: ${cacheAgeMillis}.` + + ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` + + ` Is cache hit: ${isCachedDataFresh}.`); + return isCachedDataFresh; + } + async fetch(request) { + // Reads from persisted storage to avoid cache miss if callers don't wait on initialization. + const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([ + this.storage.getLastSuccessfulFetchTimestampMillis(), + this.storage.getLastSuccessfulFetchResponse() + ]); + // Exits early on cache hit. + if (lastSuccessfulFetchResponse && + this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) { + return lastSuccessfulFetchResponse; + } + // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API + // that allows the caller to pass an ETag. + request.eTag = + lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag; + // Falls back to service on cache miss. + const response = await this.client.fetch(request); + // Fetch throws for non-success responses, so success is guaranteed here. + const storageOperations = [ + // Uses write-through cache for consistency with synchronous public API. + this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()) + ]; + if (response.status === 200) { + // Caches response only if it has changed, ie non-304 responses. + storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response)); + } + await Promise.all(storageOperations); + return response; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Attempts to get the most accurate browser language setting. + * + * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript. + * + * <p>Defers default language specification to server logic for consistency. + * + * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}. + */ +function getUserLanguage(navigatorLanguage = navigator) { + return ( + // Most reliable, but only supported in Chrome/Firefox. + (navigatorLanguage.languages && navigatorLanguage.languages[0]) || + // Supported in most browsers, but returns the language of the browser + // UI, not the language set in browser settings. + navigatorLanguage.language + // Polyfill otherwise. + ); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implements the Client abstraction for the Remote Config REST API. + */ +class RestClient { + constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) { + this.firebaseInstallations = firebaseInstallations; + this.sdkVersion = sdkVersion; + this.namespace = namespace; + this.projectId = projectId; + this.apiKey = apiKey; + this.appId = appId; + } + /** + * Fetches from the Remote Config REST API. + * + * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't + * connect to the network. + * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the + * fetch response. + * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status. + */ + async fetch(request) { + const [installationId, installationToken] = await Promise.all([ + this.firebaseInstallations.getId(), + this.firebaseInstallations.getToken() + ]); + const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE || + 'https://firebaseremoteconfig.googleapis.com'; + const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`; + const headers = { + 'Content-Type': 'application/json', + 'Content-Encoding': 'gzip', + // Deviates from pure decorator by not passing max-age header since we don't currently have + // service behavior using that header. + 'If-None-Match': request.eTag || '*' + // TODO: Add this header once CORS error is fixed internally. + //'X-Firebase-RC-Fetch-Type': `${fetchType}/${fetchAttempt}` + }; + const requestBody = { + /* eslint-disable camelcase */ + sdk_version: this.sdkVersion, + app_instance_id: installationId, + app_instance_id_token: installationToken, + app_id: this.appId, + language_code: getUserLanguage(), + custom_signals: request.customSignals + /* eslint-enable camelcase */ + }; + const options = { + method: 'POST', + headers, + body: JSON.stringify(requestBody) + }; + // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator. + const fetchPromise = fetch(url, options); + const timeoutPromise = new Promise((_resolve, reject) => { + // Maps async event listener to Promise API. + request.signal.addEventListener(() => { + // Emulates https://heycam.github.io/webidl/#aborterror + const error = new Error('The operation was aborted.'); + error.name = 'AbortError'; + reject(error); + }); + }); + let response; + try { + await Promise.race([fetchPromise, timeoutPromise]); + response = await fetchPromise; + } + catch (originalError) { + let errorCode = "fetch-client-network" /* ErrorCode.FETCH_NETWORK */; + if (originalError?.name === 'AbortError') { + errorCode = "fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */; + } + throw ERROR_FACTORY.create(errorCode, { + originalErrorMessage: originalError?.message + }); + } + let status = response.status; + // Normalizes nullable header to optional. + const responseEtag = response.headers.get('ETag') || undefined; + let config; + let state; + let templateVersion; + // JSON parsing throws SyntaxError if the response body isn't a JSON string. + // Requesting application/json and checking for a 200 ensures there's JSON data. + if (response.status === 200) { + let responseBody; + try { + responseBody = await response.json(); + } + catch (originalError) { + throw ERROR_FACTORY.create("fetch-client-parse" /* ErrorCode.FETCH_PARSE */, { + originalErrorMessage: originalError?.message + }); + } + config = responseBody['entries']; + state = responseBody['state']; + templateVersion = responseBody['templateVersion']; + } + // Normalizes based on legacy state. + if (state === 'INSTANCE_STATE_UNSPECIFIED') { + status = 500; + } + else if (state === 'NO_CHANGE') { + status = 304; + } + else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') { + // These cases can be fixed remotely, so normalize to safe value. + config = {}; + } + // Normalize to exception-based control flow for non-success cases. + // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for + // differentiating success states (200 from 304; the state body param is undefined in a + // standard 304). + if (status !== 304 && status !== 200) { + throw ERROR_FACTORY.create("fetch-status" /* ErrorCode.FETCH_STATUS */, { + httpStatus: status + }); + } + return { status, eTag: responseEtag, config, templateVersion }; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Supports waiting on a backoff by: + * + * <ul> + * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> + * <li>Listening on a signal bus for abort events, just like the Fetch API</li> + * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled + * request appear the same.</li> + * </ul> + * + * <p>Visible for testing. + */ +function setAbortableTimeout(signal, throttleEndTimeMillis) { + return new Promise((resolve, reject) => { + // Derives backoff from given end time, normalizing negative numbers to zero. + const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0); + const timeout = setTimeout(resolve, backoffMillis); + // Adds listener, rather than sets onabort, because signal is a shared object. + signal.addEventListener(() => { + clearTimeout(timeout); + // If the request completes before this timeout, the rejection has no effect. + reject(ERROR_FACTORY.create("fetch-throttle" /* ErrorCode.FETCH_THROTTLE */, { + throttleEndTimeMillis + })); + }); + }); +} +/** + * Returns true if the {@link Error} indicates a fetch request may succeed later. + */ +function isRetriableError(e) { + if (!(e instanceof FirebaseError) || !e.customData) { + return false; + } + // Uses string index defined by ErrorData, which FirebaseError implements. + const httpStatus = Number(e.customData['httpStatus']); + return (httpStatus === 429 || + httpStatus === 500 || + httpStatus === 503 || + httpStatus === 504); +} +/** + * Decorates a Client with retry logic. + * + * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache + * responses (because the SDK has no use for error responses). + */ +class RetryingClient { + constructor(client, storage) { + this.client = client; + this.storage = storage; + } + async fetch(request) { + const throttleMetadata = (await this.storage.getThrottleMetadata()) || { + backoffCount: 0, + throttleEndTimeMillis: Date.now() + }; + return this.attemptFetch(request, throttleMetadata); + } + /** + * A recursive helper for attempting a fetch request repeatedly. + * + * @throws any non-retriable errors. + */ + async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) { + // Starts with a (potentially zero) timeout to support resumption from stored state. + // Ensures the throttle end time is honored if the last attempt timed out. + // Note the SDK will never make a request if the fetch timeout expires at this point. + await setAbortableTimeout(request.signal, throttleEndTimeMillis); + try { + const response = await this.client.fetch(request); + // Note the SDK only clears throttle state if response is success or non-retriable. + await this.storage.deleteThrottleMetadata(); + return response; + } + catch (e) { + if (!isRetriableError(e)) { + throw e; + } + // Increments backoff state. + const throttleMetadata = { + throttleEndTimeMillis: Date.now() + calculateBackoffMillis(backoffCount), + backoffCount: backoffCount + 1 + }; + // Persists state. + await this.storage.setThrottleMetadata(throttleMetadata); + return this.attemptFetch(request, throttleMetadata); + } + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute +const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours. +/** + * Encapsulates business logic mapping network and storage dependencies to the public SDK API. + * + * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/compat/index.d.ts|interface documentation} for method descriptions. + */ +class RemoteConfig { + get fetchTimeMillis() { + return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1; + } + get lastFetchStatus() { + return this._storageCache.getLastFetchStatus() || 'no-fetch-yet'; + } + constructor( + // Required by FirebaseServiceFactory interface. + app, + // JS doesn't support private yet + // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an + // underscore prefix. + /** + * @internal + */ + _client, + /** + * @internal + */ + _storageCache, + /** + * @internal + */ + _storage, + /** + * @internal + */ + _logger, + /** + * @internal + */ + _realtimeHandler) { + this.app = app; + this._client = _client; + this._storageCache = _storageCache; + this._storage = _storage; + this._logger = _logger; + this._realtimeHandler = _realtimeHandler; + /** + * Tracks completion of initialization promise. + * @internal + */ + this._isInitializationComplete = false; + this.settings = { + fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS, + minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS + }; + this.defaultConfig = {}; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}. + */ +function toFirebaseError(event, errorCode) { + const originalError = event.target.error || undefined; + return ERROR_FACTORY.create(errorCode, { + originalErrorMessage: originalError && originalError?.message + }); +} +/** + * A general-purpose store keyed by app + namespace + {@link + * ProjectNamespaceKeyFieldValue}. + * + * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact + * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys + * for a set of key-value pairs. See {@link Storage#createCompositeKey}. + * + * <p>Visible for testing. + */ +const APP_NAMESPACE_STORE = 'app_namespace_store'; +const DB_NAME = 'firebase_remote_config'; +const DB_VERSION = 1; +// Visible for testing. +function openDatabase() { + return new Promise((resolve, reject) => { + try { + const request = indexedDB.open(DB_NAME, DB_VERSION); + request.onerror = event => { + reject(toFirebaseError(event, "storage-open" /* ErrorCode.STORAGE_OPEN */)); + }; + request.onsuccess = event => { + resolve(event.target.result); + }; + request.onupgradeneeded = event => { + const db = event.target.result; + // We don't use 'break' in this switch statement, the fall-through + // behavior is what we want, because if there are multiple versions between + // the old version and the current version, we want ALL the migrations + // that correspond to those versions to run, not only the last one. + // eslint-disable-next-line default-case + switch (event.oldVersion) { + case 0: + db.createObjectStore(APP_NAMESPACE_STORE, { + keyPath: 'compositeKey' + }); + } + }; + } + catch (error) { + reject(ERROR_FACTORY.create("storage-open" /* ErrorCode.STORAGE_OPEN */, { + originalErrorMessage: error?.message + })); + } + }); +} +/** + * Abstracts data persistence. + */ +class Storage { + getLastFetchStatus() { + return this.get('last_fetch_status'); + } + setLastFetchStatus(status) { + return this.set('last_fetch_status', status); + } + // This is comparable to a cache entry timestamp. If we need to expire other data, we could + // consider adding timestamp to all storage records and an optional max age arg to getters. + getLastSuccessfulFetchTimestampMillis() { + return this.get('last_successful_fetch_timestamp_millis'); + } + setLastSuccessfulFetchTimestampMillis(timestamp) { + return this.set('last_successful_fetch_timestamp_millis', timestamp); + } + getLastSuccessfulFetchResponse() { + return this.get('last_successful_fetch_response'); + } + setLastSuccessfulFetchResponse(response) { + return this.set('last_successful_fetch_response', response); + } + getActiveConfig() { + return this.get('active_config'); + } + setActiveConfig(config) { + return this.set('active_config', config); + } + getActiveConfigEtag() { + return this.get('active_config_etag'); + } + setActiveConfigEtag(etag) { + return this.set('active_config_etag', etag); + } + getThrottleMetadata() { + return this.get('throttle_metadata'); + } + setThrottleMetadata(metadata) { + return this.set('throttle_metadata', metadata); + } + deleteThrottleMetadata() { + return this.delete('throttle_metadata'); + } + getCustomSignals() { + return this.get('custom_signals'); + } + getRealtimeBackoffMetadata() { + return this.get('realtime_backoff_metadata'); + } + setRealtimeBackoffMetadata(realtimeMetadata) { + return this.set('realtime_backoff_metadata', realtimeMetadata); + } + getActiveConfigTemplateVersion() { + return this.get('last_known_template_version'); + } + setActiveConfigTemplateVersion(version) { + return this.set('last_known_template_version', version); + } +} +class IndexedDbStorage extends Storage { + /** + * @param appId enables storage segmentation by app (ID + name). + * @param appName enables storage segmentation by app (ID + name). + * @param namespace enables storage segmentation by namespace. + */ + constructor(appId, appName, namespace, openDbPromise = openDatabase()) { + super(); + this.appId = appId; + this.appName = appName; + this.namespace = namespace; + this.openDbPromise = openDbPromise; + } + async setCustomSignals(customSignals) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + const storedSignals = await this.getWithTransaction('custom_signals', transaction); + const updatedSignals = mergeCustomSignals(customSignals, storedSignals || {}); + await this.setWithTransaction('custom_signals', updatedSignals, transaction); + return updatedSignals; + } + /** + * Gets a value from the database using the provided transaction. + * + * @param key The key of the value to get. + * @param transaction The transaction to use for the operation. + * @returns The value associated with the key, or undefined if no such value exists. + */ + async getWithTransaction(key, transaction) { + return new Promise((resolve, reject) => { + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.get(compositeKey); + request.onerror = event => { + reject(toFirebaseError(event, "storage-get" /* ErrorCode.STORAGE_GET */)); + }; + request.onsuccess = event => { + const result = event.target.result; + if (result) { + resolve(result.value); + } + else { + resolve(undefined); + } + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-get" /* ErrorCode.STORAGE_GET */, { + originalErrorMessage: e?.message + })); + } + }); + } + /** + * Sets a value in the database using the provided transaction. + * + * @param key The key of the value to set. + * @param value The value to set. + * @param transaction The transaction to use for the operation. + * @returns A promise that resolves when the operation is complete. + */ + async setWithTransaction(key, value, transaction) { + return new Promise((resolve, reject) => { + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.put({ + compositeKey, + value + }); + request.onerror = (event) => { + reject(toFirebaseError(event, "storage-set" /* ErrorCode.STORAGE_SET */)); + }; + request.onsuccess = () => { + resolve(); + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-set" /* ErrorCode.STORAGE_SET */, { + originalErrorMessage: e?.message + })); + } + }); + } + async get(key) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly'); + return this.getWithTransaction(key, transaction); + } + async set(key, value) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + return this.setWithTransaction(key, value, transaction); + } + async delete(key) { + const db = await this.openDbPromise; + return new Promise((resolve, reject) => { + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.delete(compositeKey); + request.onerror = (event) => { + reject(toFirebaseError(event, "storage-delete" /* ErrorCode.STORAGE_DELETE */)); + }; + request.onsuccess = () => { + resolve(); + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-delete" /* ErrorCode.STORAGE_DELETE */, { + originalErrorMessage: e?.message + })); + } + }); + } + // Facilitates composite key functionality (which is unsupported in IE). + createCompositeKey(key) { + return [this.appId, this.appName, this.namespace, key].join(); + } +} +class InMemoryStorage extends Storage { + constructor() { + super(...arguments); + this.storage = {}; + } + async get(key) { + return Promise.resolve(this.storage[key]); + } + async set(key, value) { + this.storage[key] = value; + return Promise.resolve(undefined); + } + async delete(key) { + this.storage[key] = undefined; + return Promise.resolve(); + } + async setCustomSignals(customSignals) { + const storedSignals = (this.storage['custom_signals'] || + {}); + this.storage['custom_signals'] = mergeCustomSignals(customSignals, storedSignals); + return Promise.resolve(this.storage['custom_signals']); + } +} +function mergeCustomSignals(customSignals, storedSignals) { + const combinedSignals = { + ...storedSignals, + ...customSignals + }; + // Filter out key-value assignments with null values since they are signals being unset + const updatedSignals = Object.fromEntries(Object.entries(combinedSignals) + .filter(([_, v]) => v !== null) + .map(([k, v]) => { + // Stringify numbers to store a map of string keys and values which can be sent + // as-is in a fetch call. + if (typeof v === 'number') { + return [k, v.toString()]; + } + return [k, v]; + })); + // Throw an error if the number of custom signals to be stored exceeds the limit + if (Object.keys(updatedSignals).length > RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS) { + throw ERROR_FACTORY.create("custom-signal-max-allowed-signals" /* ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS */, { + maxSignals: RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS + }); + } + return updatedSignals; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A memory cache layer over storage to support the SDK's synchronous read requirements. + */ +class StorageCache { + constructor(storage) { + this.storage = storage; + } + /** + * Memory-only getters + */ + getLastFetchStatus() { + return this.lastFetchStatus; + } + getLastSuccessfulFetchTimestampMillis() { + return this.lastSuccessfulFetchTimestampMillis; + } + getActiveConfig() { + return this.activeConfig; + } + getCustomSignals() { + return this.customSignals; + } + /** + * Read-ahead getter + */ + async loadFromStorage() { + const lastFetchStatusPromise = this.storage.getLastFetchStatus(); + const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis(); + const activeConfigPromise = this.storage.getActiveConfig(); + const customSignalsPromise = this.storage.getCustomSignals(); + // Note: + // 1. we consistently check for undefined to avoid clobbering defined values + // in memory + // 2. we defer awaiting to improve readability, as opposed to destructuring + // a Promise.all result, for example + const lastFetchStatus = await lastFetchStatusPromise; + if (lastFetchStatus) { + this.lastFetchStatus = lastFetchStatus; + } + const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise; + if (lastSuccessfulFetchTimestampMillis) { + this.lastSuccessfulFetchTimestampMillis = + lastSuccessfulFetchTimestampMillis; + } + const activeConfig = await activeConfigPromise; + if (activeConfig) { + this.activeConfig = activeConfig; + } + const customSignals = await customSignalsPromise; + if (customSignals) { + this.customSignals = customSignals; + } + } + /** + * Write-through setters + */ + setLastFetchStatus(status) { + this.lastFetchStatus = status; + return this.storage.setLastFetchStatus(status); + } + setLastSuccessfulFetchTimestampMillis(timestampMillis) { + this.lastSuccessfulFetchTimestampMillis = timestampMillis; + return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis); + } + setActiveConfig(activeConfig) { + this.activeConfig = activeConfig; + return this.storage.setActiveConfig(activeConfig); + } + async setCustomSignals(customSignals) { + this.customSignals = await this.storage.setCustomSignals(customSignals); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 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. +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + //@ts-ignore + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 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. +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } // @ts-ignore + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } // @ts-ignore + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } // @ts-ignore + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + // @ts-ignore + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + // @ts-ignore + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const API_KEY_HEADER = 'X-Goog-Api-Key'; +const INSTALLATIONS_AUTH_TOKEN_HEADER = 'X-Goog-Firebase-Installations-Auth'; +const ORIGINAL_RETRIES = 8; +const MAXIMUM_FETCH_ATTEMPTS = 3; +const NO_BACKOFF_TIME_IN_MILLIS = -1; +const NO_FAILED_REALTIME_STREAMS = 0; +const REALTIME_DISABLED_KEY = 'featureDisabled'; +const REALTIME_RETRY_INTERVAL = 'retryIntervalSeconds'; +const TEMPLATE_VERSION_KEY = 'latestTemplateVersionNumber'; +class RealtimeHandler { + constructor(firebaseInstallations, storage, sdkVersion, namespace, projectId, apiKey, appId, logger, storageCache, cachingClient) { + this.firebaseInstallations = firebaseInstallations; + this.storage = storage; + this.sdkVersion = sdkVersion; + this.namespace = namespace; + this.projectId = projectId; + this.apiKey = apiKey; + this.appId = appId; + this.logger = logger; + this.storageCache = storageCache; + this.cachingClient = cachingClient; + this.observers = new Set(); + this.isConnectionActive = false; + this.isRealtimeDisabled = false; + this.httpRetriesRemaining = ORIGINAL_RETRIES; + this.isInBackground = false; + this.decoder = new TextDecoder('utf-8'); + this.isClosingConnection = false; + this.propagateError = (e) => this.observers.forEach(o => o.error?.(e)); + /** + * HTTP status code that the Realtime client should retry on. + */ + this.isStatusCodeRetryable = (statusCode) => { + const retryableStatusCodes = [ + 408, // Request Timeout + 429, // Too Many Requests + 502, // Bad Gateway + 503, // Service Unavailable + 504 // Gateway Timeout + ]; + return !statusCode || retryableStatusCodes.includes(statusCode); + }; + void this.setRetriesRemaining(); + void VisibilityMonitor.getInstance().on('visible', this.onVisibilityChange, this); + } + async setRetriesRemaining() { + // Retrieve number of remaining retries from last session. The minimum retry count being one. + const metadata = await this.storage.getRealtimeBackoffMetadata(); + const numFailedStreams = metadata?.numFailedStreams || 0; + this.httpRetriesRemaining = Math.max(ORIGINAL_RETRIES - numFailedStreams, 1); + } + /** + * Increment the number of failed stream attempts, increase the backoff duration, set the backoff + * end time to "backoff duration" after `lastFailedStreamTime` and persist the new + * values to storage metadata. + */ + async updateBackoffMetadataWithLastFailedStreamConnectionTime(lastFailedStreamTime) { + const numFailedStreams = ((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams || + 0) + 1; + const backoffMillis = calculateBackoffMillis(numFailedStreams, 60000, 2); + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: new Date(lastFailedStreamTime.getTime() + backoffMillis), + numFailedStreams + }); + } + /** + * Increase the backoff duration with a new end time based on Retry Interval. + */ + async updateBackoffMetadataWithRetryInterval(retryIntervalSeconds) { + const currentTime = Date.now(); + const backoffDurationInMillis = retryIntervalSeconds * 1000; + const backoffEndTime = new Date(currentTime + backoffDurationInMillis); + const numFailedStreams = 0; + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: backoffEndTime, + numFailedStreams + }); + await this.retryHttpConnectionWhenBackoffEnds(); + } + /** + * Closes the realtime HTTP connection. + * Note: This method is designed to be called only once at a time. + * If a call is already in progress, subsequent calls will be ignored. + */ + async closeRealtimeHttpConnection() { + if (this.isClosingConnection) { + return; + } + this.isClosingConnection = true; + try { + if (this.reader) { + await this.reader.cancel(); + } + } + catch (e) { + // The network connection was lost, so cancel() failed. + // This is expected in a disconnected state, so we can safely ignore the error. + this.logger.debug('Failed to cancel the reader, connection was lost.'); + } + finally { + this.reader = undefined; + } + if (this.controller) { + await this.controller.abort(); + this.controller = undefined; + } + this.isClosingConnection = false; + } + async resetRealtimeBackoff() { + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: new Date(-1), + numFailedStreams: 0 + }); + } + resetRetryCount() { + this.httpRetriesRemaining = ORIGINAL_RETRIES; + } + /** + * Assembles the request headers and body and executes the fetch request to + * establish the real-time streaming connection. This is the "worker" method + * that performs the actual network communication. + */ + async establishRealtimeConnection(url, installationId, installationTokenResult, signal) { + const eTagValue = await this.storage.getActiveConfigEtag(); + const lastKnownVersionNumber = await this.storage.getActiveConfigTemplateVersion(); + const headers = { + [API_KEY_HEADER]: this.apiKey, + [INSTALLATIONS_AUTH_TOKEN_HEADER]: installationTokenResult, + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'If-None-Match': eTagValue || '*', + 'Content-Encoding': 'gzip' + }; + const requestBody = { + project: this.projectId, + namespace: this.namespace, + lastKnownVersionNumber, + appId: this.appId, + sdkVersion: this.sdkVersion, + appInstanceId: installationId + }; + const response = await fetch(url, { + method: 'POST', + headers, + body: JSON.stringify(requestBody), + signal + }); + return response; + } + getRealtimeUrl() { + const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE || + 'https://firebaseremoteconfigrealtime.googleapis.com'; + const urlString = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`; + return new URL(urlString); + } + async createRealtimeConnection() { + const [installationId, installationTokenResult] = await Promise.all([ + this.firebaseInstallations.getId(), + this.firebaseInstallations.getToken(false) + ]); + this.controller = new AbortController(); + const url = this.getRealtimeUrl(); + const realtimeConnection = await this.establishRealtimeConnection(url, installationId, installationTokenResult, this.controller.signal); + return realtimeConnection; + } + /** + * Retries HTTP stream connection asyncly in random time intervals. + */ + async retryHttpConnectionWhenBackoffEnds() { + let backoffMetadata = await this.storage.getRealtimeBackoffMetadata(); + if (!backoffMetadata) { + backoffMetadata = { + backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS), + numFailedStreams: NO_FAILED_REALTIME_STREAMS + }; + } + const backoffEndTime = new Date(backoffMetadata.backoffEndTimeMillis).getTime(); + const currentTime = Date.now(); + const retryMillis = Math.max(0, backoffEndTime - currentTime); + await this.makeRealtimeHttpConnection(retryMillis); + } + setIsHttpConnectionRunning(connectionRunning) { + this.isConnectionActive = connectionRunning; + } + /** + * Combines the check and set operations to prevent multiple asynchronous + * calls from redundantly starting an HTTP connection. This ensures that + * only one attempt is made at a time. + */ + checkAndSetHttpConnectionFlagIfNotRunning() { + const canMakeConnection = this.canEstablishStreamConnection(); + if (canMakeConnection) { + this.setIsHttpConnectionRunning(true); + } + return canMakeConnection; + } + fetchResponseIsUpToDate(fetchResponse, lastKnownVersion) { + // If there is a config, make sure its version is >= the last known version. + if (fetchResponse.config != null && fetchResponse.templateVersion) { + return fetchResponse.templateVersion >= lastKnownVersion; + } + // If there isn't a config, return true if the fetch was successful and backend had no update. + // Else, it returned an out of date config. + return this.storageCache.getLastFetchStatus() === 'success'; + } + parseAndValidateConfigUpdateMessage(message) { + const left = message.indexOf('{'); + const right = message.indexOf('}', left); + if (left < 0 || right < 0) { + return ''; + } + return left >= right ? '' : message.substring(left, right + 1); + } + isEventListenersEmpty() { + return this.observers.size === 0; + } + getRandomInt(max) { + return Math.floor(Math.random() * max); + } + executeAllListenerCallbacks(configUpdate) { + this.observers.forEach(observer => observer.next(configUpdate)); + } + /** + * Compares two configuration objects and returns a set of keys that have changed. + * A key is considered changed if it's new, removed, or has a different value. + */ + getChangedParams(newConfig, oldConfig) { + const changedKeys = new Set(); + const newKeys = new Set(Object.keys(newConfig || {})); + const oldKeys = new Set(Object.keys(oldConfig || {})); + for (const key of newKeys) { + if (!oldKeys.has(key) || newConfig[key] !== oldConfig[key]) { + changedKeys.add(key); + } + } + for (const key of oldKeys) { + if (!newKeys.has(key)) { + changedKeys.add(key); + } + } + return changedKeys; + } + async fetchLatestConfig(remainingAttempts, targetVersion) { + const remainingAttemptsAfterFetch = remainingAttempts - 1; + const currentAttempt = MAXIMUM_FETCH_ATTEMPTS - remainingAttemptsAfterFetch; + const customSignals = this.storageCache.getCustomSignals(); + if (customSignals) { + this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(customSignals)}`); + } + const abortSignal = new RemoteConfigAbortSignal(); + try { + const fetchRequest = { + cacheMaxAgeMillis: 0, + signal: abortSignal, + customSignals, + fetchType: 'REALTIME', + fetchAttempt: currentAttempt + }; + const fetchResponse = await this.cachingClient.fetch(fetchRequest); + let activatedConfigs = await this.storage.getActiveConfig(); + if (!this.fetchResponseIsUpToDate(fetchResponse, targetVersion)) { + this.logger.debug("Fetched template version is the same as SDK's current version." + + ' Retrying fetch.'); + // Continue fetching until template version number is greater than current. + await this.autoFetch(remainingAttemptsAfterFetch, targetVersion); + return; + } + if (fetchResponse.config == null) { + this.logger.debug('The fetch succeeded, but the backend had no updates.'); + return; + } + if (activatedConfigs == null) { + activatedConfigs = {}; + } + const updatedKeys = this.getChangedParams(fetchResponse.config, activatedConfigs); + if (updatedKeys.size === 0) { + this.logger.debug('Config was fetched, but no params changed.'); + return; + } + const configUpdate = { + getUpdatedKeys() { + return new Set(updatedKeys); + } + }; + this.executeAllListenerCallbacks(configUpdate); + } + catch (e) { + const errorMessage = e instanceof Error ? e.message : String(e); + const error = ERROR_FACTORY.create("update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */, { + originalErrorMessage: `Failed to auto-fetch config update: ${errorMessage}` + }); + this.propagateError(error); + } + } + async autoFetch(remainingAttempts, targetVersion) { + if (remainingAttempts === 0) { + const error = ERROR_FACTORY.create("update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */, { + originalErrorMessage: 'Unable to fetch the latest version of the template.' + }); + this.propagateError(error); + return; + } + const timeTillFetchSeconds = this.getRandomInt(4); + const timeTillFetchInMiliseconds = timeTillFetchSeconds * 1000; + await new Promise(resolve => setTimeout(resolve, timeTillFetchInMiliseconds)); + await this.fetchLatestConfig(remainingAttempts, targetVersion); + } + /** + * Processes a stream of real-time messages for configuration updates. + * This method reassembles fragmented messages, validates and parses the JSON, + * and automatically fetches a new config if a newer template version is available. + * It also handles server-specified retry intervals and propagates errors for + * invalid messages or when real-time updates are disabled. + */ + async handleNotifications(reader) { + let partialConfigUpdateMessage; + let currentConfigUpdateMessage = ''; + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + partialConfigUpdateMessage = this.decoder.decode(value, { stream: true }); + currentConfigUpdateMessage += partialConfigUpdateMessage; + if (partialConfigUpdateMessage.includes('}')) { + currentConfigUpdateMessage = this.parseAndValidateConfigUpdateMessage(currentConfigUpdateMessage); + if (currentConfigUpdateMessage.length === 0) { + continue; + } + try { + const jsonObject = JSON.parse(currentConfigUpdateMessage); + if (this.isEventListenersEmpty()) { + break; + } + if (REALTIME_DISABLED_KEY in jsonObject && + jsonObject[REALTIME_DISABLED_KEY] === true) { + const error = ERROR_FACTORY.create("realtime-unavailable" /* ErrorCode.CONFIG_UPDATE_UNAVAILABLE */, { + originalErrorMessage: 'The server is temporarily unavailable. Try again in a few minutes.' + }); + this.propagateError(error); + break; + } + if (TEMPLATE_VERSION_KEY in jsonObject) { + const oldTemplateVersion = await this.storage.getActiveConfigTemplateVersion(); + const targetTemplateVersion = Number(jsonObject[TEMPLATE_VERSION_KEY]); + if (oldTemplateVersion && + targetTemplateVersion > oldTemplateVersion) { + await this.autoFetch(MAXIMUM_FETCH_ATTEMPTS, targetTemplateVersion); + } + } + // This field in the response indicates that the realtime request should retry after the + // specified interval to establish a long-lived connection. This interval extends the + // backoff duration without affecting the number of retries, so it will not enter an + // exponential backoff state. + if (REALTIME_RETRY_INTERVAL in jsonObject) { + const retryIntervalSeconds = Number(jsonObject[REALTIME_RETRY_INTERVAL]); + await this.updateBackoffMetadataWithRetryInterval(retryIntervalSeconds); + } + } + catch (e) { + this.logger.debug('Unable to parse latest config update message.', e); + const errorMessage = e instanceof Error ? e.message : String(e); + this.propagateError(ERROR_FACTORY.create("update-message-invalid" /* ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID */, { + originalErrorMessage: errorMessage + })); + } + currentConfigUpdateMessage = ''; + } + } + } + async listenForNotifications(reader) { + try { + await this.handleNotifications(reader); + } + catch (e) { + // If the real-time connection is at an unexpected lifecycle state when the app is + // backgrounded, it's expected closing the connection will throw an exception. + if (!this.isInBackground) { + // Otherwise, the real-time server connection was closed due to a transient issue. + this.logger.debug('Real-time connection was closed due to an exception.'); + } + } + } + /** + * Open the real-time connection, begin listening for updates, and auto-fetch when an update is + * received. + * + * If the connection is successful, this method will block on its thread while it reads the + * chunk-encoded HTTP body. When the connection closes, it attempts to reestablish the stream. + */ + async prepareAndBeginRealtimeHttpStream() { + if (!this.checkAndSetHttpConnectionFlagIfNotRunning()) { + return; + } + let backoffMetadata = await this.storage.getRealtimeBackoffMetadata(); + if (!backoffMetadata) { + backoffMetadata = { + backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS), + numFailedStreams: NO_FAILED_REALTIME_STREAMS + }; + } + const backoffEndTime = backoffMetadata.backoffEndTimeMillis.getTime(); + if (Date.now() < backoffEndTime) { + await this.retryHttpConnectionWhenBackoffEnds(); + return; + } + let response; + let responseCode; + try { + response = await this.createRealtimeConnection(); + responseCode = response.status; + if (response.ok && response.body) { + this.resetRetryCount(); + await this.resetRealtimeBackoff(); + const reader = response.body.getReader(); + this.reader = reader; + // Start listening for realtime notifications. + await this.listenForNotifications(reader); + } + } + catch (error) { + if (this.isInBackground) { + // It's possible the app was backgrounded while the connection was open, which + // threw an exception trying to read the response. No real error here, so treat + // this as a success, even if we haven't read a 200 response code yet. + this.resetRetryCount(); + } + else { + //there might have been a transient error so the client will retry the connection. + this.logger.debug('Exception connecting to real-time RC backend. Retrying the connection...:', error); + } + } + finally { + // Close HTTP connection and associated streams. + await this.closeRealtimeHttpConnection(); + this.setIsHttpConnectionRunning(false); + // Update backoff metadata if the connection failed in the foreground. + const connectionFailed = !this.isInBackground && + (responseCode === undefined || + this.isStatusCodeRetryable(responseCode)); + if (connectionFailed) { + await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date()); + } + // If responseCode is null then no connection was made to server and the SDK should still retry. + if (connectionFailed || response?.ok) { + await this.retryHttpConnectionWhenBackoffEnds(); + } + else { + const errorMessage = `Unable to connect to the server. HTTP status code: ${responseCode}`; + const firebaseError = ERROR_FACTORY.create("stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */, { + originalErrorMessage: errorMessage + }); + this.propagateError(firebaseError); + } + } + } + /** + * Checks whether connection can be made or not based on some conditions + * @returns booelean + */ + canEstablishStreamConnection() { + const hasActiveListeners = this.observers.size > 0; + const isNotDisabled = !this.isRealtimeDisabled; + const isNoConnectionActive = !this.isConnectionActive; + const inForeground = !this.isInBackground; + return (hasActiveListeners && + isNotDisabled && + isNoConnectionActive && + inForeground); + } + async makeRealtimeHttpConnection(delayMillis) { + if (!this.canEstablishStreamConnection()) { + return; + } + if (this.httpRetriesRemaining > 0) { + this.httpRetriesRemaining--; + await new Promise(resolve => setTimeout(resolve, delayMillis)); + void this.prepareAndBeginRealtimeHttpStream(); + } + else if (!this.isInBackground) { + const error = ERROR_FACTORY.create("stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */, { + originalErrorMessage: 'Unable to connect to the server. Check your connection and try again.' + }); + this.propagateError(error); + } + } + async beginRealtime() { + if (this.observers.size > 0) { + await this.makeRealtimeHttpConnection(0); + } + } + /** + * Adds an observer to the realtime updates. + * @param observer The observer to add. + */ + addObserver(observer) { + this.observers.add(observer); + void this.beginRealtime(); + } + /** + * Removes an observer from the realtime updates. + * @param observer The observer to remove. + */ + removeObserver(observer) { + if (this.observers.has(observer)) { + this.observers.delete(observer); + } + } + /** + * Handles changes to the application's visibility state, managing the real-time connection. + * + * When the application is moved to the background, this method closes the existing + * real-time connection to save resources. When the application returns to the + * foreground, it attempts to re-establish the connection. + */ + async onVisibilityChange(visible) { + this.isInBackground = !visible; + if (!visible) { + await this.closeRealtimeHttpConnection(); + } + else if (visible) { + await this.beginRealtime(); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerRemoteConfig() { + _registerComponent(new Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + registerVersion(name, version); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(name, version, 'esm2020'); + function remoteConfigFactory(container, { options }) { + /* Dependencies */ + // getImmediate for FirebaseApp will always succeed + const app = container.getProvider('app').getImmediate(); + // The following call will always succeed because rc has `import '@firebase/installations'` + const installations = container + .getProvider('installations-internal') + .getImmediate(); + // Normalizes optional inputs. + const { projectId, apiKey, appId } = app.options; + if (!projectId) { + throw ERROR_FACTORY.create("registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */); + } + if (!apiKey) { + throw ERROR_FACTORY.create("registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */); + } + if (!appId) { + throw ERROR_FACTORY.create("registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */); + } + const namespace = options?.templateId || 'firebase'; + const storage = isIndexedDBAvailable() + ? new IndexedDbStorage(appId, app.name, namespace) + : new InMemoryStorage(); + const storageCache = new StorageCache(storage); + const logger = new Logger(name); + // Sets ERROR as the default log level. + // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level. + logger.logLevel = LogLevel.ERROR; + const restClient = new RestClient(installations, + // Uses the JS SDK version, by which the RC package version can be deduced, if necessary. + SDK_VERSION, namespace, projectId, apiKey, appId); + const retryingClient = new RetryingClient(restClient, storage); + const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger); + const realtimeHandler = new RealtimeHandler(installations, storage, SDK_VERSION, namespace, projectId, apiKey, appId, logger, storageCache, cachingClient); + const remoteConfigInstance = new RemoteConfig(app, cachingClient, storageCache, storage, logger, realtimeHandler); + // Starts warming cache. + // eslint-disable-next-line @typescript-eslint/no-floating-promises + ensureInitialized(remoteConfigInstance); + return remoteConfigInstance; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// This API is put in a separate file, so we can stub fetchConfig and activate in tests. +// It's not possible to stub standalone functions from the same module. +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +async function fetchAndActivate(remoteConfig) { + remoteConfig = getModularInstance(remoteConfig); + await fetchConfig(remoteConfig); + return activate(remoteConfig); +} +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +async function isSupported() { + if (!isIndexedDBAvailable()) { + return false; + } + try { + const isDBOpenable = await validateIndexedDBOpenable(); + return isDBOpenable; + } + catch (error) { + return false; + } +} + +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +/** register component and version */ +registerRemoteConfig(); + +export { activate, ensureInitialized, fetchAndActivate, fetchConfig, getAll, getBoolean, getNumber, getRemoteConfig, getString, getValue, isSupported, onConfigUpdate, setCustomSignals, setLogLevel }; +//# sourceMappingURL=index.esm.js.map diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js.map b/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js.map new file mode 100644 index 0000000..b9305c6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../../src/client/remote_config_fetch_client.ts","../../src/constants.ts","../../src/errors.ts","../../src/value.ts","../../src/api.ts","../../src/client/caching_client.ts","../../src/language.ts","../../src/client/rest_client.ts","../../src/client/retrying_client.ts","../../src/remote_config.ts","../../src/storage/storage.ts","../../src/storage/storage_cache.ts","../../src/client/eventEmitter.ts","../../src/client/visibility_monitor.ts","../../src/client/realtime_handler.ts","../../src/register.ts","../../src/api2.ts","../../src/index.ts"],"sourcesContent":["/**\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}\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};\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}\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 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';\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 await Promise.all([\n rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag),\n rc._storage.setActiveConfigTemplateVersion(\n lastSuccessfulFetchResponse.templateVersion\n )\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} 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\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 }\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 }\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 };\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 { 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}\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 | '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 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\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 );\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"],"names":["ValueImpl","FirebaseLogLevel","packageName","RemoteConfigImpl"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;;;;;;AAOG;MACU,uBAAuB,CAAA;AAApC,IAAA,WAAA,GAAA;QACE,IAAS,CAAA,SAAA,GAAsB,EAAE,CAAC;KAOnC;AANC,IAAA,gBAAgB,CAAC,QAAoB,EAAA;AACnC,QAAA,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;K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,IAAA,OAAO,QAAQ,CAAC,YAAY,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;;;;AASG;AACI,eAAe,WAAW,GAAA;AAC/B,IAAA,IAAI,CAAC,oBAAoB,EAAE,EAAE;AAC3B,QAAA,OAAO,KAAK,CAAC;KACd;AAED,IAAA,IAAI;AACF,QAAA,MAAM,YAAY,GAAY,MAAM,yBAAyB,EAAE,CAAC;AAChE,QAAA,OAAO,YAAY,CAAC;KACrB;IAAC,OAAO,KAAK,EAAE;AACd,QAAA,OAAO,KAAK,CAAC;KACd;AACH;;ACnEA;;;;;AAKG;AAmCH;AACA,oBAAoB,EAAE;;;;"}
\ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/package.json b/frontend-old/node_modules/@firebase/remote-config/dist/esm/package.json new file mode 100644 index 0000000..7c34deb --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/package.json @@ -0,0 +1 @@ +{"type":"module"}
\ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api.d.ts new file mode 100644 index 0000000..0f16c48 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api.d.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { CustomSignals, LogLevel as RemoteConfigLogLevel, RemoteConfig, Value, RemoteConfigOptions, ConfigUpdateObserver, Unsubscribe } from './public_types'; +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +export declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig; +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function activate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +export declare function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>; +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +export declare function fetchConfig(remoteConfig: RemoteConfig): Promise<void>; +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +export declare function getAll(remoteConfig: RemoteConfig): Record<string, Value>; +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +export declare function getBoolean(remoteConfig: RemoteConfig, key: string): boolean; +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +export declare function getNumber(remoteConfig: RemoteConfig, key: string): number; +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +export declare function getString(remoteConfig: RemoteConfig, key: string): string; +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +export declare function getValue(remoteConfig: RemoteConfig, key: string): Value; +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +export declare function setLogLevel(remoteConfig: RemoteConfig, logLevel: RemoteConfigLogLevel): void; +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +export declare function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>; +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +export declare function onConfigUpdate(remoteConfig: RemoteConfig, observer: ConfigUpdateObserver): Unsubscribe; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api2.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api2.d.ts new file mode 100644 index 0000000..ea6a655 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/api2.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RemoteConfig } from './public_types'; +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +export declare function isSupported(): Promise<boolean>; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/caching_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/caching_client.d.ts new file mode 100644 index 0000000..c05bd5f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/caching_client.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StorageCache } from '../storage/storage_cache'; +import { FetchResponse } from '../public_types'; +import { RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { Storage } from '../storage/storage'; +import { Logger } from '@firebase/logger'; +/** + * Implements the {@link RemoteConfigClient} abstraction with success response caching. + * + * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service + * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the + * Cache API doesn't support matching entries by time. + */ +export declare class CachingClient implements RemoteConfigFetchClient { + private readonly client; + private readonly storage; + private readonly storageCache; + private readonly logger; + constructor(client: RemoteConfigFetchClient, storage: Storage, storageCache: StorageCache, logger: Logger); + /** + * Returns true if the age of the cached fetched configs is less than or equal to + * {@link Settings#minimumFetchIntervalInSeconds}. + * + * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the + * native Fetch API. + * + * <p>Visible for testing. + */ + isCachedDataFresh(cacheMaxAgeMillis: number, lastSuccessfulFetchTimestampMillis: number | undefined): boolean; + fetch(request: FetchRequest): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/eventEmitter.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/eventEmitter.d.ts new file mode 100644 index 0000000..2f8b9cc --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/eventEmitter.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +export declare abstract class EventEmitter { + private allowedEvents_; + private listeners_; + constructor(allowedEvents_: string[]); + /** + * To be overridden by derived classes in order to fire an initial event when + * somebody subscribes for data. + * + * @returns {Array.<*>} Array of parameters to trigger initial event with. + */ + abstract getInitialEvent(eventType: string): unknown[]; + /** + * To be called by derived classes to trigger events. + */ + protected trigger(eventType: string, ...varArgs: unknown[]): void; + on(eventType: string, callback: (a: unknown) => void, context: unknown): void; + off(eventType: string, callback: (a: unknown) => void, context: unknown): void; + private validateEventType_; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/realtime_handler.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/realtime_handler.d.ts new file mode 100644 index 0000000..3fa7c87 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/realtime_handler.d.ts @@ -0,0 +1,141 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseInstallationsInternal } from '@firebase/installations'; +import { Logger } from '@firebase/logger'; +import { ConfigUpdateObserver } from '../public_types'; +import { Storage } from '../storage/storage'; +import { StorageCache } from '../storage/storage_cache'; +import { CachingClient } from './caching_client'; +export declare class RealtimeHandler { + private readonly firebaseInstallations; + private readonly storage; + private readonly sdkVersion; + private readonly namespace; + private readonly projectId; + private readonly apiKey; + private readonly appId; + private readonly logger; + private readonly storageCache; + private readonly cachingClient; + constructor(firebaseInstallations: _FirebaseInstallationsInternal, storage: Storage, sdkVersion: string, namespace: string, projectId: string, apiKey: string, appId: string, logger: Logger, storageCache: StorageCache, cachingClient: CachingClient); + private observers; + private isConnectionActive; + private isRealtimeDisabled; + private controller?; + private reader; + private httpRetriesRemaining; + private isInBackground; + private readonly decoder; + private isClosingConnection; + private setRetriesRemaining; + private propagateError; + /** + * Increment the number of failed stream attempts, increase the backoff duration, set the backoff + * end time to "backoff duration" after `lastFailedStreamTime` and persist the new + * values to storage metadata. + */ + private updateBackoffMetadataWithLastFailedStreamConnectionTime; + /** + * Increase the backoff duration with a new end time based on Retry Interval. + */ + private updateBackoffMetadataWithRetryInterval; + /** + * HTTP status code that the Realtime client should retry on. + */ + private isStatusCodeRetryable; + /** + * Closes the realtime HTTP connection. + * Note: This method is designed to be called only once at a time. + * If a call is already in progress, subsequent calls will be ignored. + */ + private closeRealtimeHttpConnection; + private resetRealtimeBackoff; + private resetRetryCount; + /** + * Assembles the request headers and body and executes the fetch request to + * establish the real-time streaming connection. This is the "worker" method + * that performs the actual network communication. + */ + private establishRealtimeConnection; + private getRealtimeUrl; + private createRealtimeConnection; + /** + * Retries HTTP stream connection asyncly in random time intervals. + */ + private retryHttpConnectionWhenBackoffEnds; + private setIsHttpConnectionRunning; + /** + * Combines the check and set operations to prevent multiple asynchronous + * calls from redundantly starting an HTTP connection. This ensures that + * only one attempt is made at a time. + */ + private checkAndSetHttpConnectionFlagIfNotRunning; + private fetchResponseIsUpToDate; + private parseAndValidateConfigUpdateMessage; + private isEventListenersEmpty; + private getRandomInt; + private executeAllListenerCallbacks; + /** + * Compares two configuration objects and returns a set of keys that have changed. + * A key is considered changed if it's new, removed, or has a different value. + */ + private getChangedParams; + private fetchLatestConfig; + private autoFetch; + /** + * Processes a stream of real-time messages for configuration updates. + * This method reassembles fragmented messages, validates and parses the JSON, + * and automatically fetches a new config if a newer template version is available. + * It also handles server-specified retry intervals and propagates errors for + * invalid messages or when real-time updates are disabled. + */ + private handleNotifications; + private listenForNotifications; + /** + * Open the real-time connection, begin listening for updates, and auto-fetch when an update is + * received. + * + * If the connection is successful, this method will block on its thread while it reads the + * chunk-encoded HTTP body. When the connection closes, it attempts to reestablish the stream. + */ + private prepareAndBeginRealtimeHttpStream; + /** + * Checks whether connection can be made or not based on some conditions + * @returns booelean + */ + private canEstablishStreamConnection; + private makeRealtimeHttpConnection; + private beginRealtime; + /** + * Adds an observer to the realtime updates. + * @param observer The observer to add. + */ + addObserver(observer: ConfigUpdateObserver): void; + /** + * Removes an observer from the realtime updates. + * @param observer The observer to remove. + */ + removeObserver(observer: ConfigUpdateObserver): void; + /** + * Handles changes to the application's visibility state, managing the real-time connection. + * + * When the application is moved to the background, this method closes the existing + * real-time connection to save resources. When the application returns to the + * foreground, it attempts to re-establish the connection. + */ + private onVisibilityChange; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/remote_config_fetch_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/remote_config_fetch_client.d.ts new file mode 100644 index 0000000..e72ce51 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/remote_config_fetch_client.d.ts @@ -0,0 +1,104 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CustomSignals, FetchResponse, FetchType } from '../public_types'; +/** + * Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the + * Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest). + * + * <p>Abstracts throttle, response cache and network implementation details. + * + * <p>Modeled after the native {@link GlobalFetch} interface, which is relatively modern and + * convenient, but simplified for Remote Config's use case. + * + * Disambiguation: {@link GlobalFetch} interface and the Remote Config service define "fetch" + * methods. The RestClient uses the former to make HTTP calls. This interface abstracts the latter. + */ +export interface RemoteConfigFetchClient { + /** + * @throws if response status is not 200 or 304. + */ + fetch(request: FetchRequest): Promise<FetchResponse>; +} +/** + * Shims a minimal AbortSignal. + * + * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects + * of networking, such as retries. Firebase doesn't use AbortController enough to justify a + * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be + * swapped out if/when we do. + */ +export declare class RemoteConfigAbortSignal { + listeners: Array<() => void>; + addEventListener(listener: () => void): void; + abort(): void; +} +/** + * Defines per-request inputs for the Remote Config fetch request. + * + * <p>Modeled after the native {@link Request} interface, but simplified for Remote Config's + * use case. + */ +export interface FetchRequest { + /** + * Uses cached config if it is younger than this age. + * + * <p>Required because it's defined by settings, which always have a value. + * + * <p>Comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the native + * Fetch API. + */ + cacheMaxAgeMillis: number; + /** + * An event bus for the signal to abort a request. + * + * <p>Required because all requests should be abortable. + * + * <p>Comparable to the native + * Fetch API's "signal" field on its request configuration object + * https://fetch.spec.whatwg.org/#dom-requestinit-signal. + * + * <p>Disambiguation: Remote Config commonly refers to API inputs as + * "signals". See the private ConfigFetchRequestBody interface for those: + * http://google3/firebase/remote_config/web/src/core/rest_client.ts?l=14&rcl=255515243. + */ + signal: RemoteConfigAbortSignal; + /** + * The ETag header value from the last response. + * + * <p>Optional in case this is the first request. + * + * <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API. + */ + eTag?: string; + /** The custom signals stored for the app instance. + * + * <p>Optional in case no custom signals are set for the instance. + */ + customSignals?: CustomSignals; + /** + * The type of fetch to perform, such as a regular fetch or a real-time fetch. + * + * Optional as not all fetch requests need to be distinguished. + */ + fetchType?: FetchType; + /** + * The number of fetch attempts made so far for this request. + * + * Optional as not all fetch requests are part of a retry series. + */ + fetchAttempt?: number; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/rest_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/rest_client.d.ts new file mode 100644 index 0000000..24a3fe0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/rest_client.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchResponse } from '../public_types'; +import { RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { _FirebaseInstallationsInternal } from '@firebase/installations'; +/** + * Implements the Client abstraction for the Remote Config REST API. + */ +export declare class RestClient implements RemoteConfigFetchClient { + private readonly firebaseInstallations; + private readonly sdkVersion; + private readonly namespace; + private readonly projectId; + private readonly apiKey; + private readonly appId; + constructor(firebaseInstallations: _FirebaseInstallationsInternal, sdkVersion: string, namespace: string, projectId: string, apiKey: string, appId: string); + /** + * Fetches from the Remote Config REST API. + * + * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't + * connect to the network. + * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the + * fetch response. + * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status. + */ + fetch(request: FetchRequest): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/retrying_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/retrying_client.d.ts new file mode 100644 index 0000000..06c7ff0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/retrying_client.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchResponse } from '../public_types'; +import { RemoteConfigAbortSignal, RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { ThrottleMetadata, Storage } from '../storage/storage'; +/** + * Supports waiting on a backoff by: + * + * <ul> + * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> + * <li>Listening on a signal bus for abort events, just like the Fetch API</li> + * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled + * request appear the same.</li> + * </ul> + * + * <p>Visible for testing. + */ +export declare function setAbortableTimeout(signal: RemoteConfigAbortSignal, throttleEndTimeMillis: number): Promise<void>; +/** + * Decorates a Client with retry logic. + * + * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache + * responses (because the SDK has no use for error responses). + */ +export declare class RetryingClient implements RemoteConfigFetchClient { + private readonly client; + private readonly storage; + constructor(client: RemoteConfigFetchClient, storage: Storage); + fetch(request: FetchRequest): Promise<FetchResponse>; + /** + * A recursive helper for attempting a fetch request repeatedly. + * + * @throws any non-retriable errors. + */ + attemptFetch(request: FetchRequest, { throttleEndTimeMillis, backoffCount }: ThrottleMetadata): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/visibility_monitor.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/visibility_monitor.d.ts new file mode 100644 index 0000000..ef40083 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/client/visibility_monitor.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './eventEmitter'; +export declare class VisibilityMonitor extends EventEmitter { + private visible_; + static getInstance(): VisibilityMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/constants.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/constants.d.ts new file mode 100644 index 0000000..1663d8f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/constants.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const RC_COMPONENT_NAME = "remote-config"; +export declare const RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 100; +export declare const RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH = 250; +export declare const RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH = 500; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/errors.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/errors.d.ts new file mode 100644 index 0000000..3cf0b55 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/errors.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ErrorFactory } from '@firebase/util'; +export declare const enum ErrorCode { + ALREADY_INITIALIZED = "already-initialized", + REGISTRATION_WINDOW = "registration-window", + REGISTRATION_PROJECT_ID = "registration-project-id", + REGISTRATION_API_KEY = "registration-api-key", + REGISTRATION_APP_ID = "registration-app-id", + STORAGE_OPEN = "storage-open", + STORAGE_GET = "storage-get", + STORAGE_SET = "storage-set", + STORAGE_DELETE = "storage-delete", + FETCH_NETWORK = "fetch-client-network", + FETCH_TIMEOUT = "fetch-timeout", + FETCH_THROTTLE = "fetch-throttle", + FETCH_PARSE = "fetch-client-parse", + FETCH_STATUS = "fetch-status", + INDEXED_DB_UNAVAILABLE = "indexed-db-unavailable", + CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = "custom-signal-max-allowed-signals", + CONFIG_UPDATE_STREAM_ERROR = "stream-error", + CONFIG_UPDATE_UNAVAILABLE = "realtime-unavailable", + CONFIG_UPDATE_MESSAGE_INVALID = "update-message-invalid", + CONFIG_UPDATE_NOT_FETCHED = "update-not-fetched" +} +interface ErrorParams { + [ErrorCode.STORAGE_OPEN]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_GET]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_SET]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_DELETE]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.FETCH_NETWORK]: { + originalErrorMessage: string; + }; + [ErrorCode.FETCH_THROTTLE]: { + throttleEndTimeMillis: number; + }; + [ErrorCode.FETCH_PARSE]: { + originalErrorMessage: string; + }; + [ErrorCode.FETCH_STATUS]: { + httpStatus: number; + }; + [ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS]: { + maxSignals: number; + }; + [ErrorCode.CONFIG_UPDATE_STREAM_ERROR]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_UNAVAILABLE]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_NOT_FETCHED]: { + originalErrorMessage: string; + }; +} +export declare const ERROR_FACTORY: ErrorFactory<ErrorCode, ErrorParams>; +export declare function hasErrorCode(e: Error, errorCode: ErrorCode): boolean; +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/index.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/index.d.ts new file mode 100644 index 0000000..fc0de52 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/index.d.ts @@ -0,0 +1,14 @@ +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +declare global { + interface Window { + FIREBASE_REMOTE_CONFIG_URL_BASE: string; + } +} +export * from './api'; +export * from './api2'; +export * from './public_types'; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/language.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/language.d.ts new file mode 100644 index 0000000..2bfc669 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/language.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Attempts to get the most accurate browser language setting. + * + * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript. + * + * <p>Defers default language specification to server logic for consistency. + * + * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}. + */ +export declare function getUserLanguage(navigatorLanguage?: NavigatorLanguage): string; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/public_types.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/public_types.d.ts new file mode 100644 index 0000000..5c58c66 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/public_types.d.ts @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp, FirebaseError } from '@firebase/app'; +/** + * The Firebase Remote Config service interface. + * + * @public + */ +export interface RemoteConfig { + /** + * The {@link @firebase/app#FirebaseApp} this `RemoteConfig` instance is associated with. + */ + app: FirebaseApp; + /** + * Defines configuration for the Remote Config SDK. + */ + settings: RemoteConfigSettings; + /** + * Object containing default values for configs. + */ + defaultConfig: { + [key: string]: string | number | boolean; + }; + /** + * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if + * the {@link RemoteConfig} instance either hasn't fetched or initialization + * is incomplete. + */ + fetchTimeMillis: number; + /** + * The status of the last fetch <i>attempt</i>. + */ + lastFetchStatus: FetchStatus; +} +/** + * Defines a self-descriptive reference for config key-value pairs. + * + * @public + */ +export interface FirebaseRemoteConfigObject { + [key: string]: string; +} +/** + * Defines a successful response (200 or 304). + * + * <p>Modeled after the native `Response` interface, but simplified for Remote Config's + * use case. + * + * @public + */ +export interface FetchResponse { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * <p>The Remote Config client is modeled after the native `Fetch` interface, so + * HTTP status is first-class. + * + * <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the + * HTTP status code. The former is normalized into the latter. + */ + status: number; + /** + * Defines the ETag response header value. + * + * <p>Only defined for 200 and 304 responses. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + * + * <p>Only defined for 200 responses. + */ + config?: FirebaseRemoteConfigObject; + /** + * The version number of the config template fetched from the server. + */ + templateVersion?: number; +} +/** + * Options for Remote Config initialization. + * + * @public + */ +export interface RemoteConfigOptions { + /** + * The ID of the template to use. If not provided, defaults to "firebase". + */ + templateId?: string; + /** + * Hydrates the state with an initial fetch response. + */ + initialFetchResponse?: FetchResponse; +} +/** + * Indicates the source of a value. + * + * <ul> + * <li>"static" indicates the value was defined by a static constant.</li> + * <li>"default" indicates the value was defined by default config.</li> + * <li>"remote" indicates the value was defined by fetched config.</li> + * </ul> + * + * @public + */ +export type ValueSource = 'static' | 'default' | 'remote'; +/** + * Wraps a value with metadata and type-safe getters. + * + * @public + */ +export interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case-insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} +/** + * Defines configuration options for the Remote Config SDK. + * + * @public + */ +export interface RemoteConfigSettings { + /** + * Defines the maximum age in milliseconds of an entry in the config cache before + * it is considered stale. Defaults to 43200000 (Twelve hours). + */ + minimumFetchIntervalMillis: number; + /** + * Defines the maximum amount of milliseconds to wait for a response when fetching + * configuration from the Remote Config server. Defaults to 60000 (One minute). + */ + fetchTimeoutMillis: number; +} +/** + * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server. + * + * <ul> + * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted + * to fetch config, or that SDK initialization is incomplete.</li> + * <li>"success" indicates the last attempt succeeded.</li> + * <li>"failure" indicates the last attempt failed.</li> + * <li>"throttle" indicates the last attempt was rate-limited.</li> + * </ul> + * + * @public + */ +export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; +/** + * Defines levels of Remote Config logging. + * + * @public + */ +export type LogLevel = 'debug' | 'error' | 'silent'; +/** + * Defines the type for representing custom signals and their values. + * + * <p>The values in CustomSignals must be one of the following types: + * + * <ul> + * <li><code>string</code> + * <li><code>number</code> + * <li><code>null</code> + * </ul> + * + * @public + */ +export interface CustomSignals { + [key: string]: string | number | null; +} +/** + * Contains information about which keys have been updated. + * + * @public + */ +export interface ConfigUpdate { + /** + * Parameter keys whose values have been updated from the currently activated values. + * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. + */ + getUpdatedKeys(): Set<string>; +} +/** + * Observer interface for receiving real-time Remote Config update notifications. + * + * NOTE: Although an `complete` callback can be provided, it will + * never be called because the ConfigUpdate stream is never-ending. + * + * @public + */ +export interface ConfigUpdateObserver { + /** + * Called when a new ConfigUpdate is available. + */ + next: (configUpdate: ConfigUpdate) => void; + /** + * Called if an error occurs during the stream. + */ + error: (error: FirebaseError) => void; + /** + * Called when the stream is gracefully terminated. + */ + complete: () => void; +} +/** + * A function that unsubscribes from a real-time event stream. + * + * @public + */ +export type Unsubscribe = () => void; +/** + * Indicates the type of fetch request. + * + * <ul> + * <li>"BASE" indicates a standard fetch request.</li> + * <li>"REALTIME" indicates a fetch request triggered by a real-time update.</li> + * </ul> + * + * @public + */ +export type FetchType = 'BASE' | 'REALTIME'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'remote-config': RemoteConfig; + } +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/register.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/register.d.ts new file mode 100644 index 0000000..5aab5ab --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/register.d.ts @@ -0,0 +1,2 @@ +import '@firebase/installations'; +export declare function registerRemoteConfig(): void; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/remote_config.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/remote_config.d.ts new file mode 100644 index 0000000..e72b28f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/remote_config.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { RemoteConfig as RemoteConfigType, FetchStatus, RemoteConfigSettings } from './public_types'; +import { StorageCache } from './storage/storage_cache'; +import { RemoteConfigFetchClient } from './client/remote_config_fetch_client'; +import { Storage } from './storage/storage'; +import { Logger } from '@firebase/logger'; +import { RealtimeHandler } from './client/realtime_handler'; +/** + * Encapsulates business logic mapping network and storage dependencies to the public SDK API. + * + * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/compat/index.d.ts|interface documentation} for method descriptions. + */ +export declare class RemoteConfig implements RemoteConfigType { + readonly app: FirebaseApp; + /** + * @internal + */ + readonly _client: RemoteConfigFetchClient; + /** + * @internal + */ + readonly _storageCache: StorageCache; + /** + * @internal + */ + readonly _storage: Storage; + /** + * @internal + */ + readonly _logger: Logger; + /** + * @internal + */ + readonly _realtimeHandler: RealtimeHandler; + /** + * Tracks completion of initialization promise. + * @internal + */ + _isInitializationComplete: boolean; + /** + * De-duplicates initialization calls. + * @internal + */ + _initializePromise?: Promise<void>; + settings: RemoteConfigSettings; + defaultConfig: { + [key: string]: string | number | boolean; + }; + get fetchTimeMillis(): number; + get lastFetchStatus(): FetchStatus; + constructor(app: FirebaseApp, + /** + * @internal + */ + _client: RemoteConfigFetchClient, + /** + * @internal + */ + _storageCache: StorageCache, + /** + * @internal + */ + _storage: Storage, + /** + * @internal + */ + _logger: Logger, + /** + * @internal + */ + _realtimeHandler: RealtimeHandler); +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage.d.ts new file mode 100644 index 0000000..df20b57 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage.d.ts @@ -0,0 +1,116 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchStatus, CustomSignals } from '@firebase/remote-config-types'; +import { FetchResponse, FirebaseRemoteConfigObject } from '../public_types'; +/** + * A general-purpose store keyed by app + namespace + {@link + * ProjectNamespaceKeyFieldValue}. + * + * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact + * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys + * for a set of key-value pairs. See {@link Storage#createCompositeKey}. + * + * <p>Visible for testing. + */ +export declare const APP_NAMESPACE_STORE = "app_namespace_store"; +/** + * Encapsulates metadata concerning throttled fetch requests. + */ +export interface ThrottleMetadata { + backoffCount: number; + throttleEndTimeMillis: number; +} +export interface RealtimeBackoffMetadata { + numFailedStreams: number; + backoffEndTimeMillis: Date; +} +/** + * Provides type-safety for the "key" field used by {@link APP_NAMESPACE_STORE}. + * + * <p>This seems like a small price to avoid potentially subtle bugs caused by a typo. + */ +type ProjectNamespaceKeyFieldValue = 'active_config' | 'active_config_etag' | 'last_fetch_status' | 'last_successful_fetch_timestamp_millis' | 'last_successful_fetch_response' | 'settings' | 'throttle_metadata' | 'custom_signals' | 'realtime_backoff_metadata' | 'last_known_template_version'; +export declare function openDatabase(): Promise<IDBDatabase>; +/** + * Abstracts data persistence. + */ +export declare abstract class Storage { + getLastFetchStatus(): Promise<FetchStatus | undefined>; + setLastFetchStatus(status: FetchStatus): Promise<void>; + getLastSuccessfulFetchTimestampMillis(): Promise<number | undefined>; + setLastSuccessfulFetchTimestampMillis(timestamp: number): Promise<void>; + getLastSuccessfulFetchResponse(): Promise<FetchResponse | undefined>; + setLastSuccessfulFetchResponse(response: FetchResponse): Promise<void>; + getActiveConfig(): Promise<FirebaseRemoteConfigObject | undefined>; + setActiveConfig(config: FirebaseRemoteConfigObject): Promise<void>; + getActiveConfigEtag(): Promise<string | undefined>; + setActiveConfigEtag(etag: string): Promise<void>; + getThrottleMetadata(): Promise<ThrottleMetadata | undefined>; + setThrottleMetadata(metadata: ThrottleMetadata): Promise<void>; + deleteThrottleMetadata(): Promise<void>; + getCustomSignals(): Promise<CustomSignals | undefined>; + abstract setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; + abstract get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined>; + abstract set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + abstract delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + getRealtimeBackoffMetadata(): Promise<RealtimeBackoffMetadata | undefined>; + setRealtimeBackoffMetadata(realtimeMetadata: RealtimeBackoffMetadata): Promise<void>; + getActiveConfigTemplateVersion(): Promise<number | undefined>; + setActiveConfigTemplateVersion(version: number): Promise<void>; +} +export declare class IndexedDbStorage extends Storage { + private readonly appId; + private readonly appName; + private readonly namespace; + private readonly openDbPromise; + /** + * @param appId enables storage segmentation by app (ID + name). + * @param appName enables storage segmentation by app (ID + name). + * @param namespace enables storage segmentation by namespace. + */ + constructor(appId: string, appName: string, namespace: string, openDbPromise?: Promise<IDBDatabase>); + setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; + /** + * Gets a value from the database using the provided transaction. + * + * @param key The key of the value to get. + * @param transaction The transaction to use for the operation. + * @returns The value associated with the key, or undefined if no such value exists. + */ + getWithTransaction<T>(key: ProjectNamespaceKeyFieldValue, transaction: IDBTransaction): Promise<T | undefined>; + /** + * Sets a value in the database using the provided transaction. + * + * @param key The key of the value to set. + * @param value The value to set. + * @param transaction The transaction to use for the operation. + * @returns A promise that resolves when the operation is complete. + */ + setWithTransaction<T>(key: ProjectNamespaceKeyFieldValue, value: T, transaction: IDBTransaction): Promise<void>; + get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined>; + set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + createCompositeKey(key: ProjectNamespaceKeyFieldValue): string; +} +export declare class InMemoryStorage extends Storage { + private storage; + get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T>; + set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage_cache.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage_cache.d.ts new file mode 100644 index 0000000..e61c523 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/storage/storage_cache.d.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchStatus, CustomSignals } from '@firebase/remote-config-types'; +import { FirebaseRemoteConfigObject } from '../public_types'; +import { Storage } from './storage'; +/** + * A memory cache layer over storage to support the SDK's synchronous read requirements. + */ +export declare class StorageCache { + private readonly storage; + constructor(storage: Storage); + /** + * Memory caches. + */ + private lastFetchStatus?; + private lastSuccessfulFetchTimestampMillis?; + private activeConfig?; + private customSignals?; + /** + * Memory-only getters + */ + getLastFetchStatus(): FetchStatus | undefined; + getLastSuccessfulFetchTimestampMillis(): number | undefined; + getActiveConfig(): FirebaseRemoteConfigObject | undefined; + getCustomSignals(): CustomSignals | undefined; + /** + * Read-ahead getter + */ + loadFromStorage(): Promise<void>; + /** + * Write-through setters + */ + setLastFetchStatus(status: FetchStatus): Promise<void>; + setLastSuccessfulFetchTimestampMillis(timestampMillis: number): Promise<void>; + setActiveConfig(activeConfig: FirebaseRemoteConfigObject): Promise<void>; + setCustomSignals(customSignals: CustomSignals): Promise<void>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/value.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/value.d.ts new file mode 100644 index 0000000..13e29c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/src/value.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value as ValueType, ValueSource } from '@firebase/remote-config-types'; +export declare class Value implements ValueType { + private readonly _source; + private readonly _value; + constructor(_source: ValueSource, _value?: string); + asString(): string; + asBoolean(): boolean; + asNumber(): number; + getSource(): ValueSource; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/esm/test/setup.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/esm/test/setup.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/esm/test/setup.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js b/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js new file mode 100644 index 0000000..dacd9fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js @@ -0,0 +1,2137 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var util = require('@firebase/util'); +var component = require('@firebase/component'); +var logger = require('@firebase/logger'); +require('@firebase/installations'); + +const name = "@firebase/remote-config"; +const version = "0.7.0"; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Shims a minimal AbortSignal. + * + * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects + * of networking, such as retries. Firebase doesn't use AbortController enough to justify a + * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be + * swapped out if/when we do. + */ +class RemoteConfigAbortSignal { + constructor() { + this.listeners = []; + } + addEventListener(listener) { + this.listeners.push(listener); + } + abort() { + this.listeners.forEach(listener => listener()); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RC_COMPONENT_NAME = 'remote-config'; +const RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 100; +const RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH = 250; +const RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH = 500; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ERROR_DESCRIPTION_MAP = { + ["already-initialized" /* ErrorCode.ALREADY_INITIALIZED */]: 'Remote Config already initialized', + ["registration-window" /* ErrorCode.REGISTRATION_WINDOW */]: 'Undefined window object. This SDK only supports usage in a browser environment.', + ["registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */]: 'Undefined project identifier. Check Firebase app initialization.', + ["registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */]: 'Undefined API key. Check Firebase app initialization.', + ["registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */]: 'Undefined app identifier. Check Firebase app initialization.', + ["storage-open" /* ErrorCode.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.', + ["storage-get" /* ErrorCode.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.', + ["storage-set" /* ErrorCode.STORAGE_SET */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.', + ["storage-delete" /* ErrorCode.STORAGE_DELETE */]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.', + ["fetch-client-network" /* ErrorCode.FETCH_NETWORK */]: 'Fetch client failed to connect to a network. Check Internet connection.' + + ' Original error: {$originalErrorMessage}.', + ["fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */]: 'The config fetch request timed out. ' + + ' Configure timeout using "fetchTimeoutMillis" SDK setting.', + ["fetch-throttle" /* ErrorCode.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' + + ' Configure timeout using "fetchTimeoutMillis" SDK setting.' + + ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.', + ["fetch-client-parse" /* ErrorCode.FETCH_PARSE */]: 'Fetch client could not parse response.' + + ' Original error: {$originalErrorMessage}.', + ["fetch-status" /* ErrorCode.FETCH_STATUS */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.', + ["indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */]: 'Indexed DB is not supported by current browser', + ["custom-signal-max-allowed-signals" /* ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS */]: 'Setting more than {$maxSignals} custom signals is not supported.', + ["stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */]: 'The stream was not able to connect to the backend: {$originalErrorMessage}.', + ["realtime-unavailable" /* ErrorCode.CONFIG_UPDATE_UNAVAILABLE */]: 'The Realtime service is unavailable: {$originalErrorMessage}', + ["update-message-invalid" /* ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID */]: 'The stream invalidation message was unparsable: {$originalErrorMessage}', + ["update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */]: 'Unable to fetch the latest config: {$originalErrorMessage}' +}; +const ERROR_FACTORY = new util.ErrorFactory('remoteconfig' /* service */, 'Remote Config' /* service name */, ERROR_DESCRIPTION_MAP); +// Note how this is like typeof/instanceof, but for ErrorCode. +function hasErrorCode(e, errorCode) { + return e instanceof util.FirebaseError && e.code.indexOf(errorCode) !== -1; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_VALUE_FOR_BOOLEAN = false; +const DEFAULT_VALUE_FOR_STRING = ''; +const DEFAULT_VALUE_FOR_NUMBER = 0; +const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on']; +class Value { + constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) { + this._source = _source; + this._value = _value; + } + asString() { + return this._value; + } + asBoolean() { + if (this._source === 'static') { + return DEFAULT_VALUE_FOR_BOOLEAN; + } + return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0; + } + asNumber() { + if (this._source === 'static') { + return DEFAULT_VALUE_FOR_NUMBER; + } + let num = Number(this._value); + if (isNaN(num)) { + num = DEFAULT_VALUE_FOR_NUMBER; + } + return num; + } + getSource() { + return this._source; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +function getRemoteConfig(app$1 = app.getApp(), options = {}) { + app$1 = util.getModularInstance(app$1); + const rcProvider = app._getProvider(app$1, RC_COMPONENT_NAME); + if (rcProvider.isInitialized()) { + const initialOptions = rcProvider.getOptions(); + if (util.deepEqual(initialOptions, options)) { + return rcProvider.getImmediate(); + } + throw ERROR_FACTORY.create("already-initialized" /* ErrorCode.ALREADY_INITIALIZED */); + } + rcProvider.initialize({ options }); + const rc = rcProvider.getImmediate(); + if (options.initialFetchResponse) { + // We use these initial writes as the initialization promise since they will hydrate the same + // fields that `storageCache.loadFromStorage` would set. + rc._initializePromise = Promise.all([ + rc._storage.setLastSuccessfulFetchResponse(options.initialFetchResponse), + rc._storage.setActiveConfigEtag(options.initialFetchResponse?.eTag || ''), + rc._storage.setActiveConfigTemplateVersion(options.initialFetchResponse.templateVersion || 0), + rc._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()), + rc._storageCache.setLastFetchStatus('success'), + rc._storageCache.setActiveConfig(options.initialFetchResponse?.config || {}) + ]).then(); + // The `storageCache` methods above set their in-memory fields synchronously, so it's + // safe to declare our initialization complete at this point. + rc._isInitializationComplete = true; + } + return rc; +} +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +async function activate(remoteConfig) { + const rc = util.getModularInstance(remoteConfig); + const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([ + rc._storage.getLastSuccessfulFetchResponse(), + rc._storage.getActiveConfigEtag() + ]); + if (!lastSuccessfulFetchResponse || + !lastSuccessfulFetchResponse.config || + !lastSuccessfulFetchResponse.eTag || + !lastSuccessfulFetchResponse.templateVersion || + lastSuccessfulFetchResponse.eTag === activeConfigEtag) { + // Either there is no successful fetched config, or is the same as current active + // config. + return false; + } + await Promise.all([ + rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config), + rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag), + rc._storage.setActiveConfigTemplateVersion(lastSuccessfulFetchResponse.templateVersion) + ]); + return true; +} +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +function ensureInitialized(remoteConfig) { + const rc = util.getModularInstance(remoteConfig); + if (!rc._initializePromise) { + rc._initializePromise = rc._storageCache.loadFromStorage().then(() => { + rc._isInitializationComplete = true; + }); + } + return rc._initializePromise; +} +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +async function fetchConfig(remoteConfig) { + const rc = util.getModularInstance(remoteConfig); + // Aborts the request after the given timeout, causing the fetch call to + // reject with an `AbortError`. + // + // <p>Aborting after the request completes is a no-op, so we don't need a + // corresponding `clearTimeout`. + // + // Locating abort logic here because: + // * it uses a developer setting (timeout) + // * it applies to all retries (like curl's max-time arg) + // * it is consistent with the Fetch API's signal input + const abortSignal = new RemoteConfigAbortSignal(); + setTimeout(async () => { + // Note a very low delay, eg < 10ms, can elapse before listeners are initialized. + abortSignal.abort(); + }, rc.settings.fetchTimeoutMillis); + const customSignals = rc._storageCache.getCustomSignals(); + if (customSignals) { + rc._logger.debug(`Fetching config with custom signals: ${JSON.stringify(customSignals)}`); + } + // Catches *all* errors thrown by client so status can be set consistently. + try { + await rc._client.fetch({ + cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis, + signal: abortSignal, + customSignals + }); + await rc._storageCache.setLastFetchStatus('success'); + } + catch (e) { + const lastFetchStatus = hasErrorCode(e, "fetch-throttle" /* ErrorCode.FETCH_THROTTLE */) + ? 'throttle' + : 'failure'; + await rc._storageCache.setLastFetchStatus(lastFetchStatus); + throw e; + } +} +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +function getAll(remoteConfig) { + const rc = util.getModularInstance(remoteConfig); + return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => { + allConfigs[key] = getValue(remoteConfig, key); + return allConfigs; + }, {}); +} +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +function getBoolean(remoteConfig, key) { + return getValue(util.getModularInstance(remoteConfig), key).asBoolean(); +} +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +function getNumber(remoteConfig, key) { + return getValue(util.getModularInstance(remoteConfig), key).asNumber(); +} +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +function getString(remoteConfig, key) { + return getValue(util.getModularInstance(remoteConfig), key).asString(); +} +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +function getValue(remoteConfig, key) { + const rc = util.getModularInstance(remoteConfig); + if (!rc._isInitializationComplete) { + rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` + + ' Await on ensureInitialized if the intent was to get a previously activated value.'); + } + const activeConfig = rc._storageCache.getActiveConfig(); + if (activeConfig && activeConfig[key] !== undefined) { + return new Value('remote', activeConfig[key]); + } + else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) { + return new Value('default', String(rc.defaultConfig[key])); + } + rc._logger.debug(`Returning static value for key "${key}".` + + ' Define a default or remote value if this is unintentional.'); + return new Value('static'); +} +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +function setLogLevel(remoteConfig, logLevel) { + const rc = util.getModularInstance(remoteConfig); + switch (logLevel) { + case 'debug': + rc._logger.logLevel = logger.LogLevel.DEBUG; + break; + case 'silent': + rc._logger.logLevel = logger.LogLevel.SILENT; + break; + default: + rc._logger.logLevel = logger.LogLevel.ERROR; + } +} +/** + * Dedupes and returns an array of all the keys of the received objects. + */ +function getAllKeys(obj1 = {}, obj2 = {}) { + return Object.keys({ ...obj1, ...obj2 }); +} +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +async function setCustomSignals(remoteConfig, customSignals) { + const rc = util.getModularInstance(remoteConfig); + if (Object.keys(customSignals).length === 0) { + return; + } + // eslint-disable-next-line guard-for-in + for (const key in customSignals) { + if (key.length > RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH) { + rc._logger.error(`Custom signal key ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH}.`); + return; + } + const value = customSignals[key]; + if (typeof value === 'string' && + value.length > RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH) { + rc._logger.error(`Value supplied for custom signal ${key} is too long, max allowed length is ${RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH}.`); + return; + } + } + try { + await rc._storageCache.setCustomSignals(customSignals); + } + catch (error) { + rc._logger.error(`Error encountered while setting custom signals: ${error}`); + } +} +// TODO: Add public document for the Remote Config Realtime API guide on the Web Platform. +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +function onConfigUpdate(remoteConfig, observer) { + const rc = util.getModularInstance(remoteConfig); + rc._realtimeHandler.addObserver(observer); + return () => { + rc._realtimeHandler.removeObserver(observer); + }; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implements the {@link RemoteConfigClient} abstraction with success response caching. + * + * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service + * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the + * Cache API doesn't support matching entries by time. + */ +class CachingClient { + constructor(client, storage, storageCache, logger) { + this.client = client; + this.storage = storage; + this.storageCache = storageCache; + this.logger = logger; + } + /** + * Returns true if the age of the cached fetched configs is less than or equal to + * {@link Settings#minimumFetchIntervalInSeconds}. + * + * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the + * native Fetch API. + * + * <p>Visible for testing. + */ + isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) { + // Cache can only be fresh if it's populated. + if (!lastSuccessfulFetchTimestampMillis) { + this.logger.debug('Config fetch cache check. Cache unpopulated.'); + return false; + } + // Calculates age of cache entry. + const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis; + const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis; + this.logger.debug('Config fetch cache check.' + + ` Cache age millis: ${cacheAgeMillis}.` + + ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` + + ` Is cache hit: ${isCachedDataFresh}.`); + return isCachedDataFresh; + } + async fetch(request) { + // Reads from persisted storage to avoid cache miss if callers don't wait on initialization. + const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([ + this.storage.getLastSuccessfulFetchTimestampMillis(), + this.storage.getLastSuccessfulFetchResponse() + ]); + // Exits early on cache hit. + if (lastSuccessfulFetchResponse && + this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) { + return lastSuccessfulFetchResponse; + } + // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API + // that allows the caller to pass an ETag. + request.eTag = + lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag; + // Falls back to service on cache miss. + const response = await this.client.fetch(request); + // Fetch throws for non-success responses, so success is guaranteed here. + const storageOperations = [ + // Uses write-through cache for consistency with synchronous public API. + this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()) + ]; + if (response.status === 200) { + // Caches response only if it has changed, ie non-304 responses. + storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response)); + } + await Promise.all(storageOperations); + return response; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Attempts to get the most accurate browser language setting. + * + * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript. + * + * <p>Defers default language specification to server logic for consistency. + * + * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}. + */ +function getUserLanguage(navigatorLanguage = navigator) { + return ( + // Most reliable, but only supported in Chrome/Firefox. + (navigatorLanguage.languages && navigatorLanguage.languages[0]) || + // Supported in most browsers, but returns the language of the browser + // UI, not the language set in browser settings. + navigatorLanguage.language + // Polyfill otherwise. + ); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implements the Client abstraction for the Remote Config REST API. + */ +class RestClient { + constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) { + this.firebaseInstallations = firebaseInstallations; + this.sdkVersion = sdkVersion; + this.namespace = namespace; + this.projectId = projectId; + this.apiKey = apiKey; + this.appId = appId; + } + /** + * Fetches from the Remote Config REST API. + * + * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't + * connect to the network. + * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the + * fetch response. + * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status. + */ + async fetch(request) { + const [installationId, installationToken] = await Promise.all([ + this.firebaseInstallations.getId(), + this.firebaseInstallations.getToken() + ]); + const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE || + 'https://firebaseremoteconfig.googleapis.com'; + const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`; + const headers = { + 'Content-Type': 'application/json', + 'Content-Encoding': 'gzip', + // Deviates from pure decorator by not passing max-age header since we don't currently have + // service behavior using that header. + 'If-None-Match': request.eTag || '*' + // TODO: Add this header once CORS error is fixed internally. + //'X-Firebase-RC-Fetch-Type': `${fetchType}/${fetchAttempt}` + }; + const requestBody = { + /* eslint-disable camelcase */ + sdk_version: this.sdkVersion, + app_instance_id: installationId, + app_instance_id_token: installationToken, + app_id: this.appId, + language_code: getUserLanguage(), + custom_signals: request.customSignals + /* eslint-enable camelcase */ + }; + const options = { + method: 'POST', + headers, + body: JSON.stringify(requestBody) + }; + // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator. + const fetchPromise = fetch(url, options); + const timeoutPromise = new Promise((_resolve, reject) => { + // Maps async event listener to Promise API. + request.signal.addEventListener(() => { + // Emulates https://heycam.github.io/webidl/#aborterror + const error = new Error('The operation was aborted.'); + error.name = 'AbortError'; + reject(error); + }); + }); + let response; + try { + await Promise.race([fetchPromise, timeoutPromise]); + response = await fetchPromise; + } + catch (originalError) { + let errorCode = "fetch-client-network" /* ErrorCode.FETCH_NETWORK */; + if (originalError?.name === 'AbortError') { + errorCode = "fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */; + } + throw ERROR_FACTORY.create(errorCode, { + originalErrorMessage: originalError?.message + }); + } + let status = response.status; + // Normalizes nullable header to optional. + const responseEtag = response.headers.get('ETag') || undefined; + let config; + let state; + let templateVersion; + // JSON parsing throws SyntaxError if the response body isn't a JSON string. + // Requesting application/json and checking for a 200 ensures there's JSON data. + if (response.status === 200) { + let responseBody; + try { + responseBody = await response.json(); + } + catch (originalError) { + throw ERROR_FACTORY.create("fetch-client-parse" /* ErrorCode.FETCH_PARSE */, { + originalErrorMessage: originalError?.message + }); + } + config = responseBody['entries']; + state = responseBody['state']; + templateVersion = responseBody['templateVersion']; + } + // Normalizes based on legacy state. + if (state === 'INSTANCE_STATE_UNSPECIFIED') { + status = 500; + } + else if (state === 'NO_CHANGE') { + status = 304; + } + else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') { + // These cases can be fixed remotely, so normalize to safe value. + config = {}; + } + // Normalize to exception-based control flow for non-success cases. + // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for + // differentiating success states (200 from 304; the state body param is undefined in a + // standard 304). + if (status !== 304 && status !== 200) { + throw ERROR_FACTORY.create("fetch-status" /* ErrorCode.FETCH_STATUS */, { + httpStatus: status + }); + } + return { status, eTag: responseEtag, config, templateVersion }; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Supports waiting on a backoff by: + * + * <ul> + * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> + * <li>Listening on a signal bus for abort events, just like the Fetch API</li> + * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled + * request appear the same.</li> + * </ul> + * + * <p>Visible for testing. + */ +function setAbortableTimeout(signal, throttleEndTimeMillis) { + return new Promise((resolve, reject) => { + // Derives backoff from given end time, normalizing negative numbers to zero. + const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0); + const timeout = setTimeout(resolve, backoffMillis); + // Adds listener, rather than sets onabort, because signal is a shared object. + signal.addEventListener(() => { + clearTimeout(timeout); + // If the request completes before this timeout, the rejection has no effect. + reject(ERROR_FACTORY.create("fetch-throttle" /* ErrorCode.FETCH_THROTTLE */, { + throttleEndTimeMillis + })); + }); + }); +} +/** + * Returns true if the {@link Error} indicates a fetch request may succeed later. + */ +function isRetriableError(e) { + if (!(e instanceof util.FirebaseError) || !e.customData) { + return false; + } + // Uses string index defined by ErrorData, which FirebaseError implements. + const httpStatus = Number(e.customData['httpStatus']); + return (httpStatus === 429 || + httpStatus === 500 || + httpStatus === 503 || + httpStatus === 504); +} +/** + * Decorates a Client with retry logic. + * + * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache + * responses (because the SDK has no use for error responses). + */ +class RetryingClient { + constructor(client, storage) { + this.client = client; + this.storage = storage; + } + async fetch(request) { + const throttleMetadata = (await this.storage.getThrottleMetadata()) || { + backoffCount: 0, + throttleEndTimeMillis: Date.now() + }; + return this.attemptFetch(request, throttleMetadata); + } + /** + * A recursive helper for attempting a fetch request repeatedly. + * + * @throws any non-retriable errors. + */ + async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) { + // Starts with a (potentially zero) timeout to support resumption from stored state. + // Ensures the throttle end time is honored if the last attempt timed out. + // Note the SDK will never make a request if the fetch timeout expires at this point. + await setAbortableTimeout(request.signal, throttleEndTimeMillis); + try { + const response = await this.client.fetch(request); + // Note the SDK only clears throttle state if response is success or non-retriable. + await this.storage.deleteThrottleMetadata(); + return response; + } + catch (e) { + if (!isRetriableError(e)) { + throw e; + } + // Increments backoff state. + const throttleMetadata = { + throttleEndTimeMillis: Date.now() + util.calculateBackoffMillis(backoffCount), + backoffCount: backoffCount + 1 + }; + // Persists state. + await this.storage.setThrottleMetadata(throttleMetadata); + return this.attemptFetch(request, throttleMetadata); + } + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute +const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours. +/** + * Encapsulates business logic mapping network and storage dependencies to the public SDK API. + * + * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/compat/index.d.ts|interface documentation} for method descriptions. + */ +class RemoteConfig { + get fetchTimeMillis() { + return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1; + } + get lastFetchStatus() { + return this._storageCache.getLastFetchStatus() || 'no-fetch-yet'; + } + constructor( + // Required by FirebaseServiceFactory interface. + app, + // JS doesn't support private yet + // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an + // underscore prefix. + /** + * @internal + */ + _client, + /** + * @internal + */ + _storageCache, + /** + * @internal + */ + _storage, + /** + * @internal + */ + _logger, + /** + * @internal + */ + _realtimeHandler) { + this.app = app; + this._client = _client; + this._storageCache = _storageCache; + this._storage = _storage; + this._logger = _logger; + this._realtimeHandler = _realtimeHandler; + /** + * Tracks completion of initialization promise. + * @internal + */ + this._isInitializationComplete = false; + this.settings = { + fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS, + minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS + }; + this.defaultConfig = {}; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}. + */ +function toFirebaseError(event, errorCode) { + const originalError = event.target.error || undefined; + return ERROR_FACTORY.create(errorCode, { + originalErrorMessage: originalError && originalError?.message + }); +} +/** + * A general-purpose store keyed by app + namespace + {@link + * ProjectNamespaceKeyFieldValue}. + * + * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact + * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys + * for a set of key-value pairs. See {@link Storage#createCompositeKey}. + * + * <p>Visible for testing. + */ +const APP_NAMESPACE_STORE = 'app_namespace_store'; +const DB_NAME = 'firebase_remote_config'; +const DB_VERSION = 1; +// Visible for testing. +function openDatabase() { + return new Promise((resolve, reject) => { + try { + const request = indexedDB.open(DB_NAME, DB_VERSION); + request.onerror = event => { + reject(toFirebaseError(event, "storage-open" /* ErrorCode.STORAGE_OPEN */)); + }; + request.onsuccess = event => { + resolve(event.target.result); + }; + request.onupgradeneeded = event => { + const db = event.target.result; + // We don't use 'break' in this switch statement, the fall-through + // behavior is what we want, because if there are multiple versions between + // the old version and the current version, we want ALL the migrations + // that correspond to those versions to run, not only the last one. + // eslint-disable-next-line default-case + switch (event.oldVersion) { + case 0: + db.createObjectStore(APP_NAMESPACE_STORE, { + keyPath: 'compositeKey' + }); + } + }; + } + catch (error) { + reject(ERROR_FACTORY.create("storage-open" /* ErrorCode.STORAGE_OPEN */, { + originalErrorMessage: error?.message + })); + } + }); +} +/** + * Abstracts data persistence. + */ +class Storage { + getLastFetchStatus() { + return this.get('last_fetch_status'); + } + setLastFetchStatus(status) { + return this.set('last_fetch_status', status); + } + // This is comparable to a cache entry timestamp. If we need to expire other data, we could + // consider adding timestamp to all storage records and an optional max age arg to getters. + getLastSuccessfulFetchTimestampMillis() { + return this.get('last_successful_fetch_timestamp_millis'); + } + setLastSuccessfulFetchTimestampMillis(timestamp) { + return this.set('last_successful_fetch_timestamp_millis', timestamp); + } + getLastSuccessfulFetchResponse() { + return this.get('last_successful_fetch_response'); + } + setLastSuccessfulFetchResponse(response) { + return this.set('last_successful_fetch_response', response); + } + getActiveConfig() { + return this.get('active_config'); + } + setActiveConfig(config) { + return this.set('active_config', config); + } + getActiveConfigEtag() { + return this.get('active_config_etag'); + } + setActiveConfigEtag(etag) { + return this.set('active_config_etag', etag); + } + getThrottleMetadata() { + return this.get('throttle_metadata'); + } + setThrottleMetadata(metadata) { + return this.set('throttle_metadata', metadata); + } + deleteThrottleMetadata() { + return this.delete('throttle_metadata'); + } + getCustomSignals() { + return this.get('custom_signals'); + } + getRealtimeBackoffMetadata() { + return this.get('realtime_backoff_metadata'); + } + setRealtimeBackoffMetadata(realtimeMetadata) { + return this.set('realtime_backoff_metadata', realtimeMetadata); + } + getActiveConfigTemplateVersion() { + return this.get('last_known_template_version'); + } + setActiveConfigTemplateVersion(version) { + return this.set('last_known_template_version', version); + } +} +class IndexedDbStorage extends Storage { + /** + * @param appId enables storage segmentation by app (ID + name). + * @param appName enables storage segmentation by app (ID + name). + * @param namespace enables storage segmentation by namespace. + */ + constructor(appId, appName, namespace, openDbPromise = openDatabase()) { + super(); + this.appId = appId; + this.appName = appName; + this.namespace = namespace; + this.openDbPromise = openDbPromise; + } + async setCustomSignals(customSignals) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + const storedSignals = await this.getWithTransaction('custom_signals', transaction); + const updatedSignals = mergeCustomSignals(customSignals, storedSignals || {}); + await this.setWithTransaction('custom_signals', updatedSignals, transaction); + return updatedSignals; + } + /** + * Gets a value from the database using the provided transaction. + * + * @param key The key of the value to get. + * @param transaction The transaction to use for the operation. + * @returns The value associated with the key, or undefined if no such value exists. + */ + async getWithTransaction(key, transaction) { + return new Promise((resolve, reject) => { + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.get(compositeKey); + request.onerror = event => { + reject(toFirebaseError(event, "storage-get" /* ErrorCode.STORAGE_GET */)); + }; + request.onsuccess = event => { + const result = event.target.result; + if (result) { + resolve(result.value); + } + else { + resolve(undefined); + } + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-get" /* ErrorCode.STORAGE_GET */, { + originalErrorMessage: e?.message + })); + } + }); + } + /** + * Sets a value in the database using the provided transaction. + * + * @param key The key of the value to set. + * @param value The value to set. + * @param transaction The transaction to use for the operation. + * @returns A promise that resolves when the operation is complete. + */ + async setWithTransaction(key, value, transaction) { + return new Promise((resolve, reject) => { + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.put({ + compositeKey, + value + }); + request.onerror = (event) => { + reject(toFirebaseError(event, "storage-set" /* ErrorCode.STORAGE_SET */)); + }; + request.onsuccess = () => { + resolve(); + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-set" /* ErrorCode.STORAGE_SET */, { + originalErrorMessage: e?.message + })); + } + }); + } + async get(key) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly'); + return this.getWithTransaction(key, transaction); + } + async set(key, value) { + const db = await this.openDbPromise; + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + return this.setWithTransaction(key, value, transaction); + } + async delete(key) { + const db = await this.openDbPromise; + return new Promise((resolve, reject) => { + const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite'); + const objectStore = transaction.objectStore(APP_NAMESPACE_STORE); + const compositeKey = this.createCompositeKey(key); + try { + const request = objectStore.delete(compositeKey); + request.onerror = (event) => { + reject(toFirebaseError(event, "storage-delete" /* ErrorCode.STORAGE_DELETE */)); + }; + request.onsuccess = () => { + resolve(); + }; + } + catch (e) { + reject(ERROR_FACTORY.create("storage-delete" /* ErrorCode.STORAGE_DELETE */, { + originalErrorMessage: e?.message + })); + } + }); + } + // Facilitates composite key functionality (which is unsupported in IE). + createCompositeKey(key) { + return [this.appId, this.appName, this.namespace, key].join(); + } +} +class InMemoryStorage extends Storage { + constructor() { + super(...arguments); + this.storage = {}; + } + async get(key) { + return Promise.resolve(this.storage[key]); + } + async set(key, value) { + this.storage[key] = value; + return Promise.resolve(undefined); + } + async delete(key) { + this.storage[key] = undefined; + return Promise.resolve(); + } + async setCustomSignals(customSignals) { + const storedSignals = (this.storage['custom_signals'] || + {}); + this.storage['custom_signals'] = mergeCustomSignals(customSignals, storedSignals); + return Promise.resolve(this.storage['custom_signals']); + } +} +function mergeCustomSignals(customSignals, storedSignals) { + const combinedSignals = { + ...storedSignals, + ...customSignals + }; + // Filter out key-value assignments with null values since they are signals being unset + const updatedSignals = Object.fromEntries(Object.entries(combinedSignals) + .filter(([_, v]) => v !== null) + .map(([k, v]) => { + // Stringify numbers to store a map of string keys and values which can be sent + // as-is in a fetch call. + if (typeof v === 'number') { + return [k, v.toString()]; + } + return [k, v]; + })); + // Throw an error if the number of custom signals to be stored exceeds the limit + if (Object.keys(updatedSignals).length > RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS) { + throw ERROR_FACTORY.create("custom-signal-max-allowed-signals" /* ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS */, { + maxSignals: RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS + }); + } + return updatedSignals; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A memory cache layer over storage to support the SDK's synchronous read requirements. + */ +class StorageCache { + constructor(storage) { + this.storage = storage; + } + /** + * Memory-only getters + */ + getLastFetchStatus() { + return this.lastFetchStatus; + } + getLastSuccessfulFetchTimestampMillis() { + return this.lastSuccessfulFetchTimestampMillis; + } + getActiveConfig() { + return this.activeConfig; + } + getCustomSignals() { + return this.customSignals; + } + /** + * Read-ahead getter + */ + async loadFromStorage() { + const lastFetchStatusPromise = this.storage.getLastFetchStatus(); + const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis(); + const activeConfigPromise = this.storage.getActiveConfig(); + const customSignalsPromise = this.storage.getCustomSignals(); + // Note: + // 1. we consistently check for undefined to avoid clobbering defined values + // in memory + // 2. we defer awaiting to improve readability, as opposed to destructuring + // a Promise.all result, for example + const lastFetchStatus = await lastFetchStatusPromise; + if (lastFetchStatus) { + this.lastFetchStatus = lastFetchStatus; + } + const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise; + if (lastSuccessfulFetchTimestampMillis) { + this.lastSuccessfulFetchTimestampMillis = + lastSuccessfulFetchTimestampMillis; + } + const activeConfig = await activeConfigPromise; + if (activeConfig) { + this.activeConfig = activeConfig; + } + const customSignals = await customSignalsPromise; + if (customSignals) { + this.customSignals = customSignals; + } + } + /** + * Write-through setters + */ + setLastFetchStatus(status) { + this.lastFetchStatus = status; + return this.storage.setLastFetchStatus(status); + } + setLastSuccessfulFetchTimestampMillis(timestampMillis) { + this.lastSuccessfulFetchTimestampMillis = timestampMillis; + return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis); + } + setActiveConfig(activeConfig) { + this.activeConfig = activeConfig; + return this.storage.setActiveConfig(activeConfig); + } + async setCustomSignals(customSignals) { + this.customSignals = await this.storage.setCustomSignals(customSignals); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 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. +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +class EventEmitter { + constructor(allowedEvents_) { + this.allowedEvents_ = allowedEvents_; + this.listeners_ = {}; + util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array'); + } + /** + * To be called by derived classes to trigger events. + */ + trigger(eventType, ...varArgs) { + if (Array.isArray(this.listeners_[eventType])) { + // Clone the list, since callbacks could add/remove listeners. + const listeners = [...this.listeners_[eventType]]; + for (let i = 0; i < listeners.length; i++) { + listeners[i].callback.apply(listeners[i].context, varArgs); + } + } + } + on(eventType, callback, context) { + this.validateEventType_(eventType); + this.listeners_[eventType] = this.listeners_[eventType] || []; + this.listeners_[eventType].push({ callback, context }); + const eventData = this.getInitialEvent(eventType); + if (eventData) { + //@ts-ignore + callback.apply(context, eventData); + } + } + off(eventType, callback, context) { + this.validateEventType_(eventType); + const listeners = this.listeners_[eventType] || []; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i].callback === callback && + (!context || context === listeners[i].context)) { + listeners.splice(i, 1); + return; + } + } + } + validateEventType_(eventType) { + util.assert(this.allowedEvents_.find(et => { + return et === eventType; + }), 'Unknown event: ' + eventType); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 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. +class VisibilityMonitor extends EventEmitter { + static getInstance() { + return new VisibilityMonitor(); + } + constructor() { + super(['visible']); + let hidden; + let visibilityChange; + if (typeof document !== 'undefined' && + typeof document.addEventListener !== 'undefined') { + if (typeof document['hidden'] !== 'undefined') { + // Opera 12.10 and Firefox 18 and later support + visibilityChange = 'visibilitychange'; + hidden = 'hidden'; + } // @ts-ignore + else if (typeof document['mozHidden'] !== 'undefined') { + visibilityChange = 'mozvisibilitychange'; + hidden = 'mozHidden'; + } // @ts-ignore + else if (typeof document['msHidden'] !== 'undefined') { + visibilityChange = 'msvisibilitychange'; + hidden = 'msHidden'; + } // @ts-ignore + else if (typeof document['webkitHidden'] !== 'undefined') { + visibilityChange = 'webkitvisibilitychange'; + hidden = 'webkitHidden'; + } + } + // Initially, we always assume we are visible. This ensures that in browsers + // without page visibility support or in cases where we are never visible + // (e.g. chrome extension), we act as if we are visible, i.e. don't delay + // reconnects + this.visible_ = true; + // @ts-ignore + if (visibilityChange) { + document.addEventListener(visibilityChange, () => { + // @ts-ignore + const visible = !document[hidden]; + if (visible !== this.visible_) { + this.visible_ = visible; + this.trigger('visible', visible); + } + }, false); + } + } + getInitialEvent(eventType) { + util.assert(eventType === 'visible', 'Unknown event type: ' + eventType); + return [this.visible_]; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const API_KEY_HEADER = 'X-Goog-Api-Key'; +const INSTALLATIONS_AUTH_TOKEN_HEADER = 'X-Goog-Firebase-Installations-Auth'; +const ORIGINAL_RETRIES = 8; +const MAXIMUM_FETCH_ATTEMPTS = 3; +const NO_BACKOFF_TIME_IN_MILLIS = -1; +const NO_FAILED_REALTIME_STREAMS = 0; +const REALTIME_DISABLED_KEY = 'featureDisabled'; +const REALTIME_RETRY_INTERVAL = 'retryIntervalSeconds'; +const TEMPLATE_VERSION_KEY = 'latestTemplateVersionNumber'; +class RealtimeHandler { + constructor(firebaseInstallations, storage, sdkVersion, namespace, projectId, apiKey, appId, logger, storageCache, cachingClient) { + this.firebaseInstallations = firebaseInstallations; + this.storage = storage; + this.sdkVersion = sdkVersion; + this.namespace = namespace; + this.projectId = projectId; + this.apiKey = apiKey; + this.appId = appId; + this.logger = logger; + this.storageCache = storageCache; + this.cachingClient = cachingClient; + this.observers = new Set(); + this.isConnectionActive = false; + this.isRealtimeDisabled = false; + this.httpRetriesRemaining = ORIGINAL_RETRIES; + this.isInBackground = false; + this.decoder = new TextDecoder('utf-8'); + this.isClosingConnection = false; + this.propagateError = (e) => this.observers.forEach(o => o.error?.(e)); + /** + * HTTP status code that the Realtime client should retry on. + */ + this.isStatusCodeRetryable = (statusCode) => { + const retryableStatusCodes = [ + 408, // Request Timeout + 429, // Too Many Requests + 502, // Bad Gateway + 503, // Service Unavailable + 504 // Gateway Timeout + ]; + return !statusCode || retryableStatusCodes.includes(statusCode); + }; + void this.setRetriesRemaining(); + void VisibilityMonitor.getInstance().on('visible', this.onVisibilityChange, this); + } + async setRetriesRemaining() { + // Retrieve number of remaining retries from last session. The minimum retry count being one. + const metadata = await this.storage.getRealtimeBackoffMetadata(); + const numFailedStreams = metadata?.numFailedStreams || 0; + this.httpRetriesRemaining = Math.max(ORIGINAL_RETRIES - numFailedStreams, 1); + } + /** + * Increment the number of failed stream attempts, increase the backoff duration, set the backoff + * end time to "backoff duration" after `lastFailedStreamTime` and persist the new + * values to storage metadata. + */ + async updateBackoffMetadataWithLastFailedStreamConnectionTime(lastFailedStreamTime) { + const numFailedStreams = ((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams || + 0) + 1; + const backoffMillis = util.calculateBackoffMillis(numFailedStreams, 60000, 2); + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: new Date(lastFailedStreamTime.getTime() + backoffMillis), + numFailedStreams + }); + } + /** + * Increase the backoff duration with a new end time based on Retry Interval. + */ + async updateBackoffMetadataWithRetryInterval(retryIntervalSeconds) { + const currentTime = Date.now(); + const backoffDurationInMillis = retryIntervalSeconds * 1000; + const backoffEndTime = new Date(currentTime + backoffDurationInMillis); + const numFailedStreams = 0; + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: backoffEndTime, + numFailedStreams + }); + await this.retryHttpConnectionWhenBackoffEnds(); + } + /** + * Closes the realtime HTTP connection. + * Note: This method is designed to be called only once at a time. + * If a call is already in progress, subsequent calls will be ignored. + */ + async closeRealtimeHttpConnection() { + if (this.isClosingConnection) { + return; + } + this.isClosingConnection = true; + try { + if (this.reader) { + await this.reader.cancel(); + } + } + catch (e) { + // The network connection was lost, so cancel() failed. + // This is expected in a disconnected state, so we can safely ignore the error. + this.logger.debug('Failed to cancel the reader, connection was lost.'); + } + finally { + this.reader = undefined; + } + if (this.controller) { + await this.controller.abort(); + this.controller = undefined; + } + this.isClosingConnection = false; + } + async resetRealtimeBackoff() { + await this.storage.setRealtimeBackoffMetadata({ + backoffEndTimeMillis: new Date(-1), + numFailedStreams: 0 + }); + } + resetRetryCount() { + this.httpRetriesRemaining = ORIGINAL_RETRIES; + } + /** + * Assembles the request headers and body and executes the fetch request to + * establish the real-time streaming connection. This is the "worker" method + * that performs the actual network communication. + */ + async establishRealtimeConnection(url, installationId, installationTokenResult, signal) { + const eTagValue = await this.storage.getActiveConfigEtag(); + const lastKnownVersionNumber = await this.storage.getActiveConfigTemplateVersion(); + const headers = { + [API_KEY_HEADER]: this.apiKey, + [INSTALLATIONS_AUTH_TOKEN_HEADER]: installationTokenResult, + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'If-None-Match': eTagValue || '*', + 'Content-Encoding': 'gzip' + }; + const requestBody = { + project: this.projectId, + namespace: this.namespace, + lastKnownVersionNumber, + appId: this.appId, + sdkVersion: this.sdkVersion, + appInstanceId: installationId + }; + const response = await fetch(url, { + method: 'POST', + headers, + body: JSON.stringify(requestBody), + signal + }); + return response; + } + getRealtimeUrl() { + const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE || + 'https://firebaseremoteconfigrealtime.googleapis.com'; + const urlString = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`; + return new URL(urlString); + } + async createRealtimeConnection() { + const [installationId, installationTokenResult] = await Promise.all([ + this.firebaseInstallations.getId(), + this.firebaseInstallations.getToken(false) + ]); + this.controller = new AbortController(); + const url = this.getRealtimeUrl(); + const realtimeConnection = await this.establishRealtimeConnection(url, installationId, installationTokenResult, this.controller.signal); + return realtimeConnection; + } + /** + * Retries HTTP stream connection asyncly in random time intervals. + */ + async retryHttpConnectionWhenBackoffEnds() { + let backoffMetadata = await this.storage.getRealtimeBackoffMetadata(); + if (!backoffMetadata) { + backoffMetadata = { + backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS), + numFailedStreams: NO_FAILED_REALTIME_STREAMS + }; + } + const backoffEndTime = new Date(backoffMetadata.backoffEndTimeMillis).getTime(); + const currentTime = Date.now(); + const retryMillis = Math.max(0, backoffEndTime - currentTime); + await this.makeRealtimeHttpConnection(retryMillis); + } + setIsHttpConnectionRunning(connectionRunning) { + this.isConnectionActive = connectionRunning; + } + /** + * Combines the check and set operations to prevent multiple asynchronous + * calls from redundantly starting an HTTP connection. This ensures that + * only one attempt is made at a time. + */ + checkAndSetHttpConnectionFlagIfNotRunning() { + const canMakeConnection = this.canEstablishStreamConnection(); + if (canMakeConnection) { + this.setIsHttpConnectionRunning(true); + } + return canMakeConnection; + } + fetchResponseIsUpToDate(fetchResponse, lastKnownVersion) { + // If there is a config, make sure its version is >= the last known version. + if (fetchResponse.config != null && fetchResponse.templateVersion) { + return fetchResponse.templateVersion >= lastKnownVersion; + } + // If there isn't a config, return true if the fetch was successful and backend had no update. + // Else, it returned an out of date config. + return this.storageCache.getLastFetchStatus() === 'success'; + } + parseAndValidateConfigUpdateMessage(message) { + const left = message.indexOf('{'); + const right = message.indexOf('}', left); + if (left < 0 || right < 0) { + return ''; + } + return left >= right ? '' : message.substring(left, right + 1); + } + isEventListenersEmpty() { + return this.observers.size === 0; + } + getRandomInt(max) { + return Math.floor(Math.random() * max); + } + executeAllListenerCallbacks(configUpdate) { + this.observers.forEach(observer => observer.next(configUpdate)); + } + /** + * Compares two configuration objects and returns a set of keys that have changed. + * A key is considered changed if it's new, removed, or has a different value. + */ + getChangedParams(newConfig, oldConfig) { + const changedKeys = new Set(); + const newKeys = new Set(Object.keys(newConfig || {})); + const oldKeys = new Set(Object.keys(oldConfig || {})); + for (const key of newKeys) { + if (!oldKeys.has(key) || newConfig[key] !== oldConfig[key]) { + changedKeys.add(key); + } + } + for (const key of oldKeys) { + if (!newKeys.has(key)) { + changedKeys.add(key); + } + } + return changedKeys; + } + async fetchLatestConfig(remainingAttempts, targetVersion) { + const remainingAttemptsAfterFetch = remainingAttempts - 1; + const currentAttempt = MAXIMUM_FETCH_ATTEMPTS - remainingAttemptsAfterFetch; + const customSignals = this.storageCache.getCustomSignals(); + if (customSignals) { + this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(customSignals)}`); + } + const abortSignal = new RemoteConfigAbortSignal(); + try { + const fetchRequest = { + cacheMaxAgeMillis: 0, + signal: abortSignal, + customSignals, + fetchType: 'REALTIME', + fetchAttempt: currentAttempt + }; + const fetchResponse = await this.cachingClient.fetch(fetchRequest); + let activatedConfigs = await this.storage.getActiveConfig(); + if (!this.fetchResponseIsUpToDate(fetchResponse, targetVersion)) { + this.logger.debug("Fetched template version is the same as SDK's current version." + + ' Retrying fetch.'); + // Continue fetching until template version number is greater than current. + await this.autoFetch(remainingAttemptsAfterFetch, targetVersion); + return; + } + if (fetchResponse.config == null) { + this.logger.debug('The fetch succeeded, but the backend had no updates.'); + return; + } + if (activatedConfigs == null) { + activatedConfigs = {}; + } + const updatedKeys = this.getChangedParams(fetchResponse.config, activatedConfigs); + if (updatedKeys.size === 0) { + this.logger.debug('Config was fetched, but no params changed.'); + return; + } + const configUpdate = { + getUpdatedKeys() { + return new Set(updatedKeys); + } + }; + this.executeAllListenerCallbacks(configUpdate); + } + catch (e) { + const errorMessage = e instanceof Error ? e.message : String(e); + const error = ERROR_FACTORY.create("update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */, { + originalErrorMessage: `Failed to auto-fetch config update: ${errorMessage}` + }); + this.propagateError(error); + } + } + async autoFetch(remainingAttempts, targetVersion) { + if (remainingAttempts === 0) { + const error = ERROR_FACTORY.create("update-not-fetched" /* ErrorCode.CONFIG_UPDATE_NOT_FETCHED */, { + originalErrorMessage: 'Unable to fetch the latest version of the template.' + }); + this.propagateError(error); + return; + } + const timeTillFetchSeconds = this.getRandomInt(4); + const timeTillFetchInMiliseconds = timeTillFetchSeconds * 1000; + await new Promise(resolve => setTimeout(resolve, timeTillFetchInMiliseconds)); + await this.fetchLatestConfig(remainingAttempts, targetVersion); + } + /** + * Processes a stream of real-time messages for configuration updates. + * This method reassembles fragmented messages, validates and parses the JSON, + * and automatically fetches a new config if a newer template version is available. + * It also handles server-specified retry intervals and propagates errors for + * invalid messages or when real-time updates are disabled. + */ + async handleNotifications(reader) { + let partialConfigUpdateMessage; + let currentConfigUpdateMessage = ''; + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + partialConfigUpdateMessage = this.decoder.decode(value, { stream: true }); + currentConfigUpdateMessage += partialConfigUpdateMessage; + if (partialConfigUpdateMessage.includes('}')) { + currentConfigUpdateMessage = this.parseAndValidateConfigUpdateMessage(currentConfigUpdateMessage); + if (currentConfigUpdateMessage.length === 0) { + continue; + } + try { + const jsonObject = JSON.parse(currentConfigUpdateMessage); + if (this.isEventListenersEmpty()) { + break; + } + if (REALTIME_DISABLED_KEY in jsonObject && + jsonObject[REALTIME_DISABLED_KEY] === true) { + const error = ERROR_FACTORY.create("realtime-unavailable" /* ErrorCode.CONFIG_UPDATE_UNAVAILABLE */, { + originalErrorMessage: 'The server is temporarily unavailable. Try again in a few minutes.' + }); + this.propagateError(error); + break; + } + if (TEMPLATE_VERSION_KEY in jsonObject) { + const oldTemplateVersion = await this.storage.getActiveConfigTemplateVersion(); + const targetTemplateVersion = Number(jsonObject[TEMPLATE_VERSION_KEY]); + if (oldTemplateVersion && + targetTemplateVersion > oldTemplateVersion) { + await this.autoFetch(MAXIMUM_FETCH_ATTEMPTS, targetTemplateVersion); + } + } + // This field in the response indicates that the realtime request should retry after the + // specified interval to establish a long-lived connection. This interval extends the + // backoff duration without affecting the number of retries, so it will not enter an + // exponential backoff state. + if (REALTIME_RETRY_INTERVAL in jsonObject) { + const retryIntervalSeconds = Number(jsonObject[REALTIME_RETRY_INTERVAL]); + await this.updateBackoffMetadataWithRetryInterval(retryIntervalSeconds); + } + } + catch (e) { + this.logger.debug('Unable to parse latest config update message.', e); + const errorMessage = e instanceof Error ? e.message : String(e); + this.propagateError(ERROR_FACTORY.create("update-message-invalid" /* ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID */, { + originalErrorMessage: errorMessage + })); + } + currentConfigUpdateMessage = ''; + } + } + } + async listenForNotifications(reader) { + try { + await this.handleNotifications(reader); + } + catch (e) { + // If the real-time connection is at an unexpected lifecycle state when the app is + // backgrounded, it's expected closing the connection will throw an exception. + if (!this.isInBackground) { + // Otherwise, the real-time server connection was closed due to a transient issue. + this.logger.debug('Real-time connection was closed due to an exception.'); + } + } + } + /** + * Open the real-time connection, begin listening for updates, and auto-fetch when an update is + * received. + * + * If the connection is successful, this method will block on its thread while it reads the + * chunk-encoded HTTP body. When the connection closes, it attempts to reestablish the stream. + */ + async prepareAndBeginRealtimeHttpStream() { + if (!this.checkAndSetHttpConnectionFlagIfNotRunning()) { + return; + } + let backoffMetadata = await this.storage.getRealtimeBackoffMetadata(); + if (!backoffMetadata) { + backoffMetadata = { + backoffEndTimeMillis: new Date(NO_BACKOFF_TIME_IN_MILLIS), + numFailedStreams: NO_FAILED_REALTIME_STREAMS + }; + } + const backoffEndTime = backoffMetadata.backoffEndTimeMillis.getTime(); + if (Date.now() < backoffEndTime) { + await this.retryHttpConnectionWhenBackoffEnds(); + return; + } + let response; + let responseCode; + try { + response = await this.createRealtimeConnection(); + responseCode = response.status; + if (response.ok && response.body) { + this.resetRetryCount(); + await this.resetRealtimeBackoff(); + const reader = response.body.getReader(); + this.reader = reader; + // Start listening for realtime notifications. + await this.listenForNotifications(reader); + } + } + catch (error) { + if (this.isInBackground) { + // It's possible the app was backgrounded while the connection was open, which + // threw an exception trying to read the response. No real error here, so treat + // this as a success, even if we haven't read a 200 response code yet. + this.resetRetryCount(); + } + else { + //there might have been a transient error so the client will retry the connection. + this.logger.debug('Exception connecting to real-time RC backend. Retrying the connection...:', error); + } + } + finally { + // Close HTTP connection and associated streams. + await this.closeRealtimeHttpConnection(); + this.setIsHttpConnectionRunning(false); + // Update backoff metadata if the connection failed in the foreground. + const connectionFailed = !this.isInBackground && + (responseCode === undefined || + this.isStatusCodeRetryable(responseCode)); + if (connectionFailed) { + await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date()); + } + // If responseCode is null then no connection was made to server and the SDK should still retry. + if (connectionFailed || response?.ok) { + await this.retryHttpConnectionWhenBackoffEnds(); + } + else { + const errorMessage = `Unable to connect to the server. HTTP status code: ${responseCode}`; + const firebaseError = ERROR_FACTORY.create("stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */, { + originalErrorMessage: errorMessage + }); + this.propagateError(firebaseError); + } + } + } + /** + * Checks whether connection can be made or not based on some conditions + * @returns booelean + */ + canEstablishStreamConnection() { + const hasActiveListeners = this.observers.size > 0; + const isNotDisabled = !this.isRealtimeDisabled; + const isNoConnectionActive = !this.isConnectionActive; + const inForeground = !this.isInBackground; + return (hasActiveListeners && + isNotDisabled && + isNoConnectionActive && + inForeground); + } + async makeRealtimeHttpConnection(delayMillis) { + if (!this.canEstablishStreamConnection()) { + return; + } + if (this.httpRetriesRemaining > 0) { + this.httpRetriesRemaining--; + await new Promise(resolve => setTimeout(resolve, delayMillis)); + void this.prepareAndBeginRealtimeHttpStream(); + } + else if (!this.isInBackground) { + const error = ERROR_FACTORY.create("stream-error" /* ErrorCode.CONFIG_UPDATE_STREAM_ERROR */, { + originalErrorMessage: 'Unable to connect to the server. Check your connection and try again.' + }); + this.propagateError(error); + } + } + async beginRealtime() { + if (this.observers.size > 0) { + await this.makeRealtimeHttpConnection(0); + } + } + /** + * Adds an observer to the realtime updates. + * @param observer The observer to add. + */ + addObserver(observer) { + this.observers.add(observer); + void this.beginRealtime(); + } + /** + * Removes an observer from the realtime updates. + * @param observer The observer to remove. + */ + removeObserver(observer) { + if (this.observers.has(observer)) { + this.observers.delete(observer); + } + } + /** + * Handles changes to the application's visibility state, managing the real-time connection. + * + * When the application is moved to the background, this method closes the existing + * real-time connection to save resources. When the application returns to the + * foreground, it attempts to re-establish the connection. + */ + async onVisibilityChange(visible) { + this.isInBackground = !visible; + if (!visible) { + await this.closeRealtimeHttpConnection(); + } + else if (visible) { + await this.beginRealtime(); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerRemoteConfig() { + app._registerComponent(new component.Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true)); + app.registerVersion(name, version); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + app.registerVersion(name, version, 'cjs2020'); + function remoteConfigFactory(container, { options }) { + /* Dependencies */ + // getImmediate for FirebaseApp will always succeed + const app$1 = container.getProvider('app').getImmediate(); + // The following call will always succeed because rc has `import '@firebase/installations'` + const installations = container + .getProvider('installations-internal') + .getImmediate(); + // Normalizes optional inputs. + const { projectId, apiKey, appId } = app$1.options; + if (!projectId) { + throw ERROR_FACTORY.create("registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */); + } + if (!apiKey) { + throw ERROR_FACTORY.create("registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */); + } + if (!appId) { + throw ERROR_FACTORY.create("registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */); + } + const namespace = options?.templateId || 'firebase'; + const storage = util.isIndexedDBAvailable() + ? new IndexedDbStorage(appId, app$1.name, namespace) + : new InMemoryStorage(); + const storageCache = new StorageCache(storage); + const logger$1 = new logger.Logger(name); + // Sets ERROR as the default log level. + // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level. + logger$1.logLevel = logger.LogLevel.ERROR; + const restClient = new RestClient(installations, + // Uses the JS SDK version, by which the RC package version can be deduced, if necessary. + app.SDK_VERSION, namespace, projectId, apiKey, appId); + const retryingClient = new RetryingClient(restClient, storage); + const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger$1); + const realtimeHandler = new RealtimeHandler(installations, storage, app.SDK_VERSION, namespace, projectId, apiKey, appId, logger$1, storageCache, cachingClient); + const remoteConfigInstance = new RemoteConfig(app$1, cachingClient, storageCache, storage, logger$1, realtimeHandler); + // Starts warming cache. + // eslint-disable-next-line @typescript-eslint/no-floating-promises + ensureInitialized(remoteConfigInstance); + return remoteConfigInstance; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// This API is put in a separate file, so we can stub fetchConfig and activate in tests. +// It's not possible to stub standalone functions from the same module. +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +async function fetchAndActivate(remoteConfig) { + remoteConfig = util.getModularInstance(remoteConfig); + await fetchConfig(remoteConfig); + return activate(remoteConfig); +} +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +async function isSupported() { + if (!util.isIndexedDBAvailable()) { + return false; + } + try { + const isDBOpenable = await util.validateIndexedDBOpenable(); + return isDBOpenable; + } + catch (error) { + return false; + } +} + +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +/** register component and version */ +registerRemoteConfig(); + +exports.activate = activate; +exports.ensureInitialized = ensureInitialized; +exports.fetchAndActivate = fetchAndActivate; +exports.fetchConfig = fetchConfig; +exports.getAll = getAll; +exports.getBoolean = getBoolean; +exports.getNumber = getNumber; +exports.getRemoteConfig = getRemoteConfig; +exports.getString = getString; +exports.getValue = getValue; +exports.isSupported = isSupported; +exports.onConfigUpdate = onConfigUpdate; +exports.setCustomSignals = setCustomSignals; +exports.setLogLevel = setLogLevel; +//# sourceMappingURL=index.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js.map b/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js.map new file mode 100644 index 0000000..c0e40be --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/client/remote_config_fetch_client.ts","../src/constants.ts","../src/errors.ts","../src/value.ts","../src/api.ts","../src/client/caching_client.ts","../src/language.ts","../src/client/rest_client.ts","../src/client/retrying_client.ts","../src/remote_config.ts","../src/storage/storage.ts","../src/storage/storage_cache.ts","../src/client/eventEmitter.ts","../src/client/visibility_monitor.ts","../src/client/realtime_handler.ts","../src/register.ts","../src/api2.ts","../src/index.ts"],"sourcesContent":["/**\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}\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};\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}\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 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';\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 await Promise.all([\n rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag),\n rc._storage.setActiveConfigTemplateVersion(\n lastSuccessfulFetchResponse.templateVersion\n )\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} 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\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 }\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 }\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 };\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 { 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}\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 | '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 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\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 );\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"],"names":["ErrorFactory","FirebaseError","app","getApp","getModularInstance","_getProvider","deepEqual","ValueImpl","FirebaseLogLevel","calculateBackoffMillis","assert","_registerComponent","Component","registerVersion","packageName","isIndexedDBAvailable","logger","Logger","SDK_VERSION","RemoteConfigImpl","validateIndexedDBOpenable"],"mappings":";;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;;;;;;AAOG;MACU,uBAAuB,CAAA;AAApC,IAAA,WAAA,GAAA;QACE,IAAS,CAAA,SAAA,GAAsB,EAAE,CAAC;KAOnC;AANC,IAAA,gBAAgB,CAAC,QAAoB,EAAA;AACnC,QAAA,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;KAC/B;IACD,KAAK,GAAA;AACH,QAAA,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE,CAAC,CAAC;KAChD;AACF;;ACtDD;;;;;;;;;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ACI,eAAe,WAAW,GAAA;AAC/B,IAAA,IAAI,CAACW,yBAAoB,EAAE,EAAE;AAC3B,QAAA,OAAO,KAAK,CAAC;KACd;AAED,IAAA,IAAI;AACF,QAAA,MAAM,YAAY,GAAY,MAAMK,8BAAyB,EAAE,CAAC;AAChE,QAAA,OAAO,YAAY,CAAC;KACrB;IAAC,OAAO,KAAK,EAAE;AACd,QAAA,OAAO,KAAK,CAAC;KACd;AACH;;ACnEA;;;;;AAKG;AAmCH;AACA,oBAAoB,EAAE;;;;;;;;;;;;;;;;;"}
\ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/remote-config-public.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/remote-config-public.d.ts new file mode 100644 index 0000000..58c2bbc --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/remote-config-public.d.ts @@ -0,0 +1,421 @@ +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ + +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/app'; + +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function activate(remoteConfig: RemoteConfig): Promise<boolean>; + +/** + * Contains information about which keys have been updated. + * + * @public + */ +export declare interface ConfigUpdate { + /** + * Parameter keys whose values have been updated from the currently activated values. + * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. + */ + getUpdatedKeys(): Set<string>; +} + +/** + * Observer interface for receiving real-time Remote Config update notifications. + * + * NOTE: Although an `complete` callback can be provided, it will + * never be called because the ConfigUpdate stream is never-ending. + * + * @public + */ +export declare interface ConfigUpdateObserver { + /** + * Called when a new ConfigUpdate is available. + */ + next: (configUpdate: ConfigUpdate) => void; + /** + * Called if an error occurs during the stream. + */ + error: (error: FirebaseError) => void; + /** + * Called when the stream is gracefully terminated. + */ + complete: () => void; +} + +/** + * Defines the type for representing custom signals and their values. + * + * <p>The values in CustomSignals must be one of the following types: + * + * <ul> + * <li><code>string</code> + * <li><code>number</code> + * <li><code>null</code> + * </ul> + * + * @public + */ +export declare interface CustomSignals { + [key: string]: string | number | null; +} + +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +export declare function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>; + +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>; + +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +export declare function fetchConfig(remoteConfig: RemoteConfig): Promise<void>; + +/** + * Defines a successful response (200 or 304). + * + * <p>Modeled after the native `Response` interface, but simplified for Remote Config's + * use case. + * + * @public + */ +export declare interface FetchResponse { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * <p>The Remote Config client is modeled after the native `Fetch` interface, so + * HTTP status is first-class. + * + * <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the + * HTTP status code. The former is normalized into the latter. + */ + status: number; + /** + * Defines the ETag response header value. + * + * <p>Only defined for 200 and 304 responses. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + * + * <p>Only defined for 200 responses. + */ + config?: FirebaseRemoteConfigObject; + /** + * The version number of the config template fetched from the server. + */ + templateVersion?: number; +} + +/** + * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server. + * + * <ul> + * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted + * to fetch config, or that SDK initialization is incomplete.</li> + * <li>"success" indicates the last attempt succeeded.</li> + * <li>"failure" indicates the last attempt failed.</li> + * <li>"throttle" indicates the last attempt was rate-limited.</li> + * </ul> + * + * @public + */ +export declare type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; + +/** + * Indicates the type of fetch request. + * + * <ul> + * <li>"BASE" indicates a standard fetch request.</li> + * <li>"REALTIME" indicates a fetch request triggered by a real-time update.</li> + * </ul> + * + * @public + */ +export declare type FetchType = 'BASE' | 'REALTIME'; + +/** + * Defines a self-descriptive reference for config key-value pairs. + * + * @public + */ +export declare interface FirebaseRemoteConfigObject { + [key: string]: string; +} + +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +export declare function getAll(remoteConfig: RemoteConfig): Record<string, Value>; + +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +export declare function getBoolean(remoteConfig: RemoteConfig, key: string): boolean; + +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +export declare function getNumber(remoteConfig: RemoteConfig, key: string): number; + +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +export declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig; + +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +export declare function getString(remoteConfig: RemoteConfig, key: string): string; + +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +export declare function getValue(remoteConfig: RemoteConfig, key: string): Value; + +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +export declare function isSupported(): Promise<boolean>; + +/** + * Defines levels of Remote Config logging. + * + * @public + */ +export declare type LogLevel = 'debug' | 'error' | 'silent'; + +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +export declare function onConfigUpdate(remoteConfig: RemoteConfig, observer: ConfigUpdateObserver): Unsubscribe; + +/** + * The Firebase Remote Config service interface. + * + * @public + */ +export declare interface RemoteConfig { + /** + * The {@link @firebase/app#FirebaseApp} this `RemoteConfig` instance is associated with. + */ + app: FirebaseApp; + /** + * Defines configuration for the Remote Config SDK. + */ + settings: RemoteConfigSettings; + /** + * Object containing default values for configs. + */ + defaultConfig: { + [key: string]: string | number | boolean; + }; + /** + * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if + * the {@link RemoteConfig} instance either hasn't fetched or initialization + * is incomplete. + */ + fetchTimeMillis: number; + /** + * The status of the last fetch <i>attempt</i>. + */ + lastFetchStatus: FetchStatus; +} + +/** + * Options for Remote Config initialization. + * + * @public + */ +export declare interface RemoteConfigOptions { + /** + * The ID of the template to use. If not provided, defaults to "firebase". + */ + templateId?: string; + /** + * Hydrates the state with an initial fetch response. + */ + initialFetchResponse?: FetchResponse; +} + +/** + * Defines configuration options for the Remote Config SDK. + * + * @public + */ +export declare interface RemoteConfigSettings { + /** + * Defines the maximum age in milliseconds of an entry in the config cache before + * it is considered stale. Defaults to 43200000 (Twelve hours). + */ + minimumFetchIntervalMillis: number; + /** + * Defines the maximum amount of milliseconds to wait for a response when fetching + * configuration from the Remote Config server. Defaults to 60000 (One minute). + */ + fetchTimeoutMillis: number; +} + +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +export declare function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>; + +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +export declare function setLogLevel(remoteConfig: RemoteConfig, logLevel: LogLevel): void; + +/** + * A function that unsubscribes from a real-time event stream. + * + * @public + */ +export declare type Unsubscribe = () => void; + +/** + * Wraps a value with metadata and type-safe getters. + * + * @public + */ +export declare interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case-insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} + +/** + * Indicates the source of a value. + * + * <ul> + * <li>"static" indicates the value was defined by a static constant.</li> + * <li>"default" indicates the value was defined by default config.</li> + * <li>"remote" indicates the value was defined by fetched config.</li> + * </ul> + * + * @public + */ +export declare type ValueSource = 'static' | 'default' | 'remote'; + +export { } diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/remote-config.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/remote-config.d.ts new file mode 100644 index 0000000..58c2bbc --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/remote-config.d.ts @@ -0,0 +1,421 @@ +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ + +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/app'; + +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function activate(remoteConfig: RemoteConfig): Promise<boolean>; + +/** + * Contains information about which keys have been updated. + * + * @public + */ +export declare interface ConfigUpdate { + /** + * Parameter keys whose values have been updated from the currently activated values. + * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. + */ + getUpdatedKeys(): Set<string>; +} + +/** + * Observer interface for receiving real-time Remote Config update notifications. + * + * NOTE: Although an `complete` callback can be provided, it will + * never be called because the ConfigUpdate stream is never-ending. + * + * @public + */ +export declare interface ConfigUpdateObserver { + /** + * Called when a new ConfigUpdate is available. + */ + next: (configUpdate: ConfigUpdate) => void; + /** + * Called if an error occurs during the stream. + */ + error: (error: FirebaseError) => void; + /** + * Called when the stream is gracefully terminated. + */ + complete: () => void; +} + +/** + * Defines the type for representing custom signals and their values. + * + * <p>The values in CustomSignals must be one of the following types: + * + * <ul> + * <li><code>string</code> + * <li><code>number</code> + * <li><code>null</code> + * </ul> + * + * @public + */ +export declare interface CustomSignals { + [key: string]: string | number | null; +} + +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +export declare function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>; + +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>; + +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +export declare function fetchConfig(remoteConfig: RemoteConfig): Promise<void>; + +/** + * Defines a successful response (200 or 304). + * + * <p>Modeled after the native `Response` interface, but simplified for Remote Config's + * use case. + * + * @public + */ +export declare interface FetchResponse { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * <p>The Remote Config client is modeled after the native `Fetch` interface, so + * HTTP status is first-class. + * + * <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the + * HTTP status code. The former is normalized into the latter. + */ + status: number; + /** + * Defines the ETag response header value. + * + * <p>Only defined for 200 and 304 responses. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + * + * <p>Only defined for 200 responses. + */ + config?: FirebaseRemoteConfigObject; + /** + * The version number of the config template fetched from the server. + */ + templateVersion?: number; +} + +/** + * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server. + * + * <ul> + * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted + * to fetch config, or that SDK initialization is incomplete.</li> + * <li>"success" indicates the last attempt succeeded.</li> + * <li>"failure" indicates the last attempt failed.</li> + * <li>"throttle" indicates the last attempt was rate-limited.</li> + * </ul> + * + * @public + */ +export declare type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; + +/** + * Indicates the type of fetch request. + * + * <ul> + * <li>"BASE" indicates a standard fetch request.</li> + * <li>"REALTIME" indicates a fetch request triggered by a real-time update.</li> + * </ul> + * + * @public + */ +export declare type FetchType = 'BASE' | 'REALTIME'; + +/** + * Defines a self-descriptive reference for config key-value pairs. + * + * @public + */ +export declare interface FirebaseRemoteConfigObject { + [key: string]: string; +} + +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +export declare function getAll(remoteConfig: RemoteConfig): Record<string, Value>; + +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +export declare function getBoolean(remoteConfig: RemoteConfig, key: string): boolean; + +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +export declare function getNumber(remoteConfig: RemoteConfig, key: string): number; + +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +export declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig; + +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +export declare function getString(remoteConfig: RemoteConfig, key: string): string; + +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +export declare function getValue(remoteConfig: RemoteConfig, key: string): Value; + +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +export declare function isSupported(): Promise<boolean>; + +/** + * Defines levels of Remote Config logging. + * + * @public + */ +export declare type LogLevel = 'debug' | 'error' | 'silent'; + +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +export declare function onConfigUpdate(remoteConfig: RemoteConfig, observer: ConfigUpdateObserver): Unsubscribe; + +/** + * The Firebase Remote Config service interface. + * + * @public + */ +export declare interface RemoteConfig { + /** + * The {@link @firebase/app#FirebaseApp} this `RemoteConfig` instance is associated with. + */ + app: FirebaseApp; + /** + * Defines configuration for the Remote Config SDK. + */ + settings: RemoteConfigSettings; + /** + * Object containing default values for configs. + */ + defaultConfig: { + [key: string]: string | number | boolean; + }; + /** + * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if + * the {@link RemoteConfig} instance either hasn't fetched or initialization + * is incomplete. + */ + fetchTimeMillis: number; + /** + * The status of the last fetch <i>attempt</i>. + */ + lastFetchStatus: FetchStatus; +} + +/** + * Options for Remote Config initialization. + * + * @public + */ +export declare interface RemoteConfigOptions { + /** + * The ID of the template to use. If not provided, defaults to "firebase". + */ + templateId?: string; + /** + * Hydrates the state with an initial fetch response. + */ + initialFetchResponse?: FetchResponse; +} + +/** + * Defines configuration options for the Remote Config SDK. + * + * @public + */ +export declare interface RemoteConfigSettings { + /** + * Defines the maximum age in milliseconds of an entry in the config cache before + * it is considered stale. Defaults to 43200000 (Twelve hours). + */ + minimumFetchIntervalMillis: number; + /** + * Defines the maximum amount of milliseconds to wait for a response when fetching + * configuration from the Remote Config server. Defaults to 60000 (One minute). + */ + fetchTimeoutMillis: number; +} + +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +export declare function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>; + +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +export declare function setLogLevel(remoteConfig: RemoteConfig, logLevel: LogLevel): void; + +/** + * A function that unsubscribes from a real-time event stream. + * + * @public + */ +export declare type Unsubscribe = () => void; + +/** + * Wraps a value with metadata and type-safe getters. + * + * @public + */ +export declare interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case-insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} + +/** + * Indicates the source of a value. + * + * <ul> + * <li>"static" indicates the value was defined by a static constant.</li> + * <li>"default" indicates the value was defined by default config.</li> + * <li>"remote" indicates the value was defined by fetched config.</li> + * </ul> + * + * @public + */ +export declare type ValueSource = 'static' | 'default' | 'remote'; + +export { } diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/api.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/api.d.ts new file mode 100644 index 0000000..0f16c48 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/api.d.ts @@ -0,0 +1,144 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { CustomSignals, LogLevel as RemoteConfigLogLevel, RemoteConfig, Value, RemoteConfigOptions, ConfigUpdateObserver, Unsubscribe } from './public_types'; +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +export declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig; +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function activate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +export declare function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>; +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +export declare function fetchConfig(remoteConfig: RemoteConfig): Promise<void>; +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +export declare function getAll(remoteConfig: RemoteConfig): Record<string, Value>; +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +export declare function getBoolean(remoteConfig: RemoteConfig, key: string): boolean; +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +export declare function getNumber(remoteConfig: RemoteConfig, key: string): number; +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +export declare function getString(remoteConfig: RemoteConfig, key: string): string; +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +export declare function getValue(remoteConfig: RemoteConfig, key: string): Value; +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +export declare function setLogLevel(remoteConfig: RemoteConfig, logLevel: RemoteConfigLogLevel): void; +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +export declare function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>; +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +export declare function onConfigUpdate(remoteConfig: RemoteConfig, observer: ConfigUpdateObserver): Unsubscribe; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/api2.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/api2.d.ts new file mode 100644 index 0000000..ea6a655 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/api2.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { RemoteConfig } from './public_types'; +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +export declare function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +export declare function isSupported(): Promise<boolean>; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/caching_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/caching_client.d.ts new file mode 100644 index 0000000..c05bd5f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/caching_client.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StorageCache } from '../storage/storage_cache'; +import { FetchResponse } from '../public_types'; +import { RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { Storage } from '../storage/storage'; +import { Logger } from '@firebase/logger'; +/** + * Implements the {@link RemoteConfigClient} abstraction with success response caching. + * + * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service + * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the + * Cache API doesn't support matching entries by time. + */ +export declare class CachingClient implements RemoteConfigFetchClient { + private readonly client; + private readonly storage; + private readonly storageCache; + private readonly logger; + constructor(client: RemoteConfigFetchClient, storage: Storage, storageCache: StorageCache, logger: Logger); + /** + * Returns true if the age of the cached fetched configs is less than or equal to + * {@link Settings#minimumFetchIntervalInSeconds}. + * + * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the + * native Fetch API. + * + * <p>Visible for testing. + */ + isCachedDataFresh(cacheMaxAgeMillis: number, lastSuccessfulFetchTimestampMillis: number | undefined): boolean; + fetch(request: FetchRequest): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/eventEmitter.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/eventEmitter.d.ts new file mode 100644 index 0000000..2f8b9cc --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/eventEmitter.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Base class to be used if you want to emit events. Call the constructor with + * the set of allowed event names. + */ +export declare abstract class EventEmitter { + private allowedEvents_; + private listeners_; + constructor(allowedEvents_: string[]); + /** + * To be overridden by derived classes in order to fire an initial event when + * somebody subscribes for data. + * + * @returns {Array.<*>} Array of parameters to trigger initial event with. + */ + abstract getInitialEvent(eventType: string): unknown[]; + /** + * To be called by derived classes to trigger events. + */ + protected trigger(eventType: string, ...varArgs: unknown[]): void; + on(eventType: string, callback: (a: unknown) => void, context: unknown): void; + off(eventType: string, callback: (a: unknown) => void, context: unknown): void; + private validateEventType_; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/realtime_handler.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/realtime_handler.d.ts new file mode 100644 index 0000000..3fa7c87 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/realtime_handler.d.ts @@ -0,0 +1,141 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseInstallationsInternal } from '@firebase/installations'; +import { Logger } from '@firebase/logger'; +import { ConfigUpdateObserver } from '../public_types'; +import { Storage } from '../storage/storage'; +import { StorageCache } from '../storage/storage_cache'; +import { CachingClient } from './caching_client'; +export declare class RealtimeHandler { + private readonly firebaseInstallations; + private readonly storage; + private readonly sdkVersion; + private readonly namespace; + private readonly projectId; + private readonly apiKey; + private readonly appId; + private readonly logger; + private readonly storageCache; + private readonly cachingClient; + constructor(firebaseInstallations: _FirebaseInstallationsInternal, storage: Storage, sdkVersion: string, namespace: string, projectId: string, apiKey: string, appId: string, logger: Logger, storageCache: StorageCache, cachingClient: CachingClient); + private observers; + private isConnectionActive; + private isRealtimeDisabled; + private controller?; + private reader; + private httpRetriesRemaining; + private isInBackground; + private readonly decoder; + private isClosingConnection; + private setRetriesRemaining; + private propagateError; + /** + * Increment the number of failed stream attempts, increase the backoff duration, set the backoff + * end time to "backoff duration" after `lastFailedStreamTime` and persist the new + * values to storage metadata. + */ + private updateBackoffMetadataWithLastFailedStreamConnectionTime; + /** + * Increase the backoff duration with a new end time based on Retry Interval. + */ + private updateBackoffMetadataWithRetryInterval; + /** + * HTTP status code that the Realtime client should retry on. + */ + private isStatusCodeRetryable; + /** + * Closes the realtime HTTP connection. + * Note: This method is designed to be called only once at a time. + * If a call is already in progress, subsequent calls will be ignored. + */ + private closeRealtimeHttpConnection; + private resetRealtimeBackoff; + private resetRetryCount; + /** + * Assembles the request headers and body and executes the fetch request to + * establish the real-time streaming connection. This is the "worker" method + * that performs the actual network communication. + */ + private establishRealtimeConnection; + private getRealtimeUrl; + private createRealtimeConnection; + /** + * Retries HTTP stream connection asyncly in random time intervals. + */ + private retryHttpConnectionWhenBackoffEnds; + private setIsHttpConnectionRunning; + /** + * Combines the check and set operations to prevent multiple asynchronous + * calls from redundantly starting an HTTP connection. This ensures that + * only one attempt is made at a time. + */ + private checkAndSetHttpConnectionFlagIfNotRunning; + private fetchResponseIsUpToDate; + private parseAndValidateConfigUpdateMessage; + private isEventListenersEmpty; + private getRandomInt; + private executeAllListenerCallbacks; + /** + * Compares two configuration objects and returns a set of keys that have changed. + * A key is considered changed if it's new, removed, or has a different value. + */ + private getChangedParams; + private fetchLatestConfig; + private autoFetch; + /** + * Processes a stream of real-time messages for configuration updates. + * This method reassembles fragmented messages, validates and parses the JSON, + * and automatically fetches a new config if a newer template version is available. + * It also handles server-specified retry intervals and propagates errors for + * invalid messages or when real-time updates are disabled. + */ + private handleNotifications; + private listenForNotifications; + /** + * Open the real-time connection, begin listening for updates, and auto-fetch when an update is + * received. + * + * If the connection is successful, this method will block on its thread while it reads the + * chunk-encoded HTTP body. When the connection closes, it attempts to reestablish the stream. + */ + private prepareAndBeginRealtimeHttpStream; + /** + * Checks whether connection can be made or not based on some conditions + * @returns booelean + */ + private canEstablishStreamConnection; + private makeRealtimeHttpConnection; + private beginRealtime; + /** + * Adds an observer to the realtime updates. + * @param observer The observer to add. + */ + addObserver(observer: ConfigUpdateObserver): void; + /** + * Removes an observer from the realtime updates. + * @param observer The observer to remove. + */ + removeObserver(observer: ConfigUpdateObserver): void; + /** + * Handles changes to the application's visibility state, managing the real-time connection. + * + * When the application is moved to the background, this method closes the existing + * real-time connection to save resources. When the application returns to the + * foreground, it attempts to re-establish the connection. + */ + private onVisibilityChange; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/remote_config_fetch_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/remote_config_fetch_client.d.ts new file mode 100644 index 0000000..e72ce51 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/remote_config_fetch_client.d.ts @@ -0,0 +1,104 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CustomSignals, FetchResponse, FetchType } from '../public_types'; +/** + * Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the + * Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest). + * + * <p>Abstracts throttle, response cache and network implementation details. + * + * <p>Modeled after the native {@link GlobalFetch} interface, which is relatively modern and + * convenient, but simplified for Remote Config's use case. + * + * Disambiguation: {@link GlobalFetch} interface and the Remote Config service define "fetch" + * methods. The RestClient uses the former to make HTTP calls. This interface abstracts the latter. + */ +export interface RemoteConfigFetchClient { + /** + * @throws if response status is not 200 or 304. + */ + fetch(request: FetchRequest): Promise<FetchResponse>; +} +/** + * Shims a minimal AbortSignal. + * + * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects + * of networking, such as retries. Firebase doesn't use AbortController enough to justify a + * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be + * swapped out if/when we do. + */ +export declare class RemoteConfigAbortSignal { + listeners: Array<() => void>; + addEventListener(listener: () => void): void; + abort(): void; +} +/** + * Defines per-request inputs for the Remote Config fetch request. + * + * <p>Modeled after the native {@link Request} interface, but simplified for Remote Config's + * use case. + */ +export interface FetchRequest { + /** + * Uses cached config if it is younger than this age. + * + * <p>Required because it's defined by settings, which always have a value. + * + * <p>Comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the native + * Fetch API. + */ + cacheMaxAgeMillis: number; + /** + * An event bus for the signal to abort a request. + * + * <p>Required because all requests should be abortable. + * + * <p>Comparable to the native + * Fetch API's "signal" field on its request configuration object + * https://fetch.spec.whatwg.org/#dom-requestinit-signal. + * + * <p>Disambiguation: Remote Config commonly refers to API inputs as + * "signals". See the private ConfigFetchRequestBody interface for those: + * http://google3/firebase/remote_config/web/src/core/rest_client.ts?l=14&rcl=255515243. + */ + signal: RemoteConfigAbortSignal; + /** + * The ETag header value from the last response. + * + * <p>Optional in case this is the first request. + * + * <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API. + */ + eTag?: string; + /** The custom signals stored for the app instance. + * + * <p>Optional in case no custom signals are set for the instance. + */ + customSignals?: CustomSignals; + /** + * The type of fetch to perform, such as a regular fetch or a real-time fetch. + * + * Optional as not all fetch requests need to be distinguished. + */ + fetchType?: FetchType; + /** + * The number of fetch attempts made so far for this request. + * + * Optional as not all fetch requests are part of a retry series. + */ + fetchAttempt?: number; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/rest_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/rest_client.d.ts new file mode 100644 index 0000000..24a3fe0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/rest_client.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchResponse } from '../public_types'; +import { RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { _FirebaseInstallationsInternal } from '@firebase/installations'; +/** + * Implements the Client abstraction for the Remote Config REST API. + */ +export declare class RestClient implements RemoteConfigFetchClient { + private readonly firebaseInstallations; + private readonly sdkVersion; + private readonly namespace; + private readonly projectId; + private readonly apiKey; + private readonly appId; + constructor(firebaseInstallations: _FirebaseInstallationsInternal, sdkVersion: string, namespace: string, projectId: string, apiKey: string, appId: string); + /** + * Fetches from the Remote Config REST API. + * + * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't + * connect to the network. + * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the + * fetch response. + * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status. + */ + fetch(request: FetchRequest): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/retrying_client.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/retrying_client.d.ts new file mode 100644 index 0000000..06c7ff0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/retrying_client.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchResponse } from '../public_types'; +import { RemoteConfigAbortSignal, RemoteConfigFetchClient, FetchRequest } from './remote_config_fetch_client'; +import { ThrottleMetadata, Storage } from '../storage/storage'; +/** + * Supports waiting on a backoff by: + * + * <ul> + * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> + * <li>Listening on a signal bus for abort events, just like the Fetch API</li> + * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled + * request appear the same.</li> + * </ul> + * + * <p>Visible for testing. + */ +export declare function setAbortableTimeout(signal: RemoteConfigAbortSignal, throttleEndTimeMillis: number): Promise<void>; +/** + * Decorates a Client with retry logic. + * + * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache + * responses (because the SDK has no use for error responses). + */ +export declare class RetryingClient implements RemoteConfigFetchClient { + private readonly client; + private readonly storage; + constructor(client: RemoteConfigFetchClient, storage: Storage); + fetch(request: FetchRequest): Promise<FetchResponse>; + /** + * A recursive helper for attempting a fetch request repeatedly. + * + * @throws any non-retriable errors. + */ + attemptFetch(request: FetchRequest, { throttleEndTimeMillis, backoffCount }: ThrottleMetadata): Promise<FetchResponse>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/client/visibility_monitor.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/visibility_monitor.d.ts new file mode 100644 index 0000000..ef40083 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/client/visibility_monitor.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EventEmitter } from './eventEmitter'; +export declare class VisibilityMonitor extends EventEmitter { + private visible_; + static getInstance(): VisibilityMonitor; + constructor(); + getInitialEvent(eventType: string): boolean[]; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/constants.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/constants.d.ts new file mode 100644 index 0000000..1663d8f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/constants.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const RC_COMPONENT_NAME = "remote-config"; +export declare const RC_CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = 100; +export declare const RC_CUSTOM_SIGNAL_KEY_MAX_LENGTH = 250; +export declare const RC_CUSTOM_SIGNAL_VALUE_MAX_LENGTH = 500; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/errors.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/errors.d.ts new file mode 100644 index 0000000..3cf0b55 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/errors.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ErrorFactory } from '@firebase/util'; +export declare const enum ErrorCode { + ALREADY_INITIALIZED = "already-initialized", + REGISTRATION_WINDOW = "registration-window", + REGISTRATION_PROJECT_ID = "registration-project-id", + REGISTRATION_API_KEY = "registration-api-key", + REGISTRATION_APP_ID = "registration-app-id", + STORAGE_OPEN = "storage-open", + STORAGE_GET = "storage-get", + STORAGE_SET = "storage-set", + STORAGE_DELETE = "storage-delete", + FETCH_NETWORK = "fetch-client-network", + FETCH_TIMEOUT = "fetch-timeout", + FETCH_THROTTLE = "fetch-throttle", + FETCH_PARSE = "fetch-client-parse", + FETCH_STATUS = "fetch-status", + INDEXED_DB_UNAVAILABLE = "indexed-db-unavailable", + CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS = "custom-signal-max-allowed-signals", + CONFIG_UPDATE_STREAM_ERROR = "stream-error", + CONFIG_UPDATE_UNAVAILABLE = "realtime-unavailable", + CONFIG_UPDATE_MESSAGE_INVALID = "update-message-invalid", + CONFIG_UPDATE_NOT_FETCHED = "update-not-fetched" +} +interface ErrorParams { + [ErrorCode.STORAGE_OPEN]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_GET]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_SET]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.STORAGE_DELETE]: { + originalErrorMessage: string | undefined; + }; + [ErrorCode.FETCH_NETWORK]: { + originalErrorMessage: string; + }; + [ErrorCode.FETCH_THROTTLE]: { + throttleEndTimeMillis: number; + }; + [ErrorCode.FETCH_PARSE]: { + originalErrorMessage: string; + }; + [ErrorCode.FETCH_STATUS]: { + httpStatus: number; + }; + [ErrorCode.CUSTOM_SIGNAL_MAX_ALLOWED_SIGNALS]: { + maxSignals: number; + }; + [ErrorCode.CONFIG_UPDATE_STREAM_ERROR]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_UNAVAILABLE]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_MESSAGE_INVALID]: { + originalErrorMessage: string; + }; + [ErrorCode.CONFIG_UPDATE_NOT_FETCHED]: { + originalErrorMessage: string; + }; +} +export declare const ERROR_FACTORY: ErrorFactory<ErrorCode, ErrorParams>; +export declare function hasErrorCode(e: Error, errorCode: ErrorCode): boolean; +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/global_index.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/global_index.d.ts new file mode 100644 index 0000000..524adb1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/global_index.d.ts @@ -0,0 +1,655 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface VersionService { + library: string; + version: string; +} +interface PlatformLoggerService { + getPlatformInfoString(): string; +} +interface HeartbeatService { + /** + * Called to report a heartbeat. The function will generate + * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it + * to IndexedDB. + * Note that we only store one heartbeat per day. So if a heartbeat for today is + * already logged, subsequent calls to this function in the same day will be ignored. + */ + triggerHeartbeat(): Promise<void>; + /** + * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly. + * It also clears all heartbeats from memory as well as in IndexedDB. + */ + getHeartbeatsHeader(): Promise<string>; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of + * services. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeApp:1) | initializeApp()} to create an app. + * + * @public + */ +interface FirebaseApp { + /** + * The (read-only) name for this app. + * + * The default app's name is `"[DEFAULT]"`. + * + * @example + * ```javascript + * // The default app's name is "[DEFAULT]" + * const app = initializeApp(defaultAppConfig); + * console.log(app.name); // "[DEFAULT]" + * ``` + * + * @example + * ```javascript + * // A named app's name is what you provide to initializeApp() + * const otherApp = initializeApp(otherAppConfig, "other"); + * console.log(otherApp.name); // "other" + * ``` + */ + readonly name: string; + /** + * The (read-only) configuration options for this app. These are the original + * parameters given in {@link (initializeApp:1) | initializeApp()}. + * + * @example + * ```javascript + * const app = initializeApp(config); + * console.log(app.options.databaseURL === config.databaseURL); // true + * ``` + */ + readonly options: FirebaseOptions; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled: boolean; +} +/** + * @public + * + * Firebase configuration object. Contains a set of parameters required by + * services in order to successfully communicate with Firebase server APIs + * and to associate client data with your Firebase project and + * Firebase application. Typically this object is populated by the Firebase + * console at project setup. See also: + * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. + */ +interface FirebaseOptions { + /** + * An encrypted string used when calling certain APIs that don't need to + * access private user data + * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). + */ + apiKey?: string; + /** + * Auth domain for the project ID. + */ + authDomain?: string; + /** + * Default Realtime Database URL. + */ + databaseURL?: string; + /** + * The unique identifier for the project across all of Firebase and + * Google Cloud. + */ + projectId?: string; + /** + * The default Cloud Storage bucket name. + */ + storageBucket?: string; + /** + * Unique numerical value used to identify each sender that can send + * Firebase Cloud Messaging messages to client apps. + */ + messagingSenderId?: string; + /** + * Unique identifier for the app. + */ + appId?: string; + /** + * An ID automatically created when you enable Analytics in your + * Firebase project and register a web app. In versions 7.20.0 + * and higher, this parameter is optional. + */ + measurementId?: string; +} +declare module '@firebase/component' { + interface NameServiceMapping { + 'app': FirebaseApp; + 'app-version': VersionService; + 'heartbeat': HeartbeatService; + 'platform-logger': PlatformLoggerService; + } +} + +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +interface FirebaseDefaults { + config?: Record<string, string>; + emulatorHosts?: Record<string, string>; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} +declare global { + var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined; +} + +declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record<string, unknown> | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record<string, unknown> | undefined); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The Firebase Remote Config service interface. + * + * @public + */ +interface RemoteConfig { + /** + * The {@link @firebase/app#FirebaseApp} this `RemoteConfig` instance is associated with. + */ + app: FirebaseApp; + /** + * Defines configuration for the Remote Config SDK. + */ + settings: RemoteConfigSettings; + /** + * Object containing default values for configs. + */ + defaultConfig: { + [key: string]: string | number | boolean; + }; + /** + * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if + * the {@link RemoteConfig} instance either hasn't fetched or initialization + * is incomplete. + */ + fetchTimeMillis: number; + /** + * The status of the last fetch <i>attempt</i>. + */ + lastFetchStatus: FetchStatus; +} +/** + * Defines a self-descriptive reference for config key-value pairs. + * + * @public + */ +interface FirebaseRemoteConfigObject { + [key: string]: string; +} +/** + * Defines a successful response (200 or 304). + * + * <p>Modeled after the native `Response` interface, but simplified for Remote Config's + * use case. + * + * @public + */ +interface FetchResponse { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * <p>The Remote Config client is modeled after the native `Fetch` interface, so + * HTTP status is first-class. + * + * <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the + * HTTP status code. The former is normalized into the latter. + */ + status: number; + /** + * Defines the ETag response header value. + * + * <p>Only defined for 200 and 304 responses. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + * + * <p>Only defined for 200 responses. + */ + config?: FirebaseRemoteConfigObject; + /** + * The version number of the config template fetched from the server. + */ + templateVersion?: number; +} +/** + * Options for Remote Config initialization. + * + * @public + */ +interface RemoteConfigOptions { + /** + * The ID of the template to use. If not provided, defaults to "firebase". + */ + templateId?: string; + /** + * Hydrates the state with an initial fetch response. + */ + initialFetchResponse?: FetchResponse; +} +/** + * Indicates the source of a value. + * + * <ul> + * <li>"static" indicates the value was defined by a static constant.</li> + * <li>"default" indicates the value was defined by default config.</li> + * <li>"remote" indicates the value was defined by fetched config.</li> + * </ul> + * + * @public + */ +type ValueSource = 'static' | 'default' | 'remote'; +/** + * Wraps a value with metadata and type-safe getters. + * + * @public + */ +interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case-insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} +/** + * Defines configuration options for the Remote Config SDK. + * + * @public + */ +interface RemoteConfigSettings { + /** + * Defines the maximum age in milliseconds of an entry in the config cache before + * it is considered stale. Defaults to 43200000 (Twelve hours). + */ + minimumFetchIntervalMillis: number; + /** + * Defines the maximum amount of milliseconds to wait for a response when fetching + * configuration from the Remote Config server. Defaults to 60000 (One minute). + */ + fetchTimeoutMillis: number; +} +/** + * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server. + * + * <ul> + * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted + * to fetch config, or that SDK initialization is incomplete.</li> + * <li>"success" indicates the last attempt succeeded.</li> + * <li>"failure" indicates the last attempt failed.</li> + * <li>"throttle" indicates the last attempt was rate-limited.</li> + * </ul> + * + * @public + */ +type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; +/** + * Defines levels of Remote Config logging. + * + * @public + */ +type LogLevel = 'debug' | 'error' | 'silent'; +/** + * Defines the type for representing custom signals and their values. + * + * <p>The values in CustomSignals must be one of the following types: + * + * <ul> + * <li><code>string</code> + * <li><code>number</code> + * <li><code>null</code> + * </ul> + * + * @public + */ +interface CustomSignals { + [key: string]: string | number | null; +} +/** + * Contains information about which keys have been updated. + * + * @public + */ +interface ConfigUpdate { + /** + * Parameter keys whose values have been updated from the currently activated values. + * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. + */ + getUpdatedKeys(): Set<string>; +} +/** + * Observer interface for receiving real-time Remote Config update notifications. + * + * NOTE: Although an `complete` callback can be provided, it will + * never be called because the ConfigUpdate stream is never-ending. + * + * @public + */ +interface ConfigUpdateObserver { + /** + * Called when a new ConfigUpdate is available. + */ + next: (configUpdate: ConfigUpdate) => void; + /** + * Called if an error occurs during the stream. + */ + error: (error: FirebaseError) => void; + /** + * Called when the stream is gracefully terminated. + */ + complete: () => void; +} +/** + * A function that unsubscribes from a real-time event stream. + * + * @public + */ +type Unsubscribe = () => void; +/** + * Indicates the type of fetch request. + * + * <ul> + * <li>"BASE" indicates a standard fetch request.</li> + * <li>"REALTIME" indicates a fetch request triggered by a real-time update.</li> + * </ul> + * + * @public + */ +type FetchType = 'BASE' | 'REALTIME'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'remote-config': RemoteConfig; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + * @param app - The {@link @firebase/app#FirebaseApp} instance. + * @param options - Optional. The {@link RemoteConfigOptions} with which to instantiate the + * Remote Config instance. + * @returns A {@link RemoteConfig} instance. + * + * @public + */ +declare function getRemoteConfig(app?: FirebaseApp, options?: RemoteConfigOptions): RemoteConfig; +/** + * Makes the last fetched config available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +declare function activate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * Ensures the last activated config are available to the getters. + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` that resolves when the last activated config is available to the getters. + * @public + */ +declare function ensureInitialized(remoteConfig: RemoteConfig): Promise<void>; +/** + * Fetches and caches configuration from the Remote Config service. + * @param remoteConfig - The {@link RemoteConfig} instance. + * @public + */ +declare function fetchConfig(remoteConfig: RemoteConfig): Promise<void>; +/** + * Gets all config. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @returns All config. + * + * @public + */ +declare function getAll(remoteConfig: RemoteConfig): Record<string, Value>; +/** + * Gets the value for the given key as a boolean. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a boolean. + * @public + */ +declare function getBoolean(remoteConfig: RemoteConfig, key: string): boolean; +/** + * Gets the value for the given key as a number. + * + * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a number. + * + * @public + */ +declare function getNumber(remoteConfig: RemoteConfig, key: string): number; +/** + * Gets the value for the given key as a string. + * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key as a string. + * + * @public + */ +declare function getString(remoteConfig: RemoteConfig, key: string): string; +/** + * Gets the {@link Value} for the given key. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param key - The name of the parameter. + * + * @returns The value for the given key. + * + * @public + */ +declare function getValue(remoteConfig: RemoteConfig, key: string): Value; +/** + * Defines the log level to use. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param logLevel - The log level to set. + * + * @public + */ +declare function setLogLevel(remoteConfig: RemoteConfig, logLevel: LogLevel): void; +/** + * Sets the custom signals for the app instance. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param customSignals - Map (key, value) of the custom signals to be set for the app instance. If + * a key already exists, the value is overwritten. Setting the value of a custom signal to null + * unsets the signal. The signals will be persisted locally on the client. + * + * @public + */ +declare function setCustomSignals(remoteConfig: RemoteConfig, customSignals: CustomSignals): Promise<void>; +/** + * Starts listening for real-time config updates from the Remote Config backend and automatically + * fetches updates from the Remote Config backend when they are available. + * + * @remarks + * If a connection to the Remote Config backend is not already open, calling this method will + * open it. Multiple listeners can be added by calling this method again, but subsequent calls + * re-use the same connection to the backend. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * @param observer - The {@link ConfigUpdateObserver} to be notified of config updates. + * @returns An {@link Unsubscribe} function to remove the listener. + * + * @public + */ +declare function onConfigUpdate(remoteConfig: RemoteConfig, observer: ConfigUpdateObserver): Unsubscribe; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + * Performs fetch and activate operations, as a convenience. + * + * @param remoteConfig - The {@link RemoteConfig} instance. + * + * @returns A `Promise` which resolves to true if the current call activated the fetched configs. + * If the fetched configs were already activated, the `Promise` will resolve to false. + * + * @public + */ +declare function fetchAndActivate(remoteConfig: RemoteConfig): Promise<boolean>; +/** + * This method provides two different checks: + * + * 1. Check if IndexedDB exists in the browser environment. + * 2. Check if the current browser context allows IndexedDB `open()` calls. + * + * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance + * can be initialized in this environment, or false if it cannot. + * @public + */ +declare function isSupported(): Promise<boolean>; + +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +declare global { + interface Window { + FIREBASE_REMOTE_CONFIG_URL_BASE: string; + } +} + +export { ConfigUpdate, ConfigUpdateObserver, CustomSignals, FetchResponse, FetchStatus, FetchType, FirebaseRemoteConfigObject, LogLevel, RemoteConfig, RemoteConfigOptions, RemoteConfigSettings, Unsubscribe, Value, ValueSource, activate, ensureInitialized, fetchAndActivate, fetchConfig, getAll, getBoolean, getNumber, getRemoteConfig, getString, getValue, isSupported, onConfigUpdate, setCustomSignals, setLogLevel }; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/index.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/index.d.ts new file mode 100644 index 0000000..fc0de52 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/index.d.ts @@ -0,0 +1,14 @@ +/** + * The Firebase Remote Config Web SDK. + * This SDK does not work in a Node.js environment. + * + * @packageDocumentation + */ +declare global { + interface Window { + FIREBASE_REMOTE_CONFIG_URL_BASE: string; + } +} +export * from './api'; +export * from './api2'; +export * from './public_types'; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/language.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/language.d.ts new file mode 100644 index 0000000..2bfc669 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/language.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Attempts to get the most accurate browser language setting. + * + * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript. + * + * <p>Defers default language specification to server logic for consistency. + * + * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}. + */ +export declare function getUserLanguage(navigatorLanguage?: NavigatorLanguage): string; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/public_types.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/public_types.d.ts new file mode 100644 index 0000000..5c58c66 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/public_types.d.ts @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp, FirebaseError } from '@firebase/app'; +/** + * The Firebase Remote Config service interface. + * + * @public + */ +export interface RemoteConfig { + /** + * The {@link @firebase/app#FirebaseApp} this `RemoteConfig` instance is associated with. + */ + app: FirebaseApp; + /** + * Defines configuration for the Remote Config SDK. + */ + settings: RemoteConfigSettings; + /** + * Object containing default values for configs. + */ + defaultConfig: { + [key: string]: string | number | boolean; + }; + /** + * The Unix timestamp in milliseconds of the last <i>successful</i> fetch, or negative one if + * the {@link RemoteConfig} instance either hasn't fetched or initialization + * is incomplete. + */ + fetchTimeMillis: number; + /** + * The status of the last fetch <i>attempt</i>. + */ + lastFetchStatus: FetchStatus; +} +/** + * Defines a self-descriptive reference for config key-value pairs. + * + * @public + */ +export interface FirebaseRemoteConfigObject { + [key: string]: string; +} +/** + * Defines a successful response (200 or 304). + * + * <p>Modeled after the native `Response` interface, but simplified for Remote Config's + * use case. + * + * @public + */ +export interface FetchResponse { + /** + * The HTTP status, which is useful for differentiating success responses with data from + * those without. + * + * <p>The Remote Config client is modeled after the native `Fetch` interface, so + * HTTP status is first-class. + * + * <p>Disambiguation: the fetch response returns a legacy "state" value that is redundant with the + * HTTP status code. The former is normalized into the latter. + */ + status: number; + /** + * Defines the ETag response header value. + * + * <p>Only defined for 200 and 304 responses. + */ + eTag?: string; + /** + * Defines the map of parameters returned as "entries" in the fetch response body. + * + * <p>Only defined for 200 responses. + */ + config?: FirebaseRemoteConfigObject; + /** + * The version number of the config template fetched from the server. + */ + templateVersion?: number; +} +/** + * Options for Remote Config initialization. + * + * @public + */ +export interface RemoteConfigOptions { + /** + * The ID of the template to use. If not provided, defaults to "firebase". + */ + templateId?: string; + /** + * Hydrates the state with an initial fetch response. + */ + initialFetchResponse?: FetchResponse; +} +/** + * Indicates the source of a value. + * + * <ul> + * <li>"static" indicates the value was defined by a static constant.</li> + * <li>"default" indicates the value was defined by default config.</li> + * <li>"remote" indicates the value was defined by fetched config.</li> + * </ul> + * + * @public + */ +export type ValueSource = 'static' | 'default' | 'remote'; +/** + * Wraps a value with metadata and type-safe getters. + * + * @public + */ +export interface Value { + /** + * Gets the value as a boolean. + * + * The following values (case-insensitive) are interpreted as true: + * "1", "true", "t", "yes", "y", "on". Other values are interpreted as false. + */ + asBoolean(): boolean; + /** + * Gets the value as a number. Comparable to calling <code>Number(value) || 0</code>. + */ + asNumber(): number; + /** + * Gets the value as a string. + */ + asString(): string; + /** + * Gets the {@link ValueSource} for the given key. + */ + getSource(): ValueSource; +} +/** + * Defines configuration options for the Remote Config SDK. + * + * @public + */ +export interface RemoteConfigSettings { + /** + * Defines the maximum age in milliseconds of an entry in the config cache before + * it is considered stale. Defaults to 43200000 (Twelve hours). + */ + minimumFetchIntervalMillis: number; + /** + * Defines the maximum amount of milliseconds to wait for a response when fetching + * configuration from the Remote Config server. Defaults to 60000 (One minute). + */ + fetchTimeoutMillis: number; +} +/** + * Summarizes the outcome of the last attempt to fetch config from the Firebase Remote Config server. + * + * <ul> + * <li>"no-fetch-yet" indicates the {@link RemoteConfig} instance has not yet attempted + * to fetch config, or that SDK initialization is incomplete.</li> + * <li>"success" indicates the last attempt succeeded.</li> + * <li>"failure" indicates the last attempt failed.</li> + * <li>"throttle" indicates the last attempt was rate-limited.</li> + * </ul> + * + * @public + */ +export type FetchStatus = 'no-fetch-yet' | 'success' | 'failure' | 'throttle'; +/** + * Defines levels of Remote Config logging. + * + * @public + */ +export type LogLevel = 'debug' | 'error' | 'silent'; +/** + * Defines the type for representing custom signals and their values. + * + * <p>The values in CustomSignals must be one of the following types: + * + * <ul> + * <li><code>string</code> + * <li><code>number</code> + * <li><code>null</code> + * </ul> + * + * @public + */ +export interface CustomSignals { + [key: string]: string | number | null; +} +/** + * Contains information about which keys have been updated. + * + * @public + */ +export interface ConfigUpdate { + /** + * Parameter keys whose values have been updated from the currently activated values. + * Includes keys that are added, deleted, or whose value, value source, or metadata has changed. + */ + getUpdatedKeys(): Set<string>; +} +/** + * Observer interface for receiving real-time Remote Config update notifications. + * + * NOTE: Although an `complete` callback can be provided, it will + * never be called because the ConfigUpdate stream is never-ending. + * + * @public + */ +export interface ConfigUpdateObserver { + /** + * Called when a new ConfigUpdate is available. + */ + next: (configUpdate: ConfigUpdate) => void; + /** + * Called if an error occurs during the stream. + */ + error: (error: FirebaseError) => void; + /** + * Called when the stream is gracefully terminated. + */ + complete: () => void; +} +/** + * A function that unsubscribes from a real-time event stream. + * + * @public + */ +export type Unsubscribe = () => void; +/** + * Indicates the type of fetch request. + * + * <ul> + * <li>"BASE" indicates a standard fetch request.</li> + * <li>"REALTIME" indicates a fetch request triggered by a real-time update.</li> + * </ul> + * + * @public + */ +export type FetchType = 'BASE' | 'REALTIME'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'remote-config': RemoteConfig; + } +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/register.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/register.d.ts new file mode 100644 index 0000000..5aab5ab --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/register.d.ts @@ -0,0 +1,2 @@ +import '@firebase/installations'; +export declare function registerRemoteConfig(): void; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/remote_config.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/remote_config.d.ts new file mode 100644 index 0000000..e72b28f --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/remote_config.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { RemoteConfig as RemoteConfigType, FetchStatus, RemoteConfigSettings } from './public_types'; +import { StorageCache } from './storage/storage_cache'; +import { RemoteConfigFetchClient } from './client/remote_config_fetch_client'; +import { Storage } from './storage/storage'; +import { Logger } from '@firebase/logger'; +import { RealtimeHandler } from './client/realtime_handler'; +/** + * Encapsulates business logic mapping network and storage dependencies to the public SDK API. + * + * See {@link https://github.com/firebase/firebase-js-sdk/blob/main/packages/firebase/compat/index.d.ts|interface documentation} for method descriptions. + */ +export declare class RemoteConfig implements RemoteConfigType { + readonly app: FirebaseApp; + /** + * @internal + */ + readonly _client: RemoteConfigFetchClient; + /** + * @internal + */ + readonly _storageCache: StorageCache; + /** + * @internal + */ + readonly _storage: Storage; + /** + * @internal + */ + readonly _logger: Logger; + /** + * @internal + */ + readonly _realtimeHandler: RealtimeHandler; + /** + * Tracks completion of initialization promise. + * @internal + */ + _isInitializationComplete: boolean; + /** + * De-duplicates initialization calls. + * @internal + */ + _initializePromise?: Promise<void>; + settings: RemoteConfigSettings; + defaultConfig: { + [key: string]: string | number | boolean; + }; + get fetchTimeMillis(): number; + get lastFetchStatus(): FetchStatus; + constructor(app: FirebaseApp, + /** + * @internal + */ + _client: RemoteConfigFetchClient, + /** + * @internal + */ + _storageCache: StorageCache, + /** + * @internal + */ + _storage: Storage, + /** + * @internal + */ + _logger: Logger, + /** + * @internal + */ + _realtimeHandler: RealtimeHandler); +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage.d.ts new file mode 100644 index 0000000..df20b57 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage.d.ts @@ -0,0 +1,116 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchStatus, CustomSignals } from '@firebase/remote-config-types'; +import { FetchResponse, FirebaseRemoteConfigObject } from '../public_types'; +/** + * A general-purpose store keyed by app + namespace + {@link + * ProjectNamespaceKeyFieldValue}. + * + * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact + * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys + * for a set of key-value pairs. See {@link Storage#createCompositeKey}. + * + * <p>Visible for testing. + */ +export declare const APP_NAMESPACE_STORE = "app_namespace_store"; +/** + * Encapsulates metadata concerning throttled fetch requests. + */ +export interface ThrottleMetadata { + backoffCount: number; + throttleEndTimeMillis: number; +} +export interface RealtimeBackoffMetadata { + numFailedStreams: number; + backoffEndTimeMillis: Date; +} +/** + * Provides type-safety for the "key" field used by {@link APP_NAMESPACE_STORE}. + * + * <p>This seems like a small price to avoid potentially subtle bugs caused by a typo. + */ +type ProjectNamespaceKeyFieldValue = 'active_config' | 'active_config_etag' | 'last_fetch_status' | 'last_successful_fetch_timestamp_millis' | 'last_successful_fetch_response' | 'settings' | 'throttle_metadata' | 'custom_signals' | 'realtime_backoff_metadata' | 'last_known_template_version'; +export declare function openDatabase(): Promise<IDBDatabase>; +/** + * Abstracts data persistence. + */ +export declare abstract class Storage { + getLastFetchStatus(): Promise<FetchStatus | undefined>; + setLastFetchStatus(status: FetchStatus): Promise<void>; + getLastSuccessfulFetchTimestampMillis(): Promise<number | undefined>; + setLastSuccessfulFetchTimestampMillis(timestamp: number): Promise<void>; + getLastSuccessfulFetchResponse(): Promise<FetchResponse | undefined>; + setLastSuccessfulFetchResponse(response: FetchResponse): Promise<void>; + getActiveConfig(): Promise<FirebaseRemoteConfigObject | undefined>; + setActiveConfig(config: FirebaseRemoteConfigObject): Promise<void>; + getActiveConfigEtag(): Promise<string | undefined>; + setActiveConfigEtag(etag: string): Promise<void>; + getThrottleMetadata(): Promise<ThrottleMetadata | undefined>; + setThrottleMetadata(metadata: ThrottleMetadata): Promise<void>; + deleteThrottleMetadata(): Promise<void>; + getCustomSignals(): Promise<CustomSignals | undefined>; + abstract setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; + abstract get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined>; + abstract set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + abstract delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + getRealtimeBackoffMetadata(): Promise<RealtimeBackoffMetadata | undefined>; + setRealtimeBackoffMetadata(realtimeMetadata: RealtimeBackoffMetadata): Promise<void>; + getActiveConfigTemplateVersion(): Promise<number | undefined>; + setActiveConfigTemplateVersion(version: number): Promise<void>; +} +export declare class IndexedDbStorage extends Storage { + private readonly appId; + private readonly appName; + private readonly namespace; + private readonly openDbPromise; + /** + * @param appId enables storage segmentation by app (ID + name). + * @param appName enables storage segmentation by app (ID + name). + * @param namespace enables storage segmentation by namespace. + */ + constructor(appId: string, appName: string, namespace: string, openDbPromise?: Promise<IDBDatabase>); + setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; + /** + * Gets a value from the database using the provided transaction. + * + * @param key The key of the value to get. + * @param transaction The transaction to use for the operation. + * @returns The value associated with the key, or undefined if no such value exists. + */ + getWithTransaction<T>(key: ProjectNamespaceKeyFieldValue, transaction: IDBTransaction): Promise<T | undefined>; + /** + * Sets a value in the database using the provided transaction. + * + * @param key The key of the value to set. + * @param value The value to set. + * @param transaction The transaction to use for the operation. + * @returns A promise that resolves when the operation is complete. + */ + setWithTransaction<T>(key: ProjectNamespaceKeyFieldValue, value: T, transaction: IDBTransaction): Promise<void>; + get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined>; + set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + createCompositeKey(key: ProjectNamespaceKeyFieldValue): string; +} +export declare class InMemoryStorage extends Storage { + private storage; + get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T>; + set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void>; + delete(key: ProjectNamespaceKeyFieldValue): Promise<void>; + setCustomSignals(customSignals: CustomSignals): Promise<CustomSignals>; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage_cache.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage_cache.d.ts new file mode 100644 index 0000000..e61c523 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/storage/storage_cache.d.ts @@ -0,0 +1,51 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FetchStatus, CustomSignals } from '@firebase/remote-config-types'; +import { FirebaseRemoteConfigObject } from '../public_types'; +import { Storage } from './storage'; +/** + * A memory cache layer over storage to support the SDK's synchronous read requirements. + */ +export declare class StorageCache { + private readonly storage; + constructor(storage: Storage); + /** + * Memory caches. + */ + private lastFetchStatus?; + private lastSuccessfulFetchTimestampMillis?; + private activeConfig?; + private customSignals?; + /** + * Memory-only getters + */ + getLastFetchStatus(): FetchStatus | undefined; + getLastSuccessfulFetchTimestampMillis(): number | undefined; + getActiveConfig(): FirebaseRemoteConfigObject | undefined; + getCustomSignals(): CustomSignals | undefined; + /** + * Read-ahead getter + */ + loadFromStorage(): Promise<void>; + /** + * Write-through setters + */ + setLastFetchStatus(status: FetchStatus): Promise<void>; + setLastSuccessfulFetchTimestampMillis(timestampMillis: number): Promise<void>; + setActiveConfig(activeConfig: FirebaseRemoteConfigObject): Promise<void>; + setCustomSignals(customSignals: CustomSignals): Promise<void>; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/tsdoc-metadata.json b/frontend-old/node_modules/@firebase/remote-config/dist/src/tsdoc-metadata.json new file mode 100644 index 0000000..6af1f6a --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "0.1.2" + } + ] +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/src/value.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/src/value.d.ts new file mode 100644 index 0000000..13e29c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/src/value.d.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value as ValueType, ValueSource } from '@firebase/remote-config-types'; +export declare class Value implements ValueType { + private readonly _source; + private readonly _value; + constructor(_source: ValueSource, _value?: string); + asString(): string; + asBoolean(): boolean; + asNumber(): number; + getSource(): ValueSource; +} diff --git a/frontend-old/node_modules/@firebase/remote-config/dist/test/setup.d.ts b/frontend-old/node_modules/@firebase/remote-config/dist/test/setup.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/dist/test/setup.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/remote-config/package.json b/frontend-old/node_modules/@firebase/remote-config/package.json new file mode 100644 index 0000000..46e7bda --- /dev/null +++ b/frontend-old/node_modules/@firebase/remote-config/package.json @@ -0,0 +1,72 @@ +{ + "name": "@firebase/remote-config", + "version": "0.7.0", + "description": "The Remote Config package of the Firebase JS SDK", + "author": "Firebase <firebase-support@google.com> (https://firebase.google.com/)", + "main": "dist/index.cjs.js", + "browser": "dist/esm/index.esm.js", + "module": "dist/esm/index.esm.js", + "exports": { + ".": { + "types": "./dist/remote-config-public.d.ts", + "require": "./dist/index.cjs.js", + "default": "./dist/esm/index.esm.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "scripts": { + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "build": "rollup -c && yarn api-report", + "build:deps": "lerna run --scope @firebase/remote-config --include-dependencies build", + "build:release": "yarn build && yarn typings:public", + "dev": "rollup -c -w", + "test": "run-p --npm-path npm lint test:browser", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:browser", + "test:browser": "karma start", + "test:debug": "karma start --browsers=Chrome --auto-watch", + "trusted-type-check": "tsec -p tsconfig.json --noEmit", + "prettier": "prettier --write '{src,test}/**/*.{js,ts}'", + "api-report": "api-extractor run --local --verbose", + "doc": "api-documenter markdown --input temp --output docs", + "build:doc": "yarn build && yarn doc", + "typings:public": "node ../../scripts/build/use_typings.js ./dist/remote-config-public.d.ts", + "typings:internal": "node ../../scripts/build/use_typings.js ./dist/src/index.d.ts" + }, + "peerDependencies": { + "@firebase/app": "0.x" + }, + "dependencies": { + "@firebase/installations": "0.6.19", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "@firebase/component": "0.7.0", + "tslib": "^2.1.0" + }, + "license": "Apache-2.0", + "devDependencies": { + "@firebase/app": "0.14.3", + "rollup": "2.79.2", + "rollup-plugin-dts": "5.3.1", + "rollup-plugin-typescript2": "0.36.0", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/remote-config", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "./dist/remote-config-public.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + } +} |
