No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.esm2017.js 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. import { _getProvider, getApp, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app';
  2. import { ErrorFactory, FirebaseError, getModularInstance, calculateBackoffMillis, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';
  3. import { Component } from '@firebase/component';
  4. import { LogLevel, Logger } from '@firebase/logger';
  5. import '@firebase/installations';
  6. const name = "@firebase/remote-config";
  7. const version = "0.4.1";
  8. /**
  9. * @license
  10. * Copyright 2019 Google LLC
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. /**
  25. * Shims a minimal AbortSignal.
  26. *
  27. * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
  28. * of networking, such as retries. Firebase doesn't use AbortController enough to justify a
  29. * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
  30. * swapped out if/when we do.
  31. */
  32. class RemoteConfigAbortSignal {
  33. constructor() {
  34. this.listeners = [];
  35. }
  36. addEventListener(listener) {
  37. this.listeners.push(listener);
  38. }
  39. abort() {
  40. this.listeners.forEach(listener => listener());
  41. }
  42. }
  43. /**
  44. * @license
  45. * Copyright 2020 Google LLC
  46. *
  47. * Licensed under the Apache License, Version 2.0 (the "License");
  48. * you may not use this file except in compliance with the License.
  49. * You may obtain a copy of the License at
  50. *
  51. * http://www.apache.org/licenses/LICENSE-2.0
  52. *
  53. * Unless required by applicable law or agreed to in writing, software
  54. * distributed under the License is distributed on an "AS IS" BASIS,
  55. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56. * See the License for the specific language governing permissions and
  57. * limitations under the License.
  58. */
  59. const RC_COMPONENT_NAME = 'remote-config';
  60. /**
  61. * @license
  62. * Copyright 2019 Google LLC
  63. *
  64. * Licensed under the Apache License, Version 2.0 (the "License");
  65. * you may not use this file except in compliance with the License.
  66. * You may obtain a copy of the License at
  67. *
  68. * http://www.apache.org/licenses/LICENSE-2.0
  69. *
  70. * Unless required by applicable law or agreed to in writing, software
  71. * distributed under the License is distributed on an "AS IS" BASIS,
  72. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  73. * See the License for the specific language governing permissions and
  74. * limitations under the License.
  75. */
  76. const ERROR_DESCRIPTION_MAP = {
  77. ["registration-window" /* ErrorCode.REGISTRATION_WINDOW */]: 'Undefined window object. This SDK only supports usage in a browser environment.',
  78. ["registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */]: 'Undefined project identifier. Check Firebase app initialization.',
  79. ["registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */]: 'Undefined API key. Check Firebase app initialization.',
  80. ["registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */]: 'Undefined app identifier. Check Firebase app initialization.',
  81. ["storage-open" /* ErrorCode.STORAGE_OPEN */]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
  82. ["storage-get" /* ErrorCode.STORAGE_GET */]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
  83. ["storage-set" /* ErrorCode.STORAGE_SET */]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
  84. ["storage-delete" /* ErrorCode.STORAGE_DELETE */]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',
  85. ["fetch-client-network" /* ErrorCode.FETCH_NETWORK */]: 'Fetch client failed to connect to a network. Check Internet connection.' +
  86. ' Original error: {$originalErrorMessage}.',
  87. ["fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */]: 'The config fetch request timed out. ' +
  88. ' Configure timeout using "fetchTimeoutMillis" SDK setting.',
  89. ["fetch-throttle" /* ErrorCode.FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
  90. ' Configure timeout using "fetchTimeoutMillis" SDK setting.' +
  91. ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
  92. ["fetch-client-parse" /* ErrorCode.FETCH_PARSE */]: 'Fetch client could not parse response.' +
  93. ' Original error: {$originalErrorMessage}.',
  94. ["fetch-status" /* ErrorCode.FETCH_STATUS */]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',
  95. ["indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */]: 'Indexed DB is not supported by current browser'
  96. };
  97. const ERROR_FACTORY = new ErrorFactory('remoteconfig' /* service */, 'Remote Config' /* service name */, ERROR_DESCRIPTION_MAP);
  98. // Note how this is like typeof/instanceof, but for ErrorCode.
  99. function hasErrorCode(e, errorCode) {
  100. return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1;
  101. }
  102. /**
  103. * @license
  104. * Copyright 2019 Google LLC
  105. *
  106. * Licensed under the Apache License, Version 2.0 (the "License");
  107. * you may not use this file except in compliance with the License.
  108. * You may obtain a copy of the License at
  109. *
  110. * http://www.apache.org/licenses/LICENSE-2.0
  111. *
  112. * Unless required by applicable law or agreed to in writing, software
  113. * distributed under the License is distributed on an "AS IS" BASIS,
  114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  115. * See the License for the specific language governing permissions and
  116. * limitations under the License.
  117. */
  118. const DEFAULT_VALUE_FOR_BOOLEAN = false;
  119. const DEFAULT_VALUE_FOR_STRING = '';
  120. const DEFAULT_VALUE_FOR_NUMBER = 0;
  121. const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];
  122. class Value {
  123. constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) {
  124. this._source = _source;
  125. this._value = _value;
  126. }
  127. asString() {
  128. return this._value;
  129. }
  130. asBoolean() {
  131. if (this._source === 'static') {
  132. return DEFAULT_VALUE_FOR_BOOLEAN;
  133. }
  134. return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;
  135. }
  136. asNumber() {
  137. if (this._source === 'static') {
  138. return DEFAULT_VALUE_FOR_NUMBER;
  139. }
  140. let num = Number(this._value);
  141. if (isNaN(num)) {
  142. num = DEFAULT_VALUE_FOR_NUMBER;
  143. }
  144. return num;
  145. }
  146. getSource() {
  147. return this._source;
  148. }
  149. }
  150. /**
  151. * @license
  152. * Copyright 2020 Google LLC
  153. *
  154. * Licensed under the Apache License, Version 2.0 (the "License");
  155. * you may not use this file except in compliance with the License.
  156. * You may obtain a copy of the License at
  157. *
  158. * http://www.apache.org/licenses/LICENSE-2.0
  159. *
  160. * Unless required by applicable law or agreed to in writing, software
  161. * distributed under the License is distributed on an "AS IS" BASIS,
  162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  163. * See the License for the specific language governing permissions and
  164. * limitations under the License.
  165. */
  166. /**
  167. *
  168. * @param app - The {@link @firebase/app#FirebaseApp} instance.
  169. * @returns A {@link RemoteConfig} instance.
  170. *
  171. * @public
  172. */
  173. function getRemoteConfig(app = getApp()) {
  174. app = getModularInstance(app);
  175. const rcProvider = _getProvider(app, RC_COMPONENT_NAME);
  176. return rcProvider.getImmediate();
  177. }
  178. /**
  179. * Makes the last fetched config available to the getters.
  180. * @param remoteConfig - The {@link RemoteConfig} instance.
  181. * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
  182. * If the fetched configs were already activated, the `Promise` will resolve to false.
  183. *
  184. * @public
  185. */
  186. async function activate(remoteConfig) {
  187. const rc = getModularInstance(remoteConfig);
  188. const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([
  189. rc._storage.getLastSuccessfulFetchResponse(),
  190. rc._storage.getActiveConfigEtag()
  191. ]);
  192. if (!lastSuccessfulFetchResponse ||
  193. !lastSuccessfulFetchResponse.config ||
  194. !lastSuccessfulFetchResponse.eTag ||
  195. lastSuccessfulFetchResponse.eTag === activeConfigEtag) {
  196. // Either there is no successful fetched config, or is the same as current active
  197. // config.
  198. return false;
  199. }
  200. await Promise.all([
  201. rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),
  202. rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)
  203. ]);
  204. return true;
  205. }
  206. /**
  207. * Ensures the last activated config are available to the getters.
  208. * @param remoteConfig - The {@link RemoteConfig} instance.
  209. *
  210. * @returns A `Promise` that resolves when the last activated config is available to the getters.
  211. * @public
  212. */
  213. function ensureInitialized(remoteConfig) {
  214. const rc = getModularInstance(remoteConfig);
  215. if (!rc._initializePromise) {
  216. rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {
  217. rc._isInitializationComplete = true;
  218. });
  219. }
  220. return rc._initializePromise;
  221. }
  222. /**
  223. * Fetches and caches configuration from the Remote Config service.
  224. * @param remoteConfig - The {@link RemoteConfig} instance.
  225. * @public
  226. */
  227. async function fetchConfig(remoteConfig) {
  228. const rc = getModularInstance(remoteConfig);
  229. // Aborts the request after the given timeout, causing the fetch call to
  230. // reject with an `AbortError`.
  231. //
  232. // <p>Aborting after the request completes is a no-op, so we don't need a
  233. // corresponding `clearTimeout`.
  234. //
  235. // Locating abort logic here because:
  236. // * it uses a developer setting (timeout)
  237. // * it applies to all retries (like curl's max-time arg)
  238. // * it is consistent with the Fetch API's signal input
  239. const abortSignal = new RemoteConfigAbortSignal();
  240. setTimeout(async () => {
  241. // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
  242. abortSignal.abort();
  243. }, rc.settings.fetchTimeoutMillis);
  244. // Catches *all* errors thrown by client so status can be set consistently.
  245. try {
  246. await rc._client.fetch({
  247. cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,
  248. signal: abortSignal
  249. });
  250. await rc._storageCache.setLastFetchStatus('success');
  251. }
  252. catch (e) {
  253. const lastFetchStatus = hasErrorCode(e, "fetch-throttle" /* ErrorCode.FETCH_THROTTLE */)
  254. ? 'throttle'
  255. : 'failure';
  256. await rc._storageCache.setLastFetchStatus(lastFetchStatus);
  257. throw e;
  258. }
  259. }
  260. /**
  261. * Gets all config.
  262. *
  263. * @param remoteConfig - The {@link RemoteConfig} instance.
  264. * @returns All config.
  265. *
  266. * @public
  267. */
  268. function getAll(remoteConfig) {
  269. const rc = getModularInstance(remoteConfig);
  270. return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => {
  271. allConfigs[key] = getValue(remoteConfig, key);
  272. return allConfigs;
  273. }, {});
  274. }
  275. /**
  276. * Gets the value for the given key as a boolean.
  277. *
  278. * Convenience method for calling <code>remoteConfig.getValue(key).asBoolean()</code>.
  279. *
  280. * @param remoteConfig - The {@link RemoteConfig} instance.
  281. * @param key - The name of the parameter.
  282. *
  283. * @returns The value for the given key as a boolean.
  284. * @public
  285. */
  286. function getBoolean(remoteConfig, key) {
  287. return getValue(getModularInstance(remoteConfig), key).asBoolean();
  288. }
  289. /**
  290. * Gets the value for the given key as a number.
  291. *
  292. * Convenience method for calling <code>remoteConfig.getValue(key).asNumber()</code>.
  293. *
  294. * @param remoteConfig - The {@link RemoteConfig} instance.
  295. * @param key - The name of the parameter.
  296. *
  297. * @returns The value for the given key as a number.
  298. *
  299. * @public
  300. */
  301. function getNumber(remoteConfig, key) {
  302. return getValue(getModularInstance(remoteConfig), key).asNumber();
  303. }
  304. /**
  305. * Gets the value for the given key as a string.
  306. * Convenience method for calling <code>remoteConfig.getValue(key).asString()</code>.
  307. *
  308. * @param remoteConfig - The {@link RemoteConfig} instance.
  309. * @param key - The name of the parameter.
  310. *
  311. * @returns The value for the given key as a string.
  312. *
  313. * @public
  314. */
  315. function getString(remoteConfig, key) {
  316. return getValue(getModularInstance(remoteConfig), key).asString();
  317. }
  318. /**
  319. * Gets the {@link Value} for the given key.
  320. *
  321. * @param remoteConfig - The {@link RemoteConfig} instance.
  322. * @param key - The name of the parameter.
  323. *
  324. * @returns The value for the given key.
  325. *
  326. * @public
  327. */
  328. function getValue(remoteConfig, key) {
  329. const rc = getModularInstance(remoteConfig);
  330. if (!rc._isInitializationComplete) {
  331. rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` +
  332. ' Await on ensureInitialized if the intent was to get a previously activated value.');
  333. }
  334. const activeConfig = rc._storageCache.getActiveConfig();
  335. if (activeConfig && activeConfig[key] !== undefined) {
  336. return new Value('remote', activeConfig[key]);
  337. }
  338. else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {
  339. return new Value('default', String(rc.defaultConfig[key]));
  340. }
  341. rc._logger.debug(`Returning static value for key "${key}".` +
  342. ' Define a default or remote value if this is unintentional.');
  343. return new Value('static');
  344. }
  345. /**
  346. * Defines the log level to use.
  347. *
  348. * @param remoteConfig - The {@link RemoteConfig} instance.
  349. * @param logLevel - The log level to set.
  350. *
  351. * @public
  352. */
  353. function setLogLevel(remoteConfig, logLevel) {
  354. const rc = getModularInstance(remoteConfig);
  355. switch (logLevel) {
  356. case 'debug':
  357. rc._logger.logLevel = LogLevel.DEBUG;
  358. break;
  359. case 'silent':
  360. rc._logger.logLevel = LogLevel.SILENT;
  361. break;
  362. default:
  363. rc._logger.logLevel = LogLevel.ERROR;
  364. }
  365. }
  366. /**
  367. * Dedupes and returns an array of all the keys of the received objects.
  368. */
  369. function getAllKeys(obj1 = {}, obj2 = {}) {
  370. return Object.keys(Object.assign(Object.assign({}, obj1), obj2));
  371. }
  372. /**
  373. * @license
  374. * Copyright 2019 Google LLC
  375. *
  376. * Licensed under the Apache License, Version 2.0 (the "License");
  377. * you may not use this file except in compliance with the License.
  378. * You may obtain a copy of the License at
  379. *
  380. * http://www.apache.org/licenses/LICENSE-2.0
  381. *
  382. * Unless required by applicable law or agreed to in writing, software
  383. * distributed under the License is distributed on an "AS IS" BASIS,
  384. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  385. * See the License for the specific language governing permissions and
  386. * limitations under the License.
  387. */
  388. /**
  389. * Implements the {@link RemoteConfigClient} abstraction with success response caching.
  390. *
  391. * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service
  392. * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the
  393. * Cache API doesn't support matching entries by time.
  394. */
  395. class CachingClient {
  396. constructor(client, storage, storageCache, logger) {
  397. this.client = client;
  398. this.storage = storage;
  399. this.storageCache = storageCache;
  400. this.logger = logger;
  401. }
  402. /**
  403. * Returns true if the age of the cached fetched configs is less than or equal to
  404. * {@link Settings#minimumFetchIntervalInSeconds}.
  405. *
  406. * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the
  407. * native Fetch API.
  408. *
  409. * <p>Visible for testing.
  410. */
  411. isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) {
  412. // Cache can only be fresh if it's populated.
  413. if (!lastSuccessfulFetchTimestampMillis) {
  414. this.logger.debug('Config fetch cache check. Cache unpopulated.');
  415. return false;
  416. }
  417. // Calculates age of cache entry.
  418. const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;
  419. const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;
  420. this.logger.debug('Config fetch cache check.' +
  421. ` Cache age millis: ${cacheAgeMillis}.` +
  422. ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +
  423. ` Is cache hit: ${isCachedDataFresh}.`);
  424. return isCachedDataFresh;
  425. }
  426. async fetch(request) {
  427. // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.
  428. const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([
  429. this.storage.getLastSuccessfulFetchTimestampMillis(),
  430. this.storage.getLastSuccessfulFetchResponse()
  431. ]);
  432. // Exits early on cache hit.
  433. if (lastSuccessfulFetchResponse &&
  434. this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) {
  435. return lastSuccessfulFetchResponse;
  436. }
  437. // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API
  438. // that allows the caller to pass an ETag.
  439. request.eTag =
  440. lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;
  441. // Falls back to service on cache miss.
  442. const response = await this.client.fetch(request);
  443. // Fetch throws for non-success responses, so success is guaranteed here.
  444. const storageOperations = [
  445. // Uses write-through cache for consistency with synchronous public API.
  446. this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())
  447. ];
  448. if (response.status === 200) {
  449. // Caches response only if it has changed, ie non-304 responses.
  450. storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response));
  451. }
  452. await Promise.all(storageOperations);
  453. return response;
  454. }
  455. }
  456. /**
  457. * @license
  458. * Copyright 2019 Google LLC
  459. *
  460. * Licensed under the Apache License, Version 2.0 (the "License");
  461. * you may not use this file except in compliance with the License.
  462. * You may obtain a copy of the License at
  463. *
  464. * http://www.apache.org/licenses/LICENSE-2.0
  465. *
  466. * Unless required by applicable law or agreed to in writing, software
  467. * distributed under the License is distributed on an "AS IS" BASIS,
  468. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  469. * See the License for the specific language governing permissions and
  470. * limitations under the License.
  471. */
  472. /**
  473. * Attempts to get the most accurate browser language setting.
  474. *
  475. * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.
  476. *
  477. * <p>Defers default language specification to server logic for consistency.
  478. *
  479. * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.
  480. */
  481. function getUserLanguage(navigatorLanguage = navigator) {
  482. return (
  483. // Most reliable, but only supported in Chrome/Firefox.
  484. (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
  485. // Supported in most browsers, but returns the language of the browser
  486. // UI, not the language set in browser settings.
  487. navigatorLanguage.language
  488. // Polyfill otherwise.
  489. );
  490. }
  491. /**
  492. * @license
  493. * Copyright 2019 Google LLC
  494. *
  495. * Licensed under the Apache License, Version 2.0 (the "License");
  496. * you may not use this file except in compliance with the License.
  497. * You may obtain a copy of the License at
  498. *
  499. * http://www.apache.org/licenses/LICENSE-2.0
  500. *
  501. * Unless required by applicable law or agreed to in writing, software
  502. * distributed under the License is distributed on an "AS IS" BASIS,
  503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  504. * See the License for the specific language governing permissions and
  505. * limitations under the License.
  506. */
  507. /**
  508. * Implements the Client abstraction for the Remote Config REST API.
  509. */
  510. class RestClient {
  511. constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) {
  512. this.firebaseInstallations = firebaseInstallations;
  513. this.sdkVersion = sdkVersion;
  514. this.namespace = namespace;
  515. this.projectId = projectId;
  516. this.apiKey = apiKey;
  517. this.appId = appId;
  518. }
  519. /**
  520. * Fetches from the Remote Config REST API.
  521. *
  522. * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't
  523. * connect to the network.
  524. * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the
  525. * fetch response.
  526. * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.
  527. */
  528. async fetch(request) {
  529. const [installationId, installationToken] = await Promise.all([
  530. this.firebaseInstallations.getId(),
  531. this.firebaseInstallations.getToken()
  532. ]);
  533. const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE ||
  534. 'https://firebaseremoteconfig.googleapis.com';
  535. const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;
  536. const headers = {
  537. 'Content-Type': 'application/json',
  538. 'Content-Encoding': 'gzip',
  539. // Deviates from pure decorator by not passing max-age header since we don't currently have
  540. // service behavior using that header.
  541. 'If-None-Match': request.eTag || '*'
  542. };
  543. const requestBody = {
  544. /* eslint-disable camelcase */
  545. sdk_version: this.sdkVersion,
  546. app_instance_id: installationId,
  547. app_instance_id_token: installationToken,
  548. app_id: this.appId,
  549. language_code: getUserLanguage()
  550. /* eslint-enable camelcase */
  551. };
  552. const options = {
  553. method: 'POST',
  554. headers,
  555. body: JSON.stringify(requestBody)
  556. };
  557. // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.
  558. const fetchPromise = fetch(url, options);
  559. const timeoutPromise = new Promise((_resolve, reject) => {
  560. // Maps async event listener to Promise API.
  561. request.signal.addEventListener(() => {
  562. // Emulates https://heycam.github.io/webidl/#aborterror
  563. const error = new Error('The operation was aborted.');
  564. error.name = 'AbortError';
  565. reject(error);
  566. });
  567. });
  568. let response;
  569. try {
  570. await Promise.race([fetchPromise, timeoutPromise]);
  571. response = await fetchPromise;
  572. }
  573. catch (originalError) {
  574. let errorCode = "fetch-client-network" /* ErrorCode.FETCH_NETWORK */;
  575. if ((originalError === null || originalError === void 0 ? void 0 : originalError.name) === 'AbortError') {
  576. errorCode = "fetch-timeout" /* ErrorCode.FETCH_TIMEOUT */;
  577. }
  578. throw ERROR_FACTORY.create(errorCode, {
  579. originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
  580. });
  581. }
  582. let status = response.status;
  583. // Normalizes nullable header to optional.
  584. const responseEtag = response.headers.get('ETag') || undefined;
  585. let config;
  586. let state;
  587. // JSON parsing throws SyntaxError if the response body isn't a JSON string.
  588. // Requesting application/json and checking for a 200 ensures there's JSON data.
  589. if (response.status === 200) {
  590. let responseBody;
  591. try {
  592. responseBody = await response.json();
  593. }
  594. catch (originalError) {
  595. throw ERROR_FACTORY.create("fetch-client-parse" /* ErrorCode.FETCH_PARSE */, {
  596. originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
  597. });
  598. }
  599. config = responseBody['entries'];
  600. state = responseBody['state'];
  601. }
  602. // Normalizes based on legacy state.
  603. if (state === 'INSTANCE_STATE_UNSPECIFIED') {
  604. status = 500;
  605. }
  606. else if (state === 'NO_CHANGE') {
  607. status = 304;
  608. }
  609. else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {
  610. // These cases can be fixed remotely, so normalize to safe value.
  611. config = {};
  612. }
  613. // Normalize to exception-based control flow for non-success cases.
  614. // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for
  615. // differentiating success states (200 from 304; the state body param is undefined in a
  616. // standard 304).
  617. if (status !== 304 && status !== 200) {
  618. throw ERROR_FACTORY.create("fetch-status" /* ErrorCode.FETCH_STATUS */, {
  619. httpStatus: status
  620. });
  621. }
  622. return { status, eTag: responseEtag, config };
  623. }
  624. }
  625. /**
  626. * @license
  627. * Copyright 2019 Google LLC
  628. *
  629. * Licensed under the Apache License, Version 2.0 (the "License");
  630. * you may not use this file except in compliance with the License.
  631. * You may obtain a copy of the License at
  632. *
  633. * http://www.apache.org/licenses/LICENSE-2.0
  634. *
  635. * Unless required by applicable law or agreed to in writing, software
  636. * distributed under the License is distributed on an "AS IS" BASIS,
  637. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  638. * See the License for the specific language governing permissions and
  639. * limitations under the License.
  640. */
  641. /**
  642. * Supports waiting on a backoff by:
  643. *
  644. * <ul>
  645. * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
  646. * <li>Listening on a signal bus for abort events, just like the Fetch API</li>
  647. * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
  648. * request appear the same.</li>
  649. * </ul>
  650. *
  651. * <p>Visible for testing.
  652. */
  653. function setAbortableTimeout(signal, throttleEndTimeMillis) {
  654. return new Promise((resolve, reject) => {
  655. // Derives backoff from given end time, normalizing negative numbers to zero.
  656. const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
  657. const timeout = setTimeout(resolve, backoffMillis);
  658. // Adds listener, rather than sets onabort, because signal is a shared object.
  659. signal.addEventListener(() => {
  660. clearTimeout(timeout);
  661. // If the request completes before this timeout, the rejection has no effect.
  662. reject(ERROR_FACTORY.create("fetch-throttle" /* ErrorCode.FETCH_THROTTLE */, {
  663. throttleEndTimeMillis
  664. }));
  665. });
  666. });
  667. }
  668. /**
  669. * Returns true if the {@link Error} indicates a fetch request may succeed later.
  670. */
  671. function isRetriableError(e) {
  672. if (!(e instanceof FirebaseError) || !e.customData) {
  673. return false;
  674. }
  675. // Uses string index defined by ErrorData, which FirebaseError implements.
  676. const httpStatus = Number(e.customData['httpStatus']);
  677. return (httpStatus === 429 ||
  678. httpStatus === 500 ||
  679. httpStatus === 503 ||
  680. httpStatus === 504);
  681. }
  682. /**
  683. * Decorates a Client with retry logic.
  684. *
  685. * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache
  686. * responses (because the SDK has no use for error responses).
  687. */
  688. class RetryingClient {
  689. constructor(client, storage) {
  690. this.client = client;
  691. this.storage = storage;
  692. }
  693. async fetch(request) {
  694. const throttleMetadata = (await this.storage.getThrottleMetadata()) || {
  695. backoffCount: 0,
  696. throttleEndTimeMillis: Date.now()
  697. };
  698. return this.attemptFetch(request, throttleMetadata);
  699. }
  700. /**
  701. * A recursive helper for attempting a fetch request repeatedly.
  702. *
  703. * @throws any non-retriable errors.
  704. */
  705. async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) {
  706. // Starts with a (potentially zero) timeout to support resumption from stored state.
  707. // Ensures the throttle end time is honored if the last attempt timed out.
  708. // Note the SDK will never make a request if the fetch timeout expires at this point.
  709. await setAbortableTimeout(request.signal, throttleEndTimeMillis);
  710. try {
  711. const response = await this.client.fetch(request);
  712. // Note the SDK only clears throttle state if response is success or non-retriable.
  713. await this.storage.deleteThrottleMetadata();
  714. return response;
  715. }
  716. catch (e) {
  717. if (!isRetriableError(e)) {
  718. throw e;
  719. }
  720. // Increments backoff state.
  721. const throttleMetadata = {
  722. throttleEndTimeMillis: Date.now() + calculateBackoffMillis(backoffCount),
  723. backoffCount: backoffCount + 1
  724. };
  725. // Persists state.
  726. await this.storage.setThrottleMetadata(throttleMetadata);
  727. return this.attemptFetch(request, throttleMetadata);
  728. }
  729. }
  730. }
  731. /**
  732. * @license
  733. * Copyright 2019 Google LLC
  734. *
  735. * Licensed under the Apache License, Version 2.0 (the "License");
  736. * you may not use this file except in compliance with the License.
  737. * You may obtain a copy of the License at
  738. *
  739. * http://www.apache.org/licenses/LICENSE-2.0
  740. *
  741. * Unless required by applicable law or agreed to in writing, software
  742. * distributed under the License is distributed on an "AS IS" BASIS,
  743. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  744. * See the License for the specific language governing permissions and
  745. * limitations under the License.
  746. */
  747. const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute
  748. const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.
  749. /**
  750. * Encapsulates business logic mapping network and storage dependencies to the public SDK API.
  751. *
  752. * See {@link https://github.com/FirebasePrivate/firebase-js-sdk/blob/master/packages/firebase/index.d.ts|interface documentation} for method descriptions.
  753. */
  754. class RemoteConfig {
  755. constructor(
  756. // Required by FirebaseServiceFactory interface.
  757. app,
  758. // JS doesn't support private yet
  759. // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an
  760. // underscore prefix.
  761. /**
  762. * @internal
  763. */
  764. _client,
  765. /**
  766. * @internal
  767. */
  768. _storageCache,
  769. /**
  770. * @internal
  771. */
  772. _storage,
  773. /**
  774. * @internal
  775. */
  776. _logger) {
  777. this.app = app;
  778. this._client = _client;
  779. this._storageCache = _storageCache;
  780. this._storage = _storage;
  781. this._logger = _logger;
  782. /**
  783. * Tracks completion of initialization promise.
  784. * @internal
  785. */
  786. this._isInitializationComplete = false;
  787. this.settings = {
  788. fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,
  789. minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS
  790. };
  791. this.defaultConfig = {};
  792. }
  793. get fetchTimeMillis() {
  794. return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;
  795. }
  796. get lastFetchStatus() {
  797. return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';
  798. }
  799. }
  800. /**
  801. * @license
  802. * Copyright 2019 Google LLC
  803. *
  804. * Licensed under the Apache License, Version 2.0 (the "License");
  805. * you may not use this file except in compliance with the License.
  806. * You may obtain a copy of the License at
  807. *
  808. * http://www.apache.org/licenses/LICENSE-2.0
  809. *
  810. * Unless required by applicable law or agreed to in writing, software
  811. * distributed under the License is distributed on an "AS IS" BASIS,
  812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  813. * See the License for the specific language governing permissions and
  814. * limitations under the License.
  815. */
  816. /**
  817. * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.
  818. */
  819. function toFirebaseError(event, errorCode) {
  820. const originalError = event.target.error || undefined;
  821. return ERROR_FACTORY.create(errorCode, {
  822. originalErrorMessage: originalError && (originalError === null || originalError === void 0 ? void 0 : originalError.message)
  823. });
  824. }
  825. /**
  826. * A general-purpose store keyed by app + namespace + {@link
  827. * ProjectNamespaceKeyFieldValue}.
  828. *
  829. * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact
  830. * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys
  831. * for a set of key-value pairs. See {@link Storage#createCompositeKey}.
  832. *
  833. * <p>Visible for testing.
  834. */
  835. const APP_NAMESPACE_STORE = 'app_namespace_store';
  836. const DB_NAME = 'firebase_remote_config';
  837. const DB_VERSION = 1;
  838. // Visible for testing.
  839. function openDatabase() {
  840. return new Promise((resolve, reject) => {
  841. try {
  842. const request = indexedDB.open(DB_NAME, DB_VERSION);
  843. request.onerror = event => {
  844. reject(toFirebaseError(event, "storage-open" /* ErrorCode.STORAGE_OPEN */));
  845. };
  846. request.onsuccess = event => {
  847. resolve(event.target.result);
  848. };
  849. request.onupgradeneeded = event => {
  850. const db = event.target.result;
  851. // We don't use 'break' in this switch statement, the fall-through
  852. // behavior is what we want, because if there are multiple versions between
  853. // the old version and the current version, we want ALL the migrations
  854. // that correspond to those versions to run, not only the last one.
  855. // eslint-disable-next-line default-case
  856. switch (event.oldVersion) {
  857. case 0:
  858. db.createObjectStore(APP_NAMESPACE_STORE, {
  859. keyPath: 'compositeKey'
  860. });
  861. }
  862. };
  863. }
  864. catch (error) {
  865. reject(ERROR_FACTORY.create("storage-open" /* ErrorCode.STORAGE_OPEN */, {
  866. originalErrorMessage: error === null || error === void 0 ? void 0 : error.message
  867. }));
  868. }
  869. });
  870. }
  871. /**
  872. * Abstracts data persistence.
  873. */
  874. class Storage {
  875. /**
  876. * @param appId enables storage segmentation by app (ID + name).
  877. * @param appName enables storage segmentation by app (ID + name).
  878. * @param namespace enables storage segmentation by namespace.
  879. */
  880. constructor(appId, appName, namespace, openDbPromise = openDatabase()) {
  881. this.appId = appId;
  882. this.appName = appName;
  883. this.namespace = namespace;
  884. this.openDbPromise = openDbPromise;
  885. }
  886. getLastFetchStatus() {
  887. return this.get('last_fetch_status');
  888. }
  889. setLastFetchStatus(status) {
  890. return this.set('last_fetch_status', status);
  891. }
  892. // This is comparable to a cache entry timestamp. If we need to expire other data, we could
  893. // consider adding timestamp to all storage records and an optional max age arg to getters.
  894. getLastSuccessfulFetchTimestampMillis() {
  895. return this.get('last_successful_fetch_timestamp_millis');
  896. }
  897. setLastSuccessfulFetchTimestampMillis(timestamp) {
  898. return this.set('last_successful_fetch_timestamp_millis', timestamp);
  899. }
  900. getLastSuccessfulFetchResponse() {
  901. return this.get('last_successful_fetch_response');
  902. }
  903. setLastSuccessfulFetchResponse(response) {
  904. return this.set('last_successful_fetch_response', response);
  905. }
  906. getActiveConfig() {
  907. return this.get('active_config');
  908. }
  909. setActiveConfig(config) {
  910. return this.set('active_config', config);
  911. }
  912. getActiveConfigEtag() {
  913. return this.get('active_config_etag');
  914. }
  915. setActiveConfigEtag(etag) {
  916. return this.set('active_config_etag', etag);
  917. }
  918. getThrottleMetadata() {
  919. return this.get('throttle_metadata');
  920. }
  921. setThrottleMetadata(metadata) {
  922. return this.set('throttle_metadata', metadata);
  923. }
  924. deleteThrottleMetadata() {
  925. return this.delete('throttle_metadata');
  926. }
  927. async get(key) {
  928. const db = await this.openDbPromise;
  929. return new Promise((resolve, reject) => {
  930. const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');
  931. const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
  932. const compositeKey = this.createCompositeKey(key);
  933. try {
  934. const request = objectStore.get(compositeKey);
  935. request.onerror = event => {
  936. reject(toFirebaseError(event, "storage-get" /* ErrorCode.STORAGE_GET */));
  937. };
  938. request.onsuccess = event => {
  939. const result = event.target.result;
  940. if (result) {
  941. resolve(result.value);
  942. }
  943. else {
  944. resolve(undefined);
  945. }
  946. };
  947. }
  948. catch (e) {
  949. reject(ERROR_FACTORY.create("storage-get" /* ErrorCode.STORAGE_GET */, {
  950. originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
  951. }));
  952. }
  953. });
  954. }
  955. async set(key, value) {
  956. const db = await this.openDbPromise;
  957. return new Promise((resolve, reject) => {
  958. const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
  959. const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
  960. const compositeKey = this.createCompositeKey(key);
  961. try {
  962. const request = objectStore.put({
  963. compositeKey,
  964. value
  965. });
  966. request.onerror = (event) => {
  967. reject(toFirebaseError(event, "storage-set" /* ErrorCode.STORAGE_SET */));
  968. };
  969. request.onsuccess = () => {
  970. resolve();
  971. };
  972. }
  973. catch (e) {
  974. reject(ERROR_FACTORY.create("storage-set" /* ErrorCode.STORAGE_SET */, {
  975. originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
  976. }));
  977. }
  978. });
  979. }
  980. async delete(key) {
  981. const db = await this.openDbPromise;
  982. return new Promise((resolve, reject) => {
  983. const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
  984. const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
  985. const compositeKey = this.createCompositeKey(key);
  986. try {
  987. const request = objectStore.delete(compositeKey);
  988. request.onerror = (event) => {
  989. reject(toFirebaseError(event, "storage-delete" /* ErrorCode.STORAGE_DELETE */));
  990. };
  991. request.onsuccess = () => {
  992. resolve();
  993. };
  994. }
  995. catch (e) {
  996. reject(ERROR_FACTORY.create("storage-delete" /* ErrorCode.STORAGE_DELETE */, {
  997. originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
  998. }));
  999. }
  1000. });
  1001. }
  1002. // Facilitates composite key functionality (which is unsupported in IE).
  1003. createCompositeKey(key) {
  1004. return [this.appId, this.appName, this.namespace, key].join();
  1005. }
  1006. }
  1007. /**
  1008. * @license
  1009. * Copyright 2019 Google LLC
  1010. *
  1011. * Licensed under the Apache License, Version 2.0 (the "License");
  1012. * you may not use this file except in compliance with the License.
  1013. * You may obtain a copy of the License at
  1014. *
  1015. * http://www.apache.org/licenses/LICENSE-2.0
  1016. *
  1017. * Unless required by applicable law or agreed to in writing, software
  1018. * distributed under the License is distributed on an "AS IS" BASIS,
  1019. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1020. * See the License for the specific language governing permissions and
  1021. * limitations under the License.
  1022. */
  1023. /**
  1024. * A memory cache layer over storage to support the SDK's synchronous read requirements.
  1025. */
  1026. class StorageCache {
  1027. constructor(storage) {
  1028. this.storage = storage;
  1029. }
  1030. /**
  1031. * Memory-only getters
  1032. */
  1033. getLastFetchStatus() {
  1034. return this.lastFetchStatus;
  1035. }
  1036. getLastSuccessfulFetchTimestampMillis() {
  1037. return this.lastSuccessfulFetchTimestampMillis;
  1038. }
  1039. getActiveConfig() {
  1040. return this.activeConfig;
  1041. }
  1042. /**
  1043. * Read-ahead getter
  1044. */
  1045. async loadFromStorage() {
  1046. const lastFetchStatusPromise = this.storage.getLastFetchStatus();
  1047. const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis();
  1048. const activeConfigPromise = this.storage.getActiveConfig();
  1049. // Note:
  1050. // 1. we consistently check for undefined to avoid clobbering defined values
  1051. // in memory
  1052. // 2. we defer awaiting to improve readability, as opposed to destructuring
  1053. // a Promise.all result, for example
  1054. const lastFetchStatus = await lastFetchStatusPromise;
  1055. if (lastFetchStatus) {
  1056. this.lastFetchStatus = lastFetchStatus;
  1057. }
  1058. const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise;
  1059. if (lastSuccessfulFetchTimestampMillis) {
  1060. this.lastSuccessfulFetchTimestampMillis =
  1061. lastSuccessfulFetchTimestampMillis;
  1062. }
  1063. const activeConfig = await activeConfigPromise;
  1064. if (activeConfig) {
  1065. this.activeConfig = activeConfig;
  1066. }
  1067. }
  1068. /**
  1069. * Write-through setters
  1070. */
  1071. setLastFetchStatus(status) {
  1072. this.lastFetchStatus = status;
  1073. return this.storage.setLastFetchStatus(status);
  1074. }
  1075. setLastSuccessfulFetchTimestampMillis(timestampMillis) {
  1076. this.lastSuccessfulFetchTimestampMillis = timestampMillis;
  1077. return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);
  1078. }
  1079. setActiveConfig(activeConfig) {
  1080. this.activeConfig = activeConfig;
  1081. return this.storage.setActiveConfig(activeConfig);
  1082. }
  1083. }
  1084. /**
  1085. * @license
  1086. * Copyright 2020 Google LLC
  1087. *
  1088. * Licensed under the Apache License, Version 2.0 (the "License");
  1089. * you may not use this file except in compliance with the License.
  1090. * You may obtain a copy of the License at
  1091. *
  1092. * http://www.apache.org/licenses/LICENSE-2.0
  1093. *
  1094. * Unless required by applicable law or agreed to in writing, software
  1095. * distributed under the License is distributed on an "AS IS" BASIS,
  1096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1097. * See the License for the specific language governing permissions and
  1098. * limitations under the License.
  1099. */
  1100. function registerRemoteConfig() {
  1101. _registerComponent(new Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  1102. registerVersion(name, version);
  1103. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  1104. registerVersion(name, version, 'esm2017');
  1105. function remoteConfigFactory(container, { instanceIdentifier: namespace }) {
  1106. /* Dependencies */
  1107. // getImmediate for FirebaseApp will always succeed
  1108. const app = container.getProvider('app').getImmediate();
  1109. // The following call will always succeed because rc has `import '@firebase/installations'`
  1110. const installations = container
  1111. .getProvider('installations-internal')
  1112. .getImmediate();
  1113. // Guards against the SDK being used in non-browser environments.
  1114. if (typeof window === 'undefined') {
  1115. throw ERROR_FACTORY.create("registration-window" /* ErrorCode.REGISTRATION_WINDOW */);
  1116. }
  1117. // Guards against the SDK being used when indexedDB is not available.
  1118. if (!isIndexedDBAvailable()) {
  1119. throw ERROR_FACTORY.create("indexed-db-unavailable" /* ErrorCode.INDEXED_DB_UNAVAILABLE */);
  1120. }
  1121. // Normalizes optional inputs.
  1122. const { projectId, apiKey, appId } = app.options;
  1123. if (!projectId) {
  1124. throw ERROR_FACTORY.create("registration-project-id" /* ErrorCode.REGISTRATION_PROJECT_ID */);
  1125. }
  1126. if (!apiKey) {
  1127. throw ERROR_FACTORY.create("registration-api-key" /* ErrorCode.REGISTRATION_API_KEY */);
  1128. }
  1129. if (!appId) {
  1130. throw ERROR_FACTORY.create("registration-app-id" /* ErrorCode.REGISTRATION_APP_ID */);
  1131. }
  1132. namespace = namespace || 'firebase';
  1133. const storage = new Storage(appId, app.name, namespace);
  1134. const storageCache = new StorageCache(storage);
  1135. const logger = new Logger(name);
  1136. // Sets ERROR as the default log level.
  1137. // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.
  1138. logger.logLevel = LogLevel.ERROR;
  1139. const restClient = new RestClient(installations,
  1140. // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.
  1141. SDK_VERSION, namespace, projectId, apiKey, appId);
  1142. const retryingClient = new RetryingClient(restClient, storage);
  1143. const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger);
  1144. const remoteConfigInstance = new RemoteConfig(app, cachingClient, storageCache, storage, logger);
  1145. // Starts warming cache.
  1146. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1147. ensureInitialized(remoteConfigInstance);
  1148. return remoteConfigInstance;
  1149. }
  1150. }
  1151. /**
  1152. * @license
  1153. * Copyright 2020 Google LLC
  1154. *
  1155. * Licensed under the Apache License, Version 2.0 (the "License");
  1156. * you may not use this file except in compliance with the License.
  1157. * You may obtain a copy of the License at
  1158. *
  1159. * http://www.apache.org/licenses/LICENSE-2.0
  1160. *
  1161. * Unless required by applicable law or agreed to in writing, software
  1162. * distributed under the License is distributed on an "AS IS" BASIS,
  1163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1164. * See the License for the specific language governing permissions and
  1165. * limitations under the License.
  1166. */
  1167. // This API is put in a separate file, so we can stub fetchConfig and activate in tests.
  1168. // It's not possible to stub standalone functions from the same module.
  1169. /**
  1170. *
  1171. * Performs fetch and activate operations, as a convenience.
  1172. *
  1173. * @param remoteConfig - The {@link RemoteConfig} instance.
  1174. *
  1175. * @returns A `Promise` which resolves to true if the current call activated the fetched configs.
  1176. * If the fetched configs were already activated, the `Promise` will resolve to false.
  1177. *
  1178. * @public
  1179. */
  1180. async function fetchAndActivate(remoteConfig) {
  1181. remoteConfig = getModularInstance(remoteConfig);
  1182. await fetchConfig(remoteConfig);
  1183. return activate(remoteConfig);
  1184. }
  1185. /**
  1186. * This method provides two different checks:
  1187. *
  1188. * 1. Check if IndexedDB exists in the browser environment.
  1189. * 2. Check if the current browser context allows IndexedDB `open()` calls.
  1190. *
  1191. * @returns A `Promise` which resolves to true if a {@link RemoteConfig} instance
  1192. * can be initialized in this environment, or false if it cannot.
  1193. * @public
  1194. */
  1195. async function isSupported() {
  1196. if (!isIndexedDBAvailable()) {
  1197. return false;
  1198. }
  1199. try {
  1200. const isDBOpenable = await validateIndexedDBOpenable();
  1201. return isDBOpenable;
  1202. }
  1203. catch (error) {
  1204. return false;
  1205. }
  1206. }
  1207. /**
  1208. * Firebase Remote Config
  1209. *
  1210. * @packageDocumentation
  1211. */
  1212. /** register component and version */
  1213. registerRemoteConfig();
  1214. export { activate, ensureInitialized, fetchAndActivate, fetchConfig, getAll, getBoolean, getNumber, getRemoteConfig, getString, getValue, isSupported, setLogLevel };
  1215. //# sourceMappingURL=index.esm2017.js.map