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.cjs.js 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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.1";
  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.16.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 Firebase App.initializeApp()',
  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) {
  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, e_1, idbGetError;
  658. return tslib.__generator(this, function (_a) {
  659. switch (_a.label) {
  660. case 0:
  661. _a.trys.push([0, 2, , 3]);
  662. return [4 /*yield*/, getDbPromise()];
  663. case 1:
  664. db = _a.sent();
  665. return [2 /*return*/, db
  666. .transaction(STORE_NAME)
  667. .objectStore(STORE_NAME)
  668. .get(computeKey(app))];
  669. case 2:
  670. e_1 = _a.sent();
  671. if (e_1 instanceof util.FirebaseError) {
  672. logger.warn(e_1.message);
  673. }
  674. else {
  675. idbGetError = ERROR_FACTORY.create("idb-get" /* AppError.IDB_GET */, {
  676. originalErrorMessage: e_1 === null || e_1 === void 0 ? void 0 : e_1.message
  677. });
  678. logger.warn(idbGetError.message);
  679. }
  680. return [3 /*break*/, 3];
  681. case 3: return [2 /*return*/];
  682. }
  683. });
  684. });
  685. }
  686. function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
  687. return tslib.__awaiter(this, void 0, void 0, function () {
  688. var db, tx, objectStore, e_2, idbGetError;
  689. return tslib.__generator(this, function (_a) {
  690. switch (_a.label) {
  691. case 0:
  692. _a.trys.push([0, 3, , 4]);
  693. return [4 /*yield*/, getDbPromise()];
  694. case 1:
  695. db = _a.sent();
  696. tx = db.transaction(STORE_NAME, 'readwrite');
  697. objectStore = tx.objectStore(STORE_NAME);
  698. return [4 /*yield*/, objectStore.put(heartbeatObject, computeKey(app))];
  699. case 2:
  700. _a.sent();
  701. return [2 /*return*/, tx.done];
  702. case 3:
  703. e_2 = _a.sent();
  704. if (e_2 instanceof util.FirebaseError) {
  705. logger.warn(e_2.message);
  706. }
  707. else {
  708. idbGetError = ERROR_FACTORY.create("idb-set" /* AppError.IDB_WRITE */, {
  709. originalErrorMessage: e_2 === null || e_2 === void 0 ? void 0 : e_2.message
  710. });
  711. logger.warn(idbGetError.message);
  712. }
  713. return [3 /*break*/, 4];
  714. case 4: return [2 /*return*/];
  715. }
  716. });
  717. });
  718. }
  719. function computeKey(app) {
  720. return "".concat(app.name, "!").concat(app.options.appId);
  721. }
  722. /**
  723. * @license
  724. * Copyright 2021 Google LLC
  725. *
  726. * Licensed under the Apache License, Version 2.0 (the "License");
  727. * you may not use this file except in compliance with the License.
  728. * You may obtain a copy of the License at
  729. *
  730. * http://www.apache.org/licenses/LICENSE-2.0
  731. *
  732. * Unless required by applicable law or agreed to in writing, software
  733. * distributed under the License is distributed on an "AS IS" BASIS,
  734. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  735. * See the License for the specific language governing permissions and
  736. * limitations under the License.
  737. */
  738. var MAX_HEADER_BYTES = 1024;
  739. // 30 days
  740. var STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;
  741. var HeartbeatServiceImpl = /** @class */ (function () {
  742. function HeartbeatServiceImpl(container) {
  743. var _this = this;
  744. this.container = container;
  745. /**
  746. * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
  747. * the header string.
  748. * Stores one record per date. This will be consolidated into the standard
  749. * format of one record per user agent string before being sent as a header.
  750. * Populated from indexedDB when the controller is instantiated and should
  751. * be kept in sync with indexedDB.
  752. * Leave public for easier testing.
  753. */
  754. this._heartbeatsCache = null;
  755. var app = this.container.getProvider('app').getImmediate();
  756. this._storage = new HeartbeatStorageImpl(app);
  757. this._heartbeatsCachePromise = this._storage.read().then(function (result) {
  758. _this._heartbeatsCache = result;
  759. return result;
  760. });
  761. }
  762. /**
  763. * Called to report a heartbeat. The function will generate
  764. * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
  765. * to IndexedDB.
  766. * Note that we only store one heartbeat per day. So if a heartbeat for today is
  767. * already logged, subsequent calls to this function in the same day will be ignored.
  768. */
  769. HeartbeatServiceImpl.prototype.triggerHeartbeat = function () {
  770. return tslib.__awaiter(this, void 0, void 0, function () {
  771. var platformLogger, agent, date, _a;
  772. return tslib.__generator(this, function (_b) {
  773. switch (_b.label) {
  774. case 0:
  775. platformLogger = this.container
  776. .getProvider('platform-logger')
  777. .getImmediate();
  778. agent = platformLogger.getPlatformInfoString();
  779. date = getUTCDateString();
  780. if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
  781. _a = this;
  782. return [4 /*yield*/, this._heartbeatsCachePromise];
  783. case 1:
  784. _a._heartbeatsCache = _b.sent();
  785. _b.label = 2;
  786. case 2:
  787. // Do not store a heartbeat if one is already stored for this day
  788. // or if a header has already been sent today.
  789. if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
  790. this._heartbeatsCache.heartbeats.some(function (singleDateHeartbeat) { return singleDateHeartbeat.date === date; })) {
  791. return [2 /*return*/];
  792. }
  793. else {
  794. // There is no entry for this date. Create one.
  795. this._heartbeatsCache.heartbeats.push({ date: date, agent: agent });
  796. }
  797. // Remove entries older than 30 days.
  798. this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(function (singleDateHeartbeat) {
  799. var hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
  800. var now = Date.now();
  801. return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
  802. });
  803. return [2 /*return*/, this._storage.overwrite(this._heartbeatsCache)];
  804. }
  805. });
  806. });
  807. };
  808. /**
  809. * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
  810. * It also clears all heartbeats from memory as well as in IndexedDB.
  811. *
  812. * NOTE: Consuming product SDKs should not send the header if this method
  813. * returns an empty string.
  814. */
  815. HeartbeatServiceImpl.prototype.getHeartbeatsHeader = function () {
  816. return tslib.__awaiter(this, void 0, void 0, function () {
  817. var date, _a, heartbeatsToSend, unsentEntries, headerString;
  818. return tslib.__generator(this, function (_b) {
  819. switch (_b.label) {
  820. case 0:
  821. if (!(this._heartbeatsCache === null)) return [3 /*break*/, 2];
  822. return [4 /*yield*/, this._heartbeatsCachePromise];
  823. case 1:
  824. _b.sent();
  825. _b.label = 2;
  826. case 2:
  827. // If it's still null or the array is empty, there is no data to send.
  828. if (this._heartbeatsCache === null ||
  829. this._heartbeatsCache.heartbeats.length === 0) {
  830. return [2 /*return*/, ''];
  831. }
  832. date = getUTCDateString();
  833. _a = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats), heartbeatsToSend = _a.heartbeatsToSend, unsentEntries = _a.unsentEntries;
  834. headerString = util.base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
  835. // Store last sent date to prevent another being logged/sent for the same day.
  836. this._heartbeatsCache.lastSentHeartbeatDate = date;
  837. if (!(unsentEntries.length > 0)) return [3 /*break*/, 4];
  838. // Store any unsent entries if they exist.
  839. this._heartbeatsCache.heartbeats = unsentEntries;
  840. // This seems more likely than emptying the array (below) to lead to some odd state
  841. // since the cache isn't empty and this will be called again on the next request,
  842. // and is probably safest if we await it.
  843. return [4 /*yield*/, this._storage.overwrite(this._heartbeatsCache)];
  844. case 3:
  845. // This seems more likely than emptying the array (below) to lead to some odd state
  846. // since the cache isn't empty and this will be called again on the next request,
  847. // and is probably safest if we await it.
  848. _b.sent();
  849. return [3 /*break*/, 5];
  850. case 4:
  851. this._heartbeatsCache.heartbeats = [];
  852. // Do not wait for this, to reduce latency.
  853. void this._storage.overwrite(this._heartbeatsCache);
  854. _b.label = 5;
  855. case 5: return [2 /*return*/, headerString];
  856. }
  857. });
  858. });
  859. };
  860. return HeartbeatServiceImpl;
  861. }());
  862. function getUTCDateString() {
  863. var today = new Date();
  864. // Returns date format 'YYYY-MM-DD'
  865. return today.toISOString().substring(0, 10);
  866. }
  867. function extractHeartbeatsForHeader(heartbeatsCache, maxSize) {
  868. var e_1, _a;
  869. if (maxSize === void 0) { maxSize = MAX_HEADER_BYTES; }
  870. // Heartbeats grouped by user agent in the standard format to be sent in
  871. // the header.
  872. var heartbeatsToSend = [];
  873. // Single date format heartbeats that are not sent.
  874. var unsentEntries = heartbeatsCache.slice();
  875. var _loop_1 = function (singleDateHeartbeat) {
  876. // Look for an existing entry with the same user agent.
  877. var heartbeatEntry = heartbeatsToSend.find(function (hb) { return hb.agent === singleDateHeartbeat.agent; });
  878. if (!heartbeatEntry) {
  879. // If no entry for this user agent exists, create one.
  880. heartbeatsToSend.push({
  881. agent: singleDateHeartbeat.agent,
  882. dates: [singleDateHeartbeat.date]
  883. });
  884. if (countBytes(heartbeatsToSend) > maxSize) {
  885. // If the header would exceed max size, remove the added heartbeat
  886. // entry and stop adding to the header.
  887. heartbeatsToSend.pop();
  888. return "break";
  889. }
  890. }
  891. else {
  892. heartbeatEntry.dates.push(singleDateHeartbeat.date);
  893. // If the header would exceed max size, remove the added date
  894. // and stop adding to the header.
  895. if (countBytes(heartbeatsToSend) > maxSize) {
  896. heartbeatEntry.dates.pop();
  897. return "break";
  898. }
  899. }
  900. // Pop unsent entry from queue. (Skipped if adding the entry exceeded
  901. // quota and the loop breaks early.)
  902. unsentEntries = unsentEntries.slice(1);
  903. };
  904. try {
  905. for (var heartbeatsCache_1 = tslib.__values(heartbeatsCache), heartbeatsCache_1_1 = heartbeatsCache_1.next(); !heartbeatsCache_1_1.done; heartbeatsCache_1_1 = heartbeatsCache_1.next()) {
  906. var singleDateHeartbeat = heartbeatsCache_1_1.value;
  907. var state_1 = _loop_1(singleDateHeartbeat);
  908. if (state_1 === "break")
  909. break;
  910. }
  911. }
  912. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  913. finally {
  914. try {
  915. if (heartbeatsCache_1_1 && !heartbeatsCache_1_1.done && (_a = heartbeatsCache_1.return)) _a.call(heartbeatsCache_1);
  916. }
  917. finally { if (e_1) throw e_1.error; }
  918. }
  919. return {
  920. heartbeatsToSend: heartbeatsToSend,
  921. unsentEntries: unsentEntries
  922. };
  923. }
  924. var HeartbeatStorageImpl = /** @class */ (function () {
  925. function HeartbeatStorageImpl(app) {
  926. this.app = app;
  927. this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
  928. }
  929. HeartbeatStorageImpl.prototype.runIndexedDBEnvironmentCheck = function () {
  930. return tslib.__awaiter(this, void 0, void 0, function () {
  931. return tslib.__generator(this, function (_a) {
  932. if (!util.isIndexedDBAvailable()) {
  933. return [2 /*return*/, false];
  934. }
  935. else {
  936. return [2 /*return*/, util.validateIndexedDBOpenable()
  937. .then(function () { return true; })
  938. .catch(function () { return false; })];
  939. }
  940. });
  941. });
  942. };
  943. /**
  944. * Read all heartbeats.
  945. */
  946. HeartbeatStorageImpl.prototype.read = function () {
  947. return tslib.__awaiter(this, void 0, void 0, function () {
  948. var canUseIndexedDB, idbHeartbeatObject;
  949. return tslib.__generator(this, function (_a) {
  950. switch (_a.label) {
  951. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  952. case 1:
  953. canUseIndexedDB = _a.sent();
  954. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  955. return [2 /*return*/, { heartbeats: [] }];
  956. case 2: return [4 /*yield*/, readHeartbeatsFromIndexedDB(this.app)];
  957. case 3:
  958. idbHeartbeatObject = _a.sent();
  959. return [2 /*return*/, idbHeartbeatObject || { heartbeats: [] }];
  960. }
  961. });
  962. });
  963. };
  964. // overwrite the storage with the provided heartbeats
  965. HeartbeatStorageImpl.prototype.overwrite = function (heartbeatsObject) {
  966. var _a;
  967. return tslib.__awaiter(this, void 0, void 0, function () {
  968. var canUseIndexedDB, existingHeartbeatsObject;
  969. return tslib.__generator(this, function (_b) {
  970. switch (_b.label) {
  971. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  972. case 1:
  973. canUseIndexedDB = _b.sent();
  974. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  975. return [2 /*return*/];
  976. case 2: return [4 /*yield*/, this.read()];
  977. case 3:
  978. existingHeartbeatsObject = _b.sent();
  979. return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
  980. lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
  981. heartbeats: heartbeatsObject.heartbeats
  982. })];
  983. }
  984. });
  985. });
  986. };
  987. // add heartbeats
  988. HeartbeatStorageImpl.prototype.add = function (heartbeatsObject) {
  989. var _a;
  990. return tslib.__awaiter(this, void 0, void 0, function () {
  991. var canUseIndexedDB, existingHeartbeatsObject;
  992. return tslib.__generator(this, function (_b) {
  993. switch (_b.label) {
  994. case 0: return [4 /*yield*/, this._canUseIndexedDBPromise];
  995. case 1:
  996. canUseIndexedDB = _b.sent();
  997. if (!!canUseIndexedDB) return [3 /*break*/, 2];
  998. return [2 /*return*/];
  999. case 2: return [4 /*yield*/, this.read()];
  1000. case 3:
  1001. existingHeartbeatsObject = _b.sent();
  1002. return [2 /*return*/, writeHeartbeatsToIndexedDB(this.app, {
  1003. lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
  1004. heartbeats: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(existingHeartbeatsObject.heartbeats), false), tslib.__read(heartbeatsObject.heartbeats), false)
  1005. })];
  1006. }
  1007. });
  1008. });
  1009. };
  1010. return HeartbeatStorageImpl;
  1011. }());
  1012. /**
  1013. * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
  1014. * in a platform logging header JSON object, stringified, and converted
  1015. * to base 64.
  1016. */
  1017. function countBytes(heartbeatsCache) {
  1018. // base64 has a restricted set of characters, all of which should be 1 byte.
  1019. return util.base64urlEncodeWithoutPadding(
  1020. // heartbeatsCache wrapper properties
  1021. JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
  1022. }
  1023. /**
  1024. * @license
  1025. * Copyright 2019 Google LLC
  1026. *
  1027. * Licensed under the Apache License, Version 2.0 (the "License");
  1028. * you may not use this file except in compliance with the License.
  1029. * You may obtain a copy of the License at
  1030. *
  1031. * http://www.apache.org/licenses/LICENSE-2.0
  1032. *
  1033. * Unless required by applicable law or agreed to in writing, software
  1034. * distributed under the License is distributed on an "AS IS" BASIS,
  1035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1036. * See the License for the specific language governing permissions and
  1037. * limitations under the License.
  1038. */
  1039. function registerCoreComponents(variant) {
  1040. _registerComponent(new component.Component('platform-logger', function (container) { return new PlatformLoggerServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */));
  1041. _registerComponent(new component.Component('heartbeat', function (container) { return new HeartbeatServiceImpl(container); }, "PRIVATE" /* ComponentType.PRIVATE */));
  1042. // Register `app` package.
  1043. registerVersion(name$o, version$1, variant);
  1044. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  1045. registerVersion(name$o, version$1, 'cjs5');
  1046. // Register platform SDK identifier (no version).
  1047. registerVersion('fire-js', '');
  1048. }
  1049. /**
  1050. * Firebase App
  1051. *
  1052. * @remarks This package coordinates the communication between the different Firebase components
  1053. * @packageDocumentation
  1054. */
  1055. registerCoreComponents('node');
  1056. Object.defineProperty(exports, 'FirebaseError', {
  1057. enumerable: true,
  1058. get: function () { return util.FirebaseError; }
  1059. });
  1060. exports.SDK_VERSION = SDK_VERSION;
  1061. exports._DEFAULT_ENTRY_NAME = DEFAULT_ENTRY_NAME;
  1062. exports._addComponent = _addComponent;
  1063. exports._addOrOverwriteComponent = _addOrOverwriteComponent;
  1064. exports._apps = _apps;
  1065. exports._clearComponents = _clearComponents;
  1066. exports._components = _components;
  1067. exports._getProvider = _getProvider;
  1068. exports._registerComponent = _registerComponent;
  1069. exports._removeServiceInstance = _removeServiceInstance;
  1070. exports.deleteApp = deleteApp;
  1071. exports.getApp = getApp;
  1072. exports.getApps = getApps;
  1073. exports.initializeApp = initializeApp;
  1074. exports.onLog = onLog;
  1075. exports.registerVersion = registerVersion;
  1076. exports.setLogLevel = setLogLevel;
  1077. //# sourceMappingURL=index.cjs.js.map