index.cjs.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var component = require('@firebase/component');
  4. var tslib = require('tslib');
  5. var logger$1 = require('@firebase/logger');
  6. var util = require('@firebase/util');
  7. var idb = require('idb');
  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. var PlatformLoggerServiceImpl = /** @class */ (function () {
  25. function PlatformLoggerServiceImpl(container) {
  26. this.container = container;
  27. }
  28. // In initial implementation, this will be called by installations on
  29. // auth token refresh, and installations will send this string.
  30. PlatformLoggerServiceImpl.prototype.getPlatformInfoString = function () {
  31. var providers = this.container.getProviders();
  32. // Loop through providers and get library/version pairs from any that are
  33. // version components.
  34. return providers
  35. .map(function (provider) {
  36. if (isVersionServiceProvider(provider)) {
  37. var service = provider.getImmediate();
  38. return "".concat(service.library, "/").concat(service.version);
  39. }
  40. else {
  41. return null;
  42. }
  43. })
  44. .filter(function (logString) { return logString; })
  45. .join(' ');
  46. };
  47. return PlatformLoggerServiceImpl;
  48. }());
  49. /**
  50. *
  51. * @param provider check if this provider provides a VersionService
  52. *
  53. * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
  54. * provides VersionService. The provider is not necessarily a 'app-version'
  55. * provider.
  56. */
  57. function isVersionServiceProvider(provider) {
  58. var component = provider.getComponent();
  59. return (component === null || component === void 0 ? void 0 : component.type) === "VERSION" /* ComponentType.VERSION */;
  60. }
  61. var name$o = "@firebase/app";
  62. var version$1 = "0.9.13";
  63. /**
  64. * @license
  65. * Copyright 2019 Google LLC
  66. *
  67. * Licensed under the Apache License, Version 2.0 (the "License");
  68. * you may not use this file except in compliance with the License.
  69. * You may obtain a copy of the License at
  70. *
  71. * http://www.apache.org/licenses/LICENSE-2.0
  72. *
  73. * Unless required by applicable law or agreed to in writing, software
  74. * distributed under the License is distributed on an "AS IS" BASIS,
  75. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  76. * See the License for the specific language governing permissions and
  77. * limitations under the License.
  78. */
  79. var logger = new logger$1.Logger('@firebase/app');
  80. var name$n = "@firebase/app-compat";
  81. var name$m = "@firebase/analytics-compat";
  82. var name$l = "@firebase/analytics";
  83. var name$k = "@firebase/app-check-compat";
  84. var name$j = "@firebase/app-check";
  85. var name$i = "@firebase/auth";
  86. var name$h = "@firebase/auth-compat";
  87. var name$g = "@firebase/database";
  88. var name$f = "@firebase/database-compat";
  89. var name$e = "@firebase/functions";
  90. var name$d = "@firebase/functions-compat";
  91. var name$c = "@firebase/installations";
  92. var name$b = "@firebase/installations-compat";
  93. var name$a = "@firebase/messaging";
  94. var name$9 = "@firebase/messaging-compat";
  95. var name$8 = "@firebase/performance";
  96. var name$7 = "@firebase/performance-compat";
  97. var name$6 = "@firebase/remote-config";
  98. var name$5 = "@firebase/remote-config-compat";
  99. var name$4 = "@firebase/storage";
  100. var name$3 = "@firebase/storage-compat";
  101. var name$2 = "@firebase/firestore";
  102. var name$1 = "@firebase/firestore-compat";
  103. var name = "firebase";
  104. var version = "9.23.0";
  105. /**
  106. * @license
  107. * Copyright 2019 Google LLC
  108. *
  109. * Licensed under the Apache License, Version 2.0 (the "License");
  110. * you may not use this file except in compliance with the License.
  111. * You may obtain a copy of the License at
  112. *
  113. * http://www.apache.org/licenses/LICENSE-2.0
  114. *
  115. * Unless required by applicable law or agreed to in writing, software
  116. * distributed under the License is distributed on an "AS IS" BASIS,
  117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  118. * See the License for the specific language governing permissions and
  119. * limitations under the License.
  120. */
  121. var _a$1;
  122. /**
  123. * The default app name
  124. *
  125. * @internal
  126. */
  127. var DEFAULT_ENTRY_NAME = '[DEFAULT]';
  128. var PLATFORM_LOG_STRING = (_a$1 = {},
  129. _a$1[name$o] = 'fire-core',
  130. _a$1[name$n] = 'fire-core-compat',
  131. _a$1[name$l] = 'fire-analytics',
  132. _a$1[name$m] = 'fire-analytics-compat',
  133. _a$1[name$j] = 'fire-app-check',
  134. _a$1[name$k] = 'fire-app-check-compat',
  135. _a$1[name$i] = 'fire-auth',
  136. _a$1[name$h] = 'fire-auth-compat',
  137. _a$1[name$g] = 'fire-rtdb',
  138. _a$1[name$f] = 'fire-rtdb-compat',
  139. _a$1[name$e] = 'fire-fn',
  140. _a$1[name$d] = 'fire-fn-compat',
  141. _a$1[name$c] = 'fire-iid',
  142. _a$1[name$b] = 'fire-iid-compat',
  143. _a$1[name$a] = 'fire-fcm',
  144. _a$1[name$9] = 'fire-fcm-compat',
  145. _a$1[name$8] = 'fire-perf',
  146. _a$1[name$7] = 'fire-perf-compat',
  147. _a$1[name$6] = 'fire-rc',
  148. _a$1[name$5] = 'fire-rc-compat',
  149. _a$1[name$4] = 'fire-gcs',
  150. _a$1[name$3] = 'fire-gcs-compat',
  151. _a$1[name$2] = 'fire-fst',
  152. _a$1[name$1] = 'fire-fst-compat',
  153. _a$1['fire-js'] = 'fire-js',
  154. _a$1[name] = 'fire-js-all',
  155. _a$1);
  156. /**
  157. * @license
  158. * Copyright 2019 Google LLC
  159. *
  160. * Licensed under the Apache License, Version 2.0 (the "License");
  161. * you may not use this file except in compliance with the License.
  162. * You may obtain a copy of the License at
  163. *
  164. * http://www.apache.org/licenses/LICENSE-2.0
  165. *
  166. * Unless required by applicable law or agreed to in writing, software
  167. * distributed under the License is distributed on an "AS IS" BASIS,
  168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  169. * See the License for the specific language governing permissions and
  170. * limitations under the License.
  171. */
  172. /**
  173. * @internal
  174. */
  175. var _apps = new Map();
  176. /**
  177. * Registered components.
  178. *
  179. * @internal
  180. */
  181. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  182. var _components = new Map();
  183. /**
  184. * @param component - the component being added to this app's container
  185. *
  186. * @internal
  187. */
  188. function _addComponent(app, component) {
  189. try {
  190. app.container.addComponent(component);
  191. }
  192. catch (e) {
  193. logger.debug("Component ".concat(component.name, " failed to register with FirebaseApp ").concat(app.name), e);
  194. }
  195. }
  196. /**
  197. *
  198. * @internal
  199. */
  200. function _addOrOverwriteComponent(app, component) {
  201. app.container.addOrOverwriteComponent(component);
  202. }
  203. /**
  204. *
  205. * @param component - the component to register
  206. * @returns whether or not the component is registered successfully
  207. *
  208. * @internal
  209. */
  210. function _registerComponent(component) {
  211. var e_1, _a;
  212. var componentName = component.name;
  213. if (_components.has(componentName)) {
  214. logger.debug("There were multiple attempts to register component ".concat(componentName, "."));
  215. return false;
  216. }
  217. _components.set(componentName, component);
  218. try {
  219. // add the component to existing app instances
  220. for (var _b = tslib.__values(_apps.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  221. var app = _c.value;
  222. _addComponent(app, component);
  223. }
  224. }
  225. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  226. finally {
  227. try {
  228. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  229. }
  230. finally { if (e_1) throw e_1.error; }
  231. }
  232. return true;
  233. }
  234. /**
  235. *
  236. * @param app - FirebaseApp instance
  237. * @param name - service name
  238. *
  239. * @returns the provider for the service with the matching name
  240. *
  241. * @internal
  242. */
  243. function _getProvider(app, name) {
  244. var heartbeatController = app.container
  245. .getProvider('heartbeat')
  246. .getImmediate({ optional: true });
  247. if (heartbeatController) {
  248. void heartbeatController.triggerHeartbeat();
  249. }
  250. return app.container.getProvider(name);
  251. }
  252. /**
  253. *
  254. * @param app - FirebaseApp instance
  255. * @param name - service name
  256. * @param instanceIdentifier - service instance identifier in case the service supports multiple instances
  257. *
  258. * @internal
  259. */
  260. function _removeServiceInstance(app, name, instanceIdentifier) {
  261. if (instanceIdentifier === void 0) { instanceIdentifier = DEFAULT_ENTRY_NAME; }
  262. _getProvider(app, name).clearInstance(instanceIdentifier);
  263. }
  264. /**
  265. * Test only
  266. *
  267. * @internal
  268. */
  269. function _clearComponents() {
  270. _components.clear();
  271. }
  272. /**
  273. * @license
  274. * Copyright 2019 Google LLC
  275. *
  276. * Licensed under the Apache License, Version 2.0 (the "License");
  277. * you may not use this file except in compliance with the License.
  278. * You may obtain a copy of the License at
  279. *
  280. * http://www.apache.org/licenses/LICENSE-2.0
  281. *
  282. * Unless required by applicable law or agreed to in writing, software
  283. * distributed under the License is distributed on an "AS IS" BASIS,
  284. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  285. * See the License for the specific language governing permissions and
  286. * limitations under the License.
  287. */
  288. var _a;
  289. var ERRORS = (_a = {},
  290. _a["no-app" /* AppError.NO_APP */] = "No Firebase App '{$appName}' has been created - " +
  291. 'call initializeApp() first',
  292. _a["bad-app-name" /* AppError.BAD_APP_NAME */] = "Illegal App name: '{$appName}",
  293. _a["duplicate-app" /* AppError.DUPLICATE_APP */] = "Firebase App named '{$appName}' already exists with different options or config",
  294. _a["app-deleted" /* AppError.APP_DELETED */] = "Firebase App named '{$appName}' already deleted",
  295. _a["no-options" /* AppError.NO_OPTIONS */] = 'Need to provide options, when not being deployed to hosting via source.',
  296. _a["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */] = 'firebase.{$appName}() takes either no argument or a ' +
  297. 'Firebase App instance.',
  298. _a["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */] = 'First argument to `onLog` must be null or a function.',
  299. _a["idb-open" /* AppError.IDB_OPEN */] = 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
  300. _a["idb-get" /* AppError.IDB_GET */] = 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
  301. _a["idb-set" /* AppError.IDB_WRITE */] = 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
  302. _a["idb-delete" /* AppError.IDB_DELETE */] = 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
  303. _a);
  304. var ERROR_FACTORY = new util.ErrorFactory('app', 'Firebase', ERRORS);
  305. /**
  306. * @license
  307. * Copyright 2019 Google LLC
  308. *
  309. * Licensed under the Apache License, Version 2.0 (the "License");
  310. * you may not use this file except in compliance with the License.
  311. * You may obtain a copy of the License at
  312. *
  313. * http://www.apache.org/licenses/LICENSE-2.0
  314. *
  315. * Unless required by applicable law or agreed to in writing, software
  316. * distributed under the License is distributed on an "AS IS" BASIS,
  317. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  318. * See the License for the specific language governing permissions and
  319. * limitations under the License.
  320. */
  321. var FirebaseAppImpl = /** @class */ (function () {
  322. function FirebaseAppImpl(options, config, container) {
  323. var _this = this;
  324. this._isDeleted = false;
  325. this._options = tslib.__assign({}, options);
  326. this._config = tslib.__assign({}, config);
  327. this._name = config.name;
  328. this._automaticDataCollectionEnabled =
  329. config.automaticDataCollectionEnabled;
  330. this._container = container;
  331. this.container.addComponent(new component.Component('app', function () { return _this; }, "PUBLIC" /* ComponentType.PUBLIC */));
  332. }
  333. Object.defineProperty(FirebaseAppImpl.prototype, "automaticDataCollectionEnabled", {
  334. get: function () {
  335. this.checkDestroyed();
  336. return this._automaticDataCollectionEnabled;
  337. },
  338. set: function (val) {
  339. this.checkDestroyed();
  340. this._automaticDataCollectionEnabled = val;
  341. },
  342. enumerable: false,
  343. configurable: true
  344. });
  345. Object.defineProperty(FirebaseAppImpl.prototype, "name", {
  346. get: function () {
  347. this.checkDestroyed();
  348. return this._name;
  349. },
  350. enumerable: false,
  351. configurable: true
  352. });
  353. Object.defineProperty(FirebaseAppImpl.prototype, "options", {
  354. get: function () {
  355. this.checkDestroyed();
  356. return this._options;
  357. },
  358. enumerable: false,
  359. configurable: true
  360. });
  361. Object.defineProperty(FirebaseAppImpl.prototype, "config", {
  362. get: function () {
  363. this.checkDestroyed();
  364. return this._config;
  365. },
  366. enumerable: false,
  367. configurable: true
  368. });
  369. Object.defineProperty(FirebaseAppImpl.prototype, "container", {
  370. get: function () {
  371. return this._container;
  372. },
  373. enumerable: false,
  374. configurable: true
  375. });
  376. Object.defineProperty(FirebaseAppImpl.prototype, "isDeleted", {
  377. get: function () {
  378. return this._isDeleted;
  379. },
  380. set: function (val) {
  381. this._isDeleted = val;
  382. },
  383. enumerable: false,
  384. configurable: true
  385. });
  386. /**
  387. * This function will throw an Error if the App has already been deleted -
  388. * use before performing API actions on the App.
  389. */
  390. FirebaseAppImpl.prototype.checkDestroyed = function () {
  391. if (this.isDeleted) {
  392. throw ERROR_FACTORY.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
  393. }
  394. };
  395. return FirebaseAppImpl;
  396. }());
  397. /**
  398. * @license
  399. * Copyright 2019 Google LLC
  400. *
  401. * Licensed under the Apache License, Version 2.0 (the "License");
  402. * you may not use this file except in compliance with the License.
  403. * You may obtain a copy of the License at
  404. *
  405. * http://www.apache.org/licenses/LICENSE-2.0
  406. *
  407. * Unless required by applicable law or agreed to in writing, software
  408. * distributed under the License is distributed on an "AS IS" BASIS,
  409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  410. * See the License for the specific language governing permissions and
  411. * limitations under the License.
  412. */
  413. /**
  414. * The current SDK version.
  415. *
  416. * @public
  417. */
  418. var SDK_VERSION = version;
  419. function initializeApp(_options, rawConfig) {
  420. var e_1, _a;
  421. if (rawConfig === void 0) { rawConfig = {}; }
  422. var options = _options;
  423. if (typeof rawConfig !== 'object') {
  424. var name_1 = rawConfig;
  425. rawConfig = { name: name_1 };
  426. }
  427. var config = tslib.__assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
  428. var name = config.name;
  429. if (typeof name !== 'string' || !name) {
  430. throw ERROR_FACTORY.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
  431. appName: String(name)
  432. });
  433. }
  434. options || (options = util.getDefaultAppConfig());
  435. if (!options) {
  436. throw ERROR_FACTORY.create("no-options" /* AppError.NO_OPTIONS */);
  437. }
  438. var existingApp = _apps.get(name);
  439. if (existingApp) {
  440. // return the existing app if options and config deep equal the ones in the existing app.
  441. if (util.deepEqual(options, existingApp.options) &&
  442. util.deepEqual(config, existingApp.config)) {
  443. return existingApp;
  444. }
  445. else {
  446. throw ERROR_FACTORY.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
  447. }
  448. }
  449. var container = new component.ComponentContainer(name);
  450. try {
  451. for (var _b = tslib.__values(_components.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  452. var component$1 = _c.value;
  453. container.addComponent(component$1);
  454. }
  455. }
  456. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  457. finally {
  458. try {
  459. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  460. }
  461. finally { if (e_1) throw e_1.error; }
  462. }
  463. var newApp = new FirebaseAppImpl(options, config, container);
  464. _apps.set(name, newApp);
  465. return newApp;
  466. }
  467. /**
  468. * Retrieves a {@link @firebase/app#FirebaseApp} instance.
  469. *
  470. * When called with no arguments, the default app is returned. When an app name
  471. * is provided, the app corresponding to that name is returned.
  472. *
  473. * An exception is thrown if the app being retrieved has not yet been
  474. * initialized.
  475. *
  476. * @example
  477. * ```javascript
  478. * // Return the default app
  479. * const app = getApp();
  480. * ```
  481. *
  482. * @example
  483. * ```javascript
  484. * // Return a named app
  485. * const otherApp = getApp("otherApp");
  486. * ```
  487. *
  488. * @param name - Optional name of the app to return. If no name is
  489. * provided, the default is `"[DEFAULT]"`.
  490. *
  491. * @returns The app corresponding to the provided app name.
  492. * If no app name is provided, the default app is returned.
  493. *
  494. * @public
  495. */
  496. function getApp(name) {
  497. if (name === void 0) { name = DEFAULT_ENTRY_NAME; }
  498. var app = _apps.get(name);
  499. if (!app && name === DEFAULT_ENTRY_NAME && util.getDefaultAppConfig()) {
  500. return initializeApp();
  501. }
  502. if (!app) {
  503. throw ERROR_FACTORY.create("no-app" /* AppError.NO_APP */, { appName: name });
  504. }
  505. return app;
  506. }
  507. /**
  508. * A (read-only) array of all initialized apps.
  509. * @public
  510. */
  511. function getApps() {
  512. return Array.from(_apps.values());
  513. }
  514. /**
  515. * Renders this app unusable and frees the resources of all associated
  516. * services.
  517. *
  518. * @example
  519. * ```javascript
  520. * deleteApp(app)
  521. * .then(function() {
  522. * console.log("App deleted successfully");
  523. * })
  524. * .catch(function(error) {
  525. * console.log("Error deleting app:", error);
  526. * });
  527. * ```
  528. *
  529. * @public
  530. */
  531. function deleteApp(app) {
  532. return tslib.__awaiter(this, void 0, void 0, function () {
  533. var name;
  534. return tslib.__generator(this, function (_a) {
  535. switch (_a.label) {
  536. case 0:
  537. name = app.name;
  538. if (!_apps.has(name)) return [3 /*break*/, 2];
  539. _apps.delete(name);
  540. return [4 /*yield*/, Promise.all(app.container
  541. .getProviders()
  542. .map(function (provider) { return provider.delete(); }))];
  543. case 1:
  544. _a.sent();
  545. app.isDeleted = true;
  546. _a.label = 2;
  547. case 2: return [2 /*return*/];
  548. }
  549. });
  550. });
  551. }
  552. /**
  553. * Registers a library's name and version for platform logging purposes.
  554. * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
  555. * @param version - Current version of that library.
  556. * @param variant - Bundle variant, e.g., node, rn, etc.
  557. *
  558. * @public
  559. */
  560. function registerVersion(libraryKeyOrName, version, variant) {
  561. var _a;
  562. // TODO: We can use this check to whitelist strings when/if we set up
  563. // a good whitelist system.
  564. var library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;
  565. if (variant) {
  566. library += "-".concat(variant);
  567. }
  568. var libraryMismatch = library.match(/\s|\//);
  569. var versionMismatch = version.match(/\s|\//);
  570. if (libraryMismatch || versionMismatch) {
  571. var warning = [
  572. "Unable to register library \"".concat(library, "\" with version \"").concat(version, "\":")
  573. ];
  574. if (libraryMismatch) {
  575. warning.push("library name \"".concat(library, "\" contains illegal characters (whitespace or \"/\")"));
  576. }
  577. if (libraryMismatch && versionMismatch) {
  578. warning.push('and');
  579. }
  580. if (versionMismatch) {
  581. warning.push("version name \"".concat(version, "\" contains illegal characters (whitespace or \"/\")"));
  582. }
  583. logger.warn(warning.join(' '));
  584. return;
  585. }
  586. _registerComponent(new component.Component("".concat(library, "-version"), function () { return ({ library: library, version: version }); }, "VERSION" /* ComponentType.VERSION */));
  587. }
  588. /**
  589. * Sets log handler for all Firebase SDKs.
  590. * @param logCallback - An optional custom log handler that executes user code whenever
  591. * the Firebase SDK makes a logging call.
  592. *
  593. * @public
  594. */
  595. function onLog(logCallback, options) {
  596. if (logCallback !== null && typeof logCallback !== 'function') {
  597. throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */);
  598. }
  599. logger$1.setUserLogHandler(logCallback, options);
  600. }
  601. /**
  602. * Sets log level for all Firebase SDKs.
  603. *
  604. * All of the log types above the current log level are captured (i.e. if
  605. * you set the log level to `info`, errors are logged, but `debug` and
  606. * `verbose` logs are not).
  607. *
  608. * @public
  609. */
  610. function setLogLevel(logLevel) {
  611. logger$1.setLogLevel(logLevel);
  612. }
  613. /**
  614. * @license
  615. * Copyright 2021 Google LLC
  616. *
  617. * Licensed under the Apache License, Version 2.0 (the "License");
  618. * you may not use this file except in compliance with the License.
  619. * You may obtain a copy of the License at
  620. *
  621. * http://www.apache.org/licenses/LICENSE-2.0
  622. *
  623. * Unless required by applicable law or agreed to in writing, software
  624. * distributed under the License is distributed on an "AS IS" BASIS,
  625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  626. * See the License for the specific language governing permissions and
  627. * limitations under the License.
  628. */
  629. var DB_NAME = 'firebase-heartbeat-database';
  630. var DB_VERSION = 1;
  631. var STORE_NAME = 'firebase-heartbeat-store';
  632. var dbPromise = null;
  633. function getDbPromise() {
  634. if (!dbPromise) {
  635. dbPromise = idb.openDB(DB_NAME, DB_VERSION, {
  636. upgrade: function (db, oldVersion) {
  637. // We don't use 'break' in this switch statement, the fall-through
  638. // behavior is what we want, because if there are multiple versions between
  639. // the old version and the current version, we want ALL the migrations
  640. // that correspond to those versions to run, not only the last one.
  641. // eslint-disable-next-line default-case
  642. switch (oldVersion) {
  643. case 0:
  644. db.createObjectStore(STORE_NAME);
  645. }
  646. }
  647. }).catch(function (e) {
  648. throw ERROR_FACTORY.create("idb-open" /* AppError.IDB_OPEN */, {
  649. originalErrorMessage: e.message
  650. });
  651. });
  652. }
  653. return dbPromise;
  654. }
  655. function readHeartbeatsFromIndexedDB(app) {
  656. return tslib.__awaiter(this, void 0, void 0, function () {
  657. var db, result, e_1, idbGetError;
  658. return tslib.__generator(this, function (_a) {
  659. switch (_a.label) {
  660. case 0:
  661. _a.trys.push([0, 3, , 4]);
  662. return [4 /*yield*/, getDbPromise()];
  663. case 1:
  664. db = _a.sent();
  665. return [4 /*yield*/, db
  666. .transaction(STORE_NAME)
  667. .objectStore(STORE_NAME)
  668. .get(computeKey(app))];
  669. case 2:
  670. result = _a.sent();
  671. return [2 /*return*/, result];
  672. case 3:
  673. e_1 = _a.sent();
  674. if (e_1 instanceof util.FirebaseError) {
  675. logger.warn(e_1.message);
  676. }
  677. else {
  678. idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, {
  679. originalErrorMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  680. });
  681. logger.warn(idbGetError.message);
  682. }
  683. return [3 /*break*/, 4];
  684. case 4: return [2 /*return*/];
  685. }
  686. });
  687. });
  688. }
  689. function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
  690. return tslib.__awaiter(this, void 0, void 0, function () {
  691. var db, tx, objectStore, e_2, idbGetError;
  692. return tslib.__generator(this, function (_a) {
  693. switch (_a.label) {
  694. case 0:
  695. _a.trys.push([0, 4, , 5]);
  696. return [4 /*yield*/, getDbPromise()];
  697. case 1:
  698. db = _a.sent();
  699. tx = db.transaction(STORE_NAME, 'readwrite');
  700. objectStore = tx.objectStore(STORE_NAME);
  701. return [4 /*yield*/, objectStore.put(heartbeatObject, computeKey(app))];
  702. case 2:
  703. _a.sent();
  704. return [4 /*yield*/, tx.done];
  705. case 3:
  706. _a.sent();
  707. return [3 /*break*/, 5];
  708. case 4:
  709. e_2 = _a.sent();
  710. if (e_2 instanceof util.FirebaseError) {
  711. logger.warn(e_2.message);
  712. }
  713. else {
  714. idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, {
  715. originalErrorMessage: e_2 === null || e_2 === void 0 ? void 0 : e_2.message
  716. });
  717. logger.warn(idbGetError.message);
  718. }
  719. return [3 /*break*/, 5];
  720. case 5: return [2 /*return*/];
  721. }
  722. });
  723. });
  724. }
  725. function computeKey(app) {
  726. return "".concat(app.name, "!").concat(app.options.appId);
  727. }
  728. /**
  729. * @license
  730. * Copyright 2021 Google LLC
  731. *
  732. * Licensed under the Apache License, Version 2.0 (the "License");
  733. * you may not use this file except in compliance with the License.
  734. * You may obtain a copy of the License at
  735. *
  736. * http://www.apache.org/licenses/LICENSE-2.0
  737. *
  738. * Unless required by applicable law or agreed to in writing, software
  739. * distributed under the License is distributed on an "AS IS" BASIS,
  740. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  741. * See the License for the specific language governing permissions and
  742. * limitations under the License.
  743. */
  744. var MAX_HEADER_BYTES = 1024;
  745. // 30 days
  746. var STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;
  747. var HeartbeatServiceImpl = /** @class */ (function () {
  748. function HeartbeatServiceImpl(container) {
  749. var _this = this;
  750. this.container = container;
  751. /**
  752. * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
  753. * the header string.
  754. * Stores one record per date. This will be consolidated into the standard
  755. * format of one record per user agent string before being sent as a header.
  756. * Populated from indexedDB when the controller is instantiated and should
  757. * be kept in sync with indexedDB.
  758. * Leave public for easier testing.
  759. */
  760. this._heartbeatsCache = null;
  761. var app = this.container.getProvider('app').getImmediate();
  762. this._storage = new HeartbeatStorageImpl(app);
  763. this._heartbeatsCachePromise = this._storage.read().then(function (result) {
  764. _this._heartbeatsCache = result;
  765. return result;
  766. });
  767. }
  768. /**
  769. * Called to report a heartbeat. The function will generate
  770. * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
  771. * to IndexedDB.
  772. * Note that we only store one heartbeat per day. So if a heartbeat for today is
  773. * already logged, subsequent calls to this function in the same day will be ignored.
  774. */
  775. HeartbeatServiceImpl.prototype.triggerHeartbeat = function () {
  776. return tslib.__awaiter(this, void 0, void 0, function () {
  777. var platformLogger, agent, date, _a;
  778. return tslib.__generator(this, function (_b) {
  779. switch (_b.label) {
  780. case 0:
  781. platformLogger = this.container
  782. .getProvider('platform-logger')
  783. .getImmediate();
  784. agent = platformLogger.getPlatformInfoString();
  785. date = getUTCDateString();
  786. if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
  787. _a = this;
  788. return [4 /*yield*/, this._heartbeatsCachePromise];
  789. case 1:
  790. _a._heartbeatsCache = _b.sent();
  791. _b.label = 2;
  792. case 2:
  793. // Do not store a heartbeat if one is already stored for this day
  794. // or if a header has already been sent today.
  795. if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
  796. this._heartbeatsCache.heartbeats.some(function (singleDateHeartbeat) { return singleDateHeartbeat.date === date; })) {
  797. return [2 /*return*/];
  798. }
  799. else {
  800. // There is no entry for this date. Create one.
  801. this._heartbeatsCache.heartbeats.push({ date: date, agent: agent });
  802. }
  803. // Remove entries older than 30 days.
  804. this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(function (singleDateHeartbeat) {
  805. var hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
  806. var now = Date.now();
  807. return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
  808. });
  809. return [2 /*return*/, this._storage.overwrite(this._heartbeatsCache)];
  810. }
  811. });
  812. });
  813. };
  814. /**
  815. * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
  816. * It also clears all heartbeats from memory as well as in IndexedDB.
  817. *
  818. * NOTE: Consuming product SDKs should not send the header if this method
  819. * returns an empty string.
  820. */
  821. HeartbeatServiceImpl.prototype.getHeartbeatsHeader = function () {
  822. return tslib.__awaiter(this, void 0, void 0, function () {
  823. var date, _a, heartbeatsToSend, unsentEntries, headerString;
  824. return tslib.__generator(this, function (_b) {
  825. switch (_b.label) {
  826. case 0:
  827. if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
  828. return [4 /*yield*/, this._heartbeatsCachePromise];
  829. case 1:
  830. _b.sent();
  831. _b.label = 2;
  832. case 2:
  833. // If it's still null or the array is empty, there is no data to send.
  834. if (this._heartbeatsCache === null ||
  835. this._heartbeatsCache.heartbeats.length === 0) {
  836. return [2 /*return*/, ''];
  837. }
  838. date = getUTCDateString();
  839. _a = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats), heartbeatsToSend = _a.heartbeatsToSend, unsentEntries = _a.unsentEntries;
  840. headerString = util.base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
  841. // Store last sent date to prevent another being logged/sent for the same day.
  842. this._heartbeatsCache.lastSentHeartbeatDate = date;
  843. if (!(unsentEntries.length > 0)) return [3 /*break*/, 4];
  844. // Store any unsent entries if they exist.
  845. this._heartbeatsCache.heartbeats = unsentEntries;
  846. // This seems more likely than emptying the array (below) to lead to some odd state
  847. // since the cache isn't empty and this will be called again on the next request,
  848. // and is probably safest if we await it.
  849. return [4 /*yield*/, this._storage.overwrite(this._heartbeatsCache)];
  850. case 3:
  851. // This seems more likely than emptying the array (below) to lead to some odd state
  852. // since the cache isn't empty and this will be called again on the next request,
  853. // and is probably safest if we await it.
  854. _b.sent();
  855. return [3 /*break*/, 5];
  856. case 4:
  857. this._heartbeatsCache.heartbeats = [];
  858. // Do not wait for this, to reduce latency.
  859. void this._storage.overwrite(this._heartbeatsCache);
  860. _b.label = 5;
  861. case 5: return [2 /*return*/, headerString];
  862. }
  863. });
  864. });
  865. };
  866. return HeartbeatServiceImpl;
  867. }());
  868. function getUTCDateString() {
  869. var today = new Date();
  870. // Returns date format 'YYYY-MM-DD'
  871. return today.toISOString().substring(0, 10);
  872. }
  873. function extractHeartbeatsForHeader(heartbeatsCache, maxSize) {
  874. var e_1, _a;
  875. if (maxSize === void 0) { maxSize = MAX_HEADER_BYTES; }
  876. // Heartbeats grouped by user agent in the standard format to be sent in
  877. // the header.
  878. var heartbeatsToSend = [];
  879. // Single date format heartbeats that are not sent.
  880. var unsentEntries = heartbeatsCache.slice();
  881. var _loop_1 = function (singleDateHeartbeat) {
  882. // Look for an existing entry with the same user agent.
  883. var heartbeatEntry = heartbeatsToSend.find(function (hb) { return hb.agent === singleDateHeartbeat.agent; });
  884. if (!heartbeatEntry) {
  885. // If no entry for this user agent exists, create one.
  886. heartbeatsToSend.push({
  887. agent: singleDateHeartbeat.agent,
  888. dates: [singleDateHeartbeat.date]
  889. });
  890. if (countBytes(heartbeatsToSend) > maxSize) {
  891. // If the header would exceed max size, remove the added heartbeat
  892. // entry and stop adding to the header.
  893. heartbeatsToSend.pop();
  894. return "break";
  895. }
  896. }
  897. else {
  898. heartbeatEntry.dates.push(singleDateHeartbeat.date);
  899. // If the header would exceed max size, remove the added date
  900. // and stop adding to the header.
  901. if (countBytes(heartbeatsToSend) > maxSize) {
  902. heartbeatEntry.dates.pop();
  903. return "break";
  904. }
  905. }
  906. // Pop unsent entry from queue. (Skipped if adding the entry exceeded
  907. // quota and the loop breaks early.)
  908. unsentEntries = unsentEntries.slice(1);
  909. };
  910. try {
  911. for (var heartbeatsCache_1 = tslib.__values(heartbeatsCache), heartbeatsCache_1_1 = heartbeatsCache_1.next(); !heartbeatsCache_1_1.done; heartbeatsCache_1_1 = heartbeatsCache_1.next()) {
  912. var singleDateHeartbeat = heartbeatsCache_1_1.value;
  913. var state_1 = _loop_1(singleDateHeartbeat);
  914. if (state_1 === "break")
  915. break;
  916. }
  917. }
  918. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  919. finally {
  920. try {
  921. if (heartbeatsCache_1_1 && !heartbeatsCache_1_1.done && (_a = heartbeatsCache_1.return)) _a.call(heartbeatsCache_1);
  922. }
  923. finally { if (e_1) throw e_1.error; }
  924. }
  925. return {
  926. heartbeatsToSend: heartbeatsToSend,
  927. unsentEntries: unsentEntries
  928. };
  929. }
  930. var HeartbeatStorageImpl = /** @class */ (function () {
  931. function HeartbeatStorageImpl(app) {
  932. this.app = app;
  933. this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
  934. }
  935. HeartbeatStorageImpl.prototype.runIndexedDBEnvironmentCheck = function () {
  936. return tslib.__awaiter(this, void 0, void 0, function () {
  937. return tslib.__generator(this, function (_a) {
  938. if (!util.isIndexedDBAvailable()) {
  939. return [2 /*return*/, false];
  940. }
  941. else {
  942. return [2 /*return*/, util.validateIndexedDBOpenable()
  943. .then(function () { return true; })
  944. .catch(function () { return false; })];
  945. }
  946. });
  947. });
  948. };
  949. /**
  950. * Read all heartbeats.
  951. */
  952. HeartbeatStorageImpl.prototype.read = function () {
  953. return tslib.__awaiter(this, void 0, void 0, function () {
  954. var canUseIndexedDB, idbHeartbeatObject;
  955. return tslib.__generator(this, function (_a) {
  956. switch (_a.label) {
  957. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  958. case 1:
  959. canUseIndexedDB = _a.sent();
  960. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  961. return [2 /*return*/, { heartbeats: [] }];
  962. case 2: return [4 /*yield*/, readHeartbeatsFromIndexedDB(this.app)];
  963. case 3:
  964. idbHeartbeatObject = _a.sent();
  965. return [2 /*return*/, idbHeartbeatObject || { heartbeats: [] }];
  966. }
  967. });
  968. });
  969. };
  970. // overwrite the storage with the provided heartbeats
  971. HeartbeatStorageImpl.prototype.overwrite = function (heartbeatsObject) {
  972. var _a;
  973. return tslib.__awaiter(this, void 0, void 0, function () {
  974. var canUseIndexedDB, existingHeartbeatsObject;
  975. return tslib.__generator(this, function (_b) {
  976. switch (_b.label) {
  977. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  978. case 1:
  979. canUseIndexedDB = _b.sent();
  980. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  981. return [2 /*return*/];
  982. case 2: return [4 /*yield*/, this.read()];
  983. case 3:
  984. existingHeartbeatsObject = _b.sent();
  985. return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
  986. lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
  987. heartbeats: heartbeatsObject.heartbeats
  988. })];
  989. }
  990. });
  991. });
  992. };
  993. // add heartbeats
  994. HeartbeatStorageImpl.prototype.add = function (heartbeatsObject) {
  995. var _a;
  996. return tslib.__awaiter(this, void 0, void 0, function () {
  997. var canUseIndexedDB, existingHeartbeatsObject;
  998. return tslib.__generator(this, function (_b) {
  999. switch (_b.label) {
  1000. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  1001. case 1:
  1002. canUseIndexedDB = _b.sent();
  1003. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  1004. return [2 /*return*/];
  1005. case 2: return [4 /*yield*/, this.read()];
  1006. case 3:
  1007. existingHeartbeatsObject = _b.sent();
  1008. return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
  1009. lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
  1010. heartbeats: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(existingHeartbeatsObject.heartbeats), false), tslib.__read(heartbeatsObject.heartbeats), false)
  1011. })];
  1012. }
  1013. });
  1014. });
  1015. };
  1016. return HeartbeatStorageImpl;
  1017. }());
  1018. /**
  1019. * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
  1020. * in a platform logging header JSON object, stringified, and converted
  1021. * to base 64.
  1022. */
  1023. function countBytes(heartbeatsCache) {
  1024. // base64 has a restricted set of characters, all of which should be 1 byte.
  1025. return util.base64urlEncodeWithoutPadding(
  1026. // heartbeatsCache wrapper properties
  1027. JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
  1028. }
  1029. /**
  1030. * @license
  1031. * Copyright 2019 Google LLC
  1032. *
  1033. * Licensed under the Apache License, Version 2.0 (the "License");
  1034. * you may not use this file except in compliance with the License.
  1035. * You may obtain a copy of the License at
  1036. *
  1037. * http://www.apache.org/licenses/LICENSE-2.0
  1038. *
  1039. * Unless required by applicable law or agreed to in writing, software
  1040. * distributed under the License is distributed on an "AS IS" BASIS,
  1041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1042. * See the License for the specific language governing permissions and
  1043. * limitations under the License.
  1044. */
  1045. function registerCoreComponents(variant) {
  1046. _registerComponent(new component.Component('platform-logger', function (container) { return new PlatformLoggerServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */));
  1047. _registerComponent(new component.Component('heartbeat', function (container) { return new HeartbeatServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */));
  1048. // Register `app` package.
  1049. registerVersion(name$o, version$1, variant);
  1050. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  1051. registerVersion(name$o, version$1, 'cjs5');
  1052. // Register platform SDK identifier (no version).
  1053. registerVersion('fire-js', '');
  1054. }
  1055. /**
  1056. * Firebase App
  1057. *
  1058. * @remarks This package coordinates the communication between the different Firebase components
  1059. * @packageDocumentation
  1060. */
  1061. registerCoreComponents('node');
  1062. Object.defineProperty(exports, 'FirebaseError', {
  1063. enumerable: true,
  1064. get: function () { return util.FirebaseError; }
  1065. });
  1066. exports.SDK_VERSION = SDK_VERSION;
  1067. exports._DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME;
  1068. exports._addComponent = _addComponent;
  1069. exports._addOrOverwriteComponent = _addOrOverwriteComponent;
  1070. exports._apps = _apps;
  1071. exports._clearComponents = _clearComponents;
  1072. exports._components = _components;
  1073. exports._getProvider = _getProvider;
  1074. exports._registerComponent = _registerComponent;
  1075. exports._removeServiceInstance = _removeServiceInstance;
  1076. exports.deleteApp = deleteApp;
  1077. exports.getApp = getApp;
  1078. exports.getApps = getApps;
  1079. exports.initializeApp = initializeApp;
  1080. exports.onLog = onLog;
  1081. exports.registerVersion = registerVersion;
  1082. exports.setLogLevel = setLogLevel;
  1083. //# sourceMappingURL=index.cjs.js.map