datastake-daf 0.6.584 → 0.6.586

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,8 @@ var lodash = require('lodash');
11
11
  var PropTypes = require('prop-types');
12
12
  var reactIs = require('react-is');
13
13
  require('react-dom');
14
+ var app = require('firebase/app');
15
+ var messaging = require('firebase/messaging');
14
16
 
15
17
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
18
 
@@ -820,7 +822,6 @@ const mapTheme = (theme = {}) => ({
820
822
  '--custom-sidenav-subsection-hover': theme.customSidenavSubsectionHover,
821
823
  '--custom-collapsed-sidenav-hover-color': theme.customCollapsedSidenavHoverColor,
822
824
  '--custom-sidenav-disabled-menu-item-color': theme.customSidenavDisabledMenuItemColor,
823
- '--custom-sidenav-text-color': theme.customSidenavTextColor,
824
825
  '--nested-sidenav-color': theme.nestedSidenavColor,
825
826
  '--nested-sidenav-submenu-color': theme.nestedSidenavSubMenuColor,
826
827
  '--nested-sidenav-hover-color': theme.nestedSidenavHoverColor,
@@ -1422,7 +1423,7 @@ var platform = 'browser';
1422
1423
  var browser = true;
1423
1424
  var env = {};
1424
1425
  var argv = [];
1425
- var version$3 = ''; // empty string to avoid regexp issues
1426
+ var version = ''; // empty string to avoid regexp issues
1426
1427
  var versions = {};
1427
1428
  var release = {};
1428
1429
  var config = {};
@@ -1486,7 +1487,7 @@ var browser$1 = {
1486
1487
  browser: browser,
1487
1488
  env: env,
1488
1489
  argv: argv,
1489
- version: version$3,
1490
+ version: version,
1490
1491
  versions: versions,
1491
1492
  on: on,
1492
1493
  addListener: addListener,
@@ -1577,4662 +1578,21 @@ const usePermissions = ({
1577
1578
  return value;
1578
1579
  };
1579
1580
 
1580
- const getDefaultsFromPostinstall = () => (undefined);
1581
-
1582
- /**
1583
- * @license
1584
- * Copyright 2017 Google LLC
1585
- *
1586
- * Licensed under the Apache License, Version 2.0 (the "License");
1587
- * you may not use this file except in compliance with the License.
1588
- * You may obtain a copy of the License at
1589
- *
1590
- * http://www.apache.org/licenses/LICENSE-2.0
1591
- *
1592
- * Unless required by applicable law or agreed to in writing, software
1593
- * distributed under the License is distributed on an "AS IS" BASIS,
1594
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1595
- * See the License for the specific language governing permissions and
1596
- * limitations under the License.
1597
- */
1598
- const stringToByteArray$1 = function (str) {
1599
- // TODO(user): Use native implementations if/when available
1600
- const out = [];
1601
- let p = 0;
1602
- for (let i = 0; i < str.length; i++) {
1603
- let c = str.charCodeAt(i);
1604
- if (c < 128) {
1605
- out[p++] = c;
1606
- }
1607
- else if (c < 2048) {
1608
- out[p++] = (c >> 6) | 192;
1609
- out[p++] = (c & 63) | 128;
1610
- }
1611
- else if ((c & 0xfc00) === 0xd800 &&
1612
- i + 1 < str.length &&
1613
- (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
1614
- // Surrogate Pair
1615
- c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
1616
- out[p++] = (c >> 18) | 240;
1617
- out[p++] = ((c >> 12) & 63) | 128;
1618
- out[p++] = ((c >> 6) & 63) | 128;
1619
- out[p++] = (c & 63) | 128;
1620
- }
1621
- else {
1622
- out[p++] = (c >> 12) | 224;
1623
- out[p++] = ((c >> 6) & 63) | 128;
1624
- out[p++] = (c & 63) | 128;
1625
- }
1626
- }
1627
- return out;
1628
- };
1629
- /**
1630
- * Turns an array of numbers into the string given by the concatenation of the
1631
- * characters to which the numbers correspond.
1632
- * @param bytes Array of numbers representing characters.
1633
- * @return Stringification of the array.
1634
- */
1635
- const byteArrayToString = function (bytes) {
1636
- // TODO(user): Use native implementations if/when available
1637
- const out = [];
1638
- let pos = 0, c = 0;
1639
- while (pos < bytes.length) {
1640
- const c1 = bytes[pos++];
1641
- if (c1 < 128) {
1642
- out[c++] = String.fromCharCode(c1);
1643
- }
1644
- else if (c1 > 191 && c1 < 224) {
1645
- const c2 = bytes[pos++];
1646
- out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
1647
- }
1648
- else if (c1 > 239 && c1 < 365) {
1649
- // Surrogate Pair
1650
- const c2 = bytes[pos++];
1651
- const c3 = bytes[pos++];
1652
- const c4 = bytes[pos++];
1653
- const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
1654
- 0x10000;
1655
- out[c++] = String.fromCharCode(0xd800 + (u >> 10));
1656
- out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
1657
- }
1658
- else {
1659
- const c2 = bytes[pos++];
1660
- const c3 = bytes[pos++];
1661
- out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
1662
- }
1663
- }
1664
- return out.join('');
1665
- };
1666
- // We define it as an object literal instead of a class because a class compiled down to es5 can't
1667
- // be treeshaked. https://github.com/rollup/rollup/issues/1691
1668
- // Static lookup maps, lazily populated by init_()
1669
- // TODO(dlarocque): Define this as a class, since we no longer target ES5.
1670
- const base64 = {
1671
- /**
1672
- * Maps bytes to characters.
1673
- */
1674
- byteToCharMap_: null,
1675
- /**
1676
- * Maps characters to bytes.
1677
- */
1678
- charToByteMap_: null,
1679
- /**
1680
- * Maps bytes to websafe characters.
1681
- * @private
1682
- */
1683
- byteToCharMapWebSafe_: null,
1684
- /**
1685
- * Maps websafe characters to bytes.
1686
- * @private
1687
- */
1688
- charToByteMapWebSafe_: null,
1689
- /**
1690
- * Our default alphabet, shared between
1691
- * ENCODED_VALS and ENCODED_VALS_WEBSAFE
1692
- */
1693
- ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
1694
- /**
1695
- * Our default alphabet. Value 64 (=) is special; it means "nothing."
1696
- */
1697
- get ENCODED_VALS() {
1698
- return this.ENCODED_VALS_BASE + '+/=';
1699
- },
1700
- /**
1701
- * Our websafe alphabet.
1702
- */
1703
- get ENCODED_VALS_WEBSAFE() {
1704
- return this.ENCODED_VALS_BASE + '-_.';
1705
- },
1706
- /**
1707
- * Whether this browser supports the atob and btoa functions. This extension
1708
- * started at Mozilla but is now implemented by many browsers. We use the
1709
- * ASSUME_* variables to avoid pulling in the full useragent detection library
1710
- * but still allowing the standard per-browser compilations.
1711
- *
1712
- */
1713
- HAS_NATIVE_SUPPORT: typeof atob === 'function',
1714
- /**
1715
- * Base64-encode an array of bytes.
1716
- *
1717
- * @param input An array of bytes (numbers with
1718
- * value in [0, 255]) to encode.
1719
- * @param webSafe Boolean indicating we should use the
1720
- * alternative alphabet.
1721
- * @return The base64 encoded string.
1722
- */
1723
- encodeByteArray(input, webSafe) {
1724
- if (!Array.isArray(input)) {
1725
- throw Error('encodeByteArray takes an array as a parameter');
1726
- }
1727
- this.init_();
1728
- const byteToCharMap = webSafe
1729
- ? this.byteToCharMapWebSafe_
1730
- : this.byteToCharMap_;
1731
- const output = [];
1732
- for (let i = 0; i < input.length; i += 3) {
1733
- const byte1 = input[i];
1734
- const haveByte2 = i + 1 < input.length;
1735
- const byte2 = haveByte2 ? input[i + 1] : 0;
1736
- const haveByte3 = i + 2 < input.length;
1737
- const byte3 = haveByte3 ? input[i + 2] : 0;
1738
- const outByte1 = byte1 >> 2;
1739
- const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
1740
- let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
1741
- let outByte4 = byte3 & 0x3f;
1742
- if (!haveByte3) {
1743
- outByte4 = 64;
1744
- if (!haveByte2) {
1745
- outByte3 = 64;
1746
- }
1747
- }
1748
- output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
1749
- }
1750
- return output.join('');
1751
- },
1752
- /**
1753
- * Base64-encode a string.
1754
- *
1755
- * @param input A string to encode.
1756
- * @param webSafe If true, we should use the
1757
- * alternative alphabet.
1758
- * @return The base64 encoded string.
1759
- */
1760
- encodeString(input, webSafe) {
1761
- // Shortcut for Mozilla browsers that implement
1762
- // a native base64 encoder in the form of "btoa/atob"
1763
- if (this.HAS_NATIVE_SUPPORT && !webSafe) {
1764
- return btoa(input);
1765
- }
1766
- return this.encodeByteArray(stringToByteArray$1(input), webSafe);
1767
- },
1768
- /**
1769
- * Base64-decode a string.
1770
- *
1771
- * @param input to decode.
1772
- * @param webSafe True if we should use the
1773
- * alternative alphabet.
1774
- * @return string representing the decoded value.
1775
- */
1776
- decodeString(input, webSafe) {
1777
- // Shortcut for Mozilla browsers that implement
1778
- // a native base64 encoder in the form of "btoa/atob"
1779
- if (this.HAS_NATIVE_SUPPORT && !webSafe) {
1780
- return atob(input);
1781
- }
1782
- return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
1783
- },
1784
- /**
1785
- * Base64-decode a string.
1786
- *
1787
- * In base-64 decoding, groups of four characters are converted into three
1788
- * bytes. If the encoder did not apply padding, the input length may not
1789
- * be a multiple of 4.
1790
- *
1791
- * In this case, the last group will have fewer than 4 characters, and
1792
- * padding will be inferred. If the group has one or two characters, it decodes
1793
- * to one byte. If the group has three characters, it decodes to two bytes.
1794
- *
1795
- * @param input Input to decode.
1796
- * @param webSafe True if we should use the web-safe alphabet.
1797
- * @return bytes representing the decoded value.
1798
- */
1799
- decodeStringToByteArray(input, webSafe) {
1800
- this.init_();
1801
- const charToByteMap = webSafe
1802
- ? this.charToByteMapWebSafe_
1803
- : this.charToByteMap_;
1804
- const output = [];
1805
- for (let i = 0; i < input.length;) {
1806
- const byte1 = charToByteMap[input.charAt(i++)];
1807
- const haveByte2 = i < input.length;
1808
- const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
1809
- ++i;
1810
- const haveByte3 = i < input.length;
1811
- const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
1812
- ++i;
1813
- const haveByte4 = i < input.length;
1814
- const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
1815
- ++i;
1816
- if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
1817
- throw new DecodeBase64StringError();
1818
- }
1819
- const outByte1 = (byte1 << 2) | (byte2 >> 4);
1820
- output.push(outByte1);
1821
- if (byte3 !== 64) {
1822
- const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
1823
- output.push(outByte2);
1824
- if (byte4 !== 64) {
1825
- const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
1826
- output.push(outByte3);
1827
- }
1828
- }
1829
- }
1830
- return output;
1831
- },
1832
- /**
1833
- * Lazy static initialization function. Called before
1834
- * accessing any of the static map variables.
1835
- * @private
1836
- */
1837
- init_() {
1838
- if (!this.byteToCharMap_) {
1839
- this.byteToCharMap_ = {};
1840
- this.charToByteMap_ = {};
1841
- this.byteToCharMapWebSafe_ = {};
1842
- this.charToByteMapWebSafe_ = {};
1843
- // We want quick mappings back and forth, so we precompute two maps.
1844
- for (let i = 0; i < this.ENCODED_VALS.length; i++) {
1845
- this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
1846
- this.charToByteMap_[this.byteToCharMap_[i]] = i;
1847
- this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
1848
- this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
1849
- // Be forgiving when decoding and correctly decode both encodings.
1850
- if (i >= this.ENCODED_VALS_BASE.length) {
1851
- this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
1852
- this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
1853
- }
1854
- }
1855
- }
1856
- }
1857
- };
1858
- /**
1859
- * An error encountered while decoding base64 string.
1860
- */
1861
- class DecodeBase64StringError extends Error {
1862
- constructor() {
1863
- super(...arguments);
1864
- this.name = 'DecodeBase64StringError';
1865
- }
1866
- }
1867
- /**
1868
- * URL-safe base64 encoding
1869
- */
1870
- const base64Encode = function (str) {
1871
- const utf8Bytes = stringToByteArray$1(str);
1872
- return base64.encodeByteArray(utf8Bytes, true);
1873
- };
1874
- /**
1875
- * URL-safe base64 encoding (without "." padding in the end).
1876
- * e.g. Used in JSON Web Token (JWT) parts.
1877
- */
1878
- const base64urlEncodeWithoutPadding = function (str) {
1879
- // Use base64url encoding and remove padding in the end (dot characters).
1880
- return base64Encode(str).replace(/\./g, '');
1881
- };
1882
- /**
1883
- * URL-safe base64 decoding
1884
- *
1885
- * NOTE: DO NOT use the global atob() function - it does NOT support the
1886
- * base64Url variant encoding.
1887
- *
1888
- * @param str To be decoded
1889
- * @return Decoded result, if possible
1890
- */
1891
- const base64Decode = function (str) {
1892
- try {
1893
- return base64.decodeString(str, true);
1894
- }
1895
- catch (e) {
1896
- console.error('base64Decode failed: ', e);
1897
- }
1898
- return null;
1899
- };
1900
-
1901
- /**
1902
- * @license
1903
- * Copyright 2022 Google LLC
1904
- *
1905
- * Licensed under the Apache License, Version 2.0 (the "License");
1906
- * you may not use this file except in compliance with the License.
1907
- * You may obtain a copy of the License at
1908
- *
1909
- * http://www.apache.org/licenses/LICENSE-2.0
1910
- *
1911
- * Unless required by applicable law or agreed to in writing, software
1912
- * distributed under the License is distributed on an "AS IS" BASIS,
1913
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1914
- * See the License for the specific language governing permissions and
1915
- * limitations under the License.
1916
- */
1917
- /**
1918
- * Polyfill for `globalThis` object.
1919
- * @returns the `globalThis` object for the given environment.
1920
- * @public
1921
- */
1922
- function getGlobal() {
1923
- if (typeof self !== 'undefined') {
1924
- return self;
1925
- }
1926
- if (typeof window !== 'undefined') {
1927
- return window;
1928
- }
1929
- if (typeof global$1 !== 'undefined') {
1930
- return global$1;
1931
- }
1932
- throw new Error('Unable to locate global object.');
1933
- }
1934
-
1935
- /**
1936
- * @license
1937
- * Copyright 2022 Google LLC
1938
- *
1939
- * Licensed under the Apache License, Version 2.0 (the "License");
1940
- * you may not use this file except in compliance with the License.
1941
- * You may obtain a copy of the License at
1942
- *
1943
- * http://www.apache.org/licenses/LICENSE-2.0
1944
- *
1945
- * Unless required by applicable law or agreed to in writing, software
1946
- * distributed under the License is distributed on an "AS IS" BASIS,
1947
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1948
- * See the License for the specific language governing permissions and
1949
- * limitations under the License.
1950
- */
1951
- const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
1952
- /**
1953
- * Attempt to read defaults from a JSON string provided to
1954
- * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
1955
- * process(.)env(.)__FIREBASE_DEFAULTS_PATH__
1956
- * The dots are in parens because certain compilers (Vite?) cannot
1957
- * handle seeing that variable in comments.
1958
- * See https://github.com/firebase/firebase-js-sdk/issues/6838
1959
- */
1960
- const getDefaultsFromEnvVariable = () => {
1961
- if (typeof process === 'undefined' || typeof process.env === 'undefined') {
1962
- return;
1963
- }
1964
- const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
1965
- if (defaultsJsonString) {
1966
- return JSON.parse(defaultsJsonString);
1967
- }
1968
- };
1969
- const getDefaultsFromCookie = () => {
1970
- if (typeof document === 'undefined') {
1971
- return;
1972
- }
1973
- let match;
1974
- try {
1975
- match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
1976
- }
1977
- catch (e) {
1978
- // Some environments such as Angular Universal SSR have a
1979
- // `document` object but error on accessing `document.cookie`.
1980
- return;
1981
- }
1982
- const decoded = match && base64Decode(match[1]);
1983
- return decoded && JSON.parse(decoded);
1984
- };
1985
- /**
1986
- * Get the __FIREBASE_DEFAULTS__ object. It checks in order:
1987
- * (1) if such an object exists as a property of `globalThis`
1988
- * (2) if such an object was provided on a shell environment variable
1989
- * (3) if such an object exists in a cookie
1990
- * @public
1991
- */
1992
- const getDefaults = () => {
1993
- try {
1994
- return (getDefaultsFromPostinstall() ||
1995
- getDefaultsFromGlobal() ||
1996
- getDefaultsFromEnvVariable() ||
1997
- getDefaultsFromCookie());
1998
- }
1999
- catch (e) {
2000
- /**
2001
- * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
2002
- * to any environment case we have not accounted for. Log to
2003
- * info instead of swallowing so we can find these unknown cases
2004
- * and add paths for them if needed.
2005
- */
2006
- console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
2007
- return;
2008
- }
2009
- };
2010
- /**
2011
- * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
2012
- * @public
2013
- */
2014
- const getDefaultAppConfig = () => getDefaults()?.config;
2015
-
2016
- /**
2017
- * @license
2018
- * Copyright 2017 Google LLC
2019
- *
2020
- * Licensed under the Apache License, Version 2.0 (the "License");
2021
- * you may not use this file except in compliance with the License.
2022
- * You may obtain a copy of the License at
2023
- *
2024
- * http://www.apache.org/licenses/LICENSE-2.0
2025
- *
2026
- * Unless required by applicable law or agreed to in writing, software
2027
- * distributed under the License is distributed on an "AS IS" BASIS,
2028
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2029
- * See the License for the specific language governing permissions and
2030
- * limitations under the License.
2031
- */
2032
- class Deferred {
2033
- constructor() {
2034
- this.reject = () => { };
2035
- this.resolve = () => { };
2036
- this.promise = new Promise((resolve, reject) => {
2037
- this.resolve = resolve;
2038
- this.reject = reject;
2039
- });
2040
- }
2041
- /**
2042
- * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around
2043
- * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
2044
- * and returns a node-style callback which will resolve or reject the Deferred's promise.
2045
- */
2046
- wrapCallback(callback) {
2047
- return (error, value) => {
2048
- if (error) {
2049
- this.reject(error);
2050
- }
2051
- else {
2052
- this.resolve(value);
2053
- }
2054
- if (typeof callback === 'function') {
2055
- // Attaching noop handler just in case developer wasn't expecting
2056
- // promises
2057
- this.promise.catch(() => { });
2058
- // Some of our callbacks don't expect a value and our own tests
2059
- // assert that the parameter length is 1
2060
- if (callback.length === 1) {
2061
- callback(error);
2062
- }
2063
- else {
2064
- callback(error, value);
2065
- }
2066
- }
2067
- };
2068
- }
2069
- }
2070
- /**
2071
- * This method checks if indexedDB is supported by current browser/service worker context
2072
- * @return true if indexedDB is supported by current browser/service worker context
2073
- */
2074
- function isIndexedDBAvailable() {
2075
- try {
2076
- return typeof indexedDB === 'object';
2077
- }
2078
- catch (e) {
2079
- return false;
2080
- }
2081
- }
2082
- /**
2083
- * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
2084
- * if errors occur during the database open operation.
2085
- *
2086
- * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
2087
- * private browsing)
2088
- */
2089
- function validateIndexedDBOpenable() {
2090
- return new Promise((resolve, reject) => {
2091
- try {
2092
- let preExist = true;
2093
- const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
2094
- const request = self.indexedDB.open(DB_CHECK_NAME);
2095
- request.onsuccess = () => {
2096
- request.result.close();
2097
- // delete database only when it doesn't pre-exist
2098
- if (!preExist) {
2099
- self.indexedDB.deleteDatabase(DB_CHECK_NAME);
2100
- }
2101
- resolve(true);
2102
- };
2103
- request.onupgradeneeded = () => {
2104
- preExist = false;
2105
- };
2106
- request.onerror = () => {
2107
- reject(request.error?.message || '');
2108
- };
2109
- }
2110
- catch (error) {
2111
- reject(error);
2112
- }
2113
- });
2114
- }
2115
- /**
2116
- *
2117
- * This method checks whether cookie is enabled within current browser
2118
- * @return true if cookie is enabled within current browser
2119
- */
2120
- function areCookiesEnabled() {
2121
- if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
2122
- return false;
2123
- }
2124
- return true;
2125
- }
2126
-
2127
- /**
2128
- * @license
2129
- * Copyright 2017 Google LLC
2130
- *
2131
- * Licensed under the Apache License, Version 2.0 (the "License");
2132
- * you may not use this file except in compliance with the License.
2133
- * You may obtain a copy of the License at
2134
- *
2135
- * http://www.apache.org/licenses/LICENSE-2.0
2136
- *
2137
- * Unless required by applicable law or agreed to in writing, software
2138
- * distributed under the License is distributed on an "AS IS" BASIS,
2139
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2140
- * See the License for the specific language governing permissions and
2141
- * limitations under the License.
2142
- */
2143
- /**
2144
- * @fileoverview Standardized Firebase Error.
2145
- *
2146
- * Usage:
2147
- *
2148
- * // TypeScript string literals for type-safe codes
2149
- * type Err =
2150
- * 'unknown' |
2151
- * 'object-not-found'
2152
- * ;
2153
- *
2154
- * // Closure enum for type-safe error codes
2155
- * // at-enum {string}
2156
- * var Err = {
2157
- * UNKNOWN: 'unknown',
2158
- * OBJECT_NOT_FOUND: 'object-not-found',
2159
- * }
2160
- *
2161
- * let errors: Map<Err, string> = {
2162
- * 'generic-error': "Unknown error",
2163
- * 'file-not-found': "Could not find file: {$file}",
2164
- * };
2165
- *
2166
- * // Type-safe function - must pass a valid error code as param.
2167
- * let error = new ErrorFactory<Err>('service', 'Service', errors);
2168
- *
2169
- * ...
2170
- * throw error.create(Err.GENERIC);
2171
- * ...
2172
- * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
2173
- * ...
2174
- * // Service: Could not file file: foo.txt (service/file-not-found).
2175
- *
2176
- * catch (e) {
2177
- * assert(e.message === "Could not find file: foo.txt.");
2178
- * if ((e as FirebaseError)?.code === 'service/file-not-found') {
2179
- * console.log("Could not read file: " + e['file']);
2180
- * }
2181
- * }
2182
- */
2183
- const ERROR_NAME = 'FirebaseError';
2184
- // Based on code from:
2185
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
2186
- class FirebaseError extends Error {
2187
- constructor(
2188
- /** The error code for this error. */
2189
- code, message,
2190
- /** Custom data for this error. */
2191
- customData) {
2192
- super(message);
2193
- this.code = code;
2194
- this.customData = customData;
2195
- /** The custom name for all FirebaseErrors. */
2196
- this.name = ERROR_NAME;
2197
- // Fix For ES5
2198
- // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
2199
- // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
2200
- // which we can now use since we no longer target ES5.
2201
- Object.setPrototypeOf(this, FirebaseError.prototype);
2202
- // Maintains proper stack trace for where our error was thrown.
2203
- // Only available on V8.
2204
- if (Error.captureStackTrace) {
2205
- Error.captureStackTrace(this, ErrorFactory.prototype.create);
2206
- }
2207
- }
2208
- }
2209
- class ErrorFactory {
2210
- constructor(service, serviceName, errors) {
2211
- this.service = service;
2212
- this.serviceName = serviceName;
2213
- this.errors = errors;
2214
- }
2215
- create(code, ...data) {
2216
- const customData = data[0] || {};
2217
- const fullCode = `${this.service}/${code}`;
2218
- const template = this.errors[code];
2219
- const message = template ? replaceTemplate(template, customData) : 'Error';
2220
- // Service Name: Error message (service/code).
2221
- const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
2222
- const error = new FirebaseError(fullCode, fullMessage, customData);
2223
- return error;
2224
- }
2225
- }
2226
- function replaceTemplate(template, data) {
2227
- return template.replace(PATTERN, (_, key) => {
2228
- const value = data[key];
2229
- return value != null ? String(value) : `<${key}?>`;
2230
- });
2231
- }
2232
- const PATTERN = /\{\$([^}]+)}/g;
2233
- /**
2234
- * Deep equal two objects. Support Arrays and Objects.
2235
- */
2236
- function deepEqual(a, b) {
2237
- if (a === b) {
2238
- return true;
2239
- }
2240
- const aKeys = Object.keys(a);
2241
- const bKeys = Object.keys(b);
2242
- for (const k of aKeys) {
2243
- if (!bKeys.includes(k)) {
2244
- return false;
2245
- }
2246
- const aProp = a[k];
2247
- const bProp = b[k];
2248
- if (isObject(aProp) && isObject(bProp)) {
2249
- if (!deepEqual(aProp, bProp)) {
2250
- return false;
2251
- }
2252
- }
2253
- else if (aProp !== bProp) {
2254
- return false;
2255
- }
2256
- }
2257
- for (const k of bKeys) {
2258
- if (!aKeys.includes(k)) {
2259
- return false;
2260
- }
2261
- }
2262
- return true;
2263
- }
2264
- function isObject(thing) {
2265
- return thing !== null && typeof thing === 'object';
2266
- }
2267
-
2268
- /**
2269
- * @license
2270
- * Copyright 2021 Google LLC
2271
- *
2272
- * Licensed under the Apache License, Version 2.0 (the "License");
2273
- * you may not use this file except in compliance with the License.
2274
- * You may obtain a copy of the License at
2275
- *
2276
- * http://www.apache.org/licenses/LICENSE-2.0
2277
- *
2278
- * Unless required by applicable law or agreed to in writing, software
2279
- * distributed under the License is distributed on an "AS IS" BASIS,
2280
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2281
- * See the License for the specific language governing permissions and
2282
- * limitations under the License.
2283
- */
2284
- function getModularInstance(service) {
2285
- if (service && service._delegate) {
2286
- return service._delegate;
2287
- }
2288
- else {
2289
- return service;
2290
- }
2291
- }
2292
-
2293
- /**
2294
- * Component for service name T, e.g. `auth`, `auth-internal`
2295
- */
2296
- class Component {
2297
- /**
2298
- *
2299
- * @param name The public service name, e.g. app, auth, firestore, database
2300
- * @param instanceFactory Service factory responsible for creating the public interface
2301
- * @param type whether the service provided by the component is public or private
2302
- */
2303
- constructor(name, instanceFactory, type) {
2304
- this.name = name;
2305
- this.instanceFactory = instanceFactory;
2306
- this.type = type;
2307
- this.multipleInstances = false;
2308
- /**
2309
- * Properties to be added to the service namespace
2310
- */
2311
- this.serviceProps = {};
2312
- this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */;
2313
- this.onInstanceCreated = null;
2314
- }
2315
- setInstantiationMode(mode) {
2316
- this.instantiationMode = mode;
2317
- return this;
2318
- }
2319
- setMultipleInstances(multipleInstances) {
2320
- this.multipleInstances = multipleInstances;
2321
- return this;
2322
- }
2323
- setServiceProps(props) {
2324
- this.serviceProps = props;
2325
- return this;
2326
- }
2327
- setInstanceCreatedCallback(callback) {
2328
- this.onInstanceCreated = callback;
2329
- return this;
2330
- }
2331
- }
2332
-
2333
- /**
2334
- * @license
2335
- * Copyright 2019 Google LLC
2336
- *
2337
- * Licensed under the Apache License, Version 2.0 (the "License");
2338
- * you may not use this file except in compliance with the License.
2339
- * You may obtain a copy of the License at
2340
- *
2341
- * http://www.apache.org/licenses/LICENSE-2.0
2342
- *
2343
- * Unless required by applicable law or agreed to in writing, software
2344
- * distributed under the License is distributed on an "AS IS" BASIS,
2345
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2346
- * See the License for the specific language governing permissions and
2347
- * limitations under the License.
2348
- */
2349
- const DEFAULT_ENTRY_NAME$1 = '[DEFAULT]';
2350
-
2351
- /**
2352
- * @license
2353
- * Copyright 2019 Google LLC
2354
- *
2355
- * Licensed under the Apache License, Version 2.0 (the "License");
2356
- * you may not use this file except in compliance with the License.
2357
- * You may obtain a copy of the License at
2358
- *
2359
- * http://www.apache.org/licenses/LICENSE-2.0
2360
- *
2361
- * Unless required by applicable law or agreed to in writing, software
2362
- * distributed under the License is distributed on an "AS IS" BASIS,
2363
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2364
- * See the License for the specific language governing permissions and
2365
- * limitations under the License.
2366
- */
2367
- /**
2368
- * Provider for instance for service name T, e.g. 'auth', 'auth-internal'
2369
- * NameServiceMapping[T] is an alias for the type of the instance
2370
- */
2371
- class Provider {
2372
- constructor(name, container) {
2373
- this.name = name;
2374
- this.container = container;
2375
- this.component = null;
2376
- this.instances = new Map();
2377
- this.instancesDeferred = new Map();
2378
- this.instancesOptions = new Map();
2379
- this.onInitCallbacks = new Map();
2380
- }
2381
- /**
2382
- * @param identifier A provider can provide multiple instances of a service
2383
- * if this.component.multipleInstances is true.
2384
- */
2385
- get(identifier) {
2386
- // if multipleInstances is not supported, use the default name
2387
- const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
2388
- if (!this.instancesDeferred.has(normalizedIdentifier)) {
2389
- const deferred = new Deferred();
2390
- this.instancesDeferred.set(normalizedIdentifier, deferred);
2391
- if (this.isInitialized(normalizedIdentifier) ||
2392
- this.shouldAutoInitialize()) {
2393
- // initialize the service if it can be auto-initialized
2394
- try {
2395
- const instance = this.getOrInitializeService({
2396
- instanceIdentifier: normalizedIdentifier
2397
- });
2398
- if (instance) {
2399
- deferred.resolve(instance);
2400
- }
2401
- }
2402
- catch (e) {
2403
- // when the instance factory throws an exception during get(), it should not cause
2404
- // a fatal error. We just return the unresolved promise in this case.
2405
- }
2406
- }
2407
- }
2408
- return this.instancesDeferred.get(normalizedIdentifier).promise;
2409
- }
2410
- getImmediate(options) {
2411
- // if multipleInstances is not supported, use the default name
2412
- const normalizedIdentifier = this.normalizeInstanceIdentifier(options?.identifier);
2413
- const optional = options?.optional ?? false;
2414
- if (this.isInitialized(normalizedIdentifier) ||
2415
- this.shouldAutoInitialize()) {
2416
- try {
2417
- return this.getOrInitializeService({
2418
- instanceIdentifier: normalizedIdentifier
2419
- });
2420
- }
2421
- catch (e) {
2422
- if (optional) {
2423
- return null;
2424
- }
2425
- else {
2426
- throw e;
2427
- }
2428
- }
2429
- }
2430
- else {
2431
- // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw
2432
- if (optional) {
2433
- return null;
2434
- }
2435
- else {
2436
- throw Error(`Service ${this.name} is not available`);
2437
- }
2438
- }
2439
- }
2440
- getComponent() {
2441
- return this.component;
2442
- }
2443
- setComponent(component) {
2444
- if (component.name !== this.name) {
2445
- throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
2446
- }
2447
- if (this.component) {
2448
- throw Error(`Component for ${this.name} has already been provided`);
2449
- }
2450
- this.component = component;
2451
- // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
2452
- if (!this.shouldAutoInitialize()) {
2453
- return;
2454
- }
2455
- // if the service is eager, initialize the default instance
2456
- if (isComponentEager(component)) {
2457
- try {
2458
- this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 });
2459
- }
2460
- catch (e) {
2461
- // when the instance factory for an eager Component throws an exception during the eager
2462
- // initialization, it should not cause a fatal error.
2463
- // TODO: Investigate if we need to make it configurable, because some component may want to cause
2464
- // a fatal error in this case?
2465
- }
2466
- }
2467
- // Create service instances for the pending promises and resolve them
2468
- // NOTE: if this.multipleInstances is false, only the default instance will be created
2469
- // and all promises with resolve with it regardless of the identifier.
2470
- for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
2471
- const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
2472
- try {
2473
- // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
2474
- const instance = this.getOrInitializeService({
2475
- instanceIdentifier: normalizedIdentifier
2476
- });
2477
- instanceDeferred.resolve(instance);
2478
- }
2479
- catch (e) {
2480
- // when the instance factory throws an exception, it should not cause
2481
- // a fatal error. We just leave the promise unresolved.
2482
- }
2483
- }
2484
- }
2485
- clearInstance(identifier = DEFAULT_ENTRY_NAME$1) {
2486
- this.instancesDeferred.delete(identifier);
2487
- this.instancesOptions.delete(identifier);
2488
- this.instances.delete(identifier);
2489
- }
2490
- // app.delete() will call this method on every provider to delete the services
2491
- // TODO: should we mark the provider as deleted?
2492
- async delete() {
2493
- const services = Array.from(this.instances.values());
2494
- await Promise.all([
2495
- ...services
2496
- .filter(service => 'INTERNAL' in service) // legacy services
2497
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2498
- .map(service => service.INTERNAL.delete()),
2499
- ...services
2500
- .filter(service => '_delete' in service) // modularized services
2501
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2502
- .map(service => service._delete())
2503
- ]);
2504
- }
2505
- isComponentSet() {
2506
- return this.component != null;
2507
- }
2508
- isInitialized(identifier = DEFAULT_ENTRY_NAME$1) {
2509
- return this.instances.has(identifier);
2510
- }
2511
- getOptions(identifier = DEFAULT_ENTRY_NAME$1) {
2512
- return this.instancesOptions.get(identifier) || {};
2513
- }
2514
- initialize(opts = {}) {
2515
- const { options = {} } = opts;
2516
- const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
2517
- if (this.isInitialized(normalizedIdentifier)) {
2518
- throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
2519
- }
2520
- if (!this.isComponentSet()) {
2521
- throw Error(`Component ${this.name} has not been registered yet`);
2522
- }
2523
- const instance = this.getOrInitializeService({
2524
- instanceIdentifier: normalizedIdentifier,
2525
- options
2526
- });
2527
- // resolve any pending promise waiting for the service instance
2528
- for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
2529
- const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
2530
- if (normalizedIdentifier === normalizedDeferredIdentifier) {
2531
- instanceDeferred.resolve(instance);
2532
- }
2533
- }
2534
- return instance;
2535
- }
2536
- /**
2537
- *
2538
- * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
2539
- * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
2540
- *
2541
- * @param identifier An optional instance identifier
2542
- * @returns a function to unregister the callback
2543
- */
2544
- onInit(callback, identifier) {
2545
- const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
2546
- const existingCallbacks = this.onInitCallbacks.get(normalizedIdentifier) ??
2547
- new Set();
2548
- existingCallbacks.add(callback);
2549
- this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
2550
- const existingInstance = this.instances.get(normalizedIdentifier);
2551
- if (existingInstance) {
2552
- callback(existingInstance, normalizedIdentifier);
2553
- }
2554
- return () => {
2555
- existingCallbacks.delete(callback);
2556
- };
2557
- }
2558
- /**
2559
- * Invoke onInit callbacks synchronously
2560
- * @param instance the service instance`
2561
- */
2562
- invokeOnInitCallbacks(instance, identifier) {
2563
- const callbacks = this.onInitCallbacks.get(identifier);
2564
- if (!callbacks) {
2565
- return;
2566
- }
2567
- for (const callback of callbacks) {
2568
- try {
2569
- callback(instance, identifier);
2570
- }
2571
- catch {
2572
- // ignore errors in the onInit callback
2573
- }
2574
- }
2575
- }
2576
- getOrInitializeService({ instanceIdentifier, options = {} }) {
2577
- let instance = this.instances.get(instanceIdentifier);
2578
- if (!instance && this.component) {
2579
- instance = this.component.instanceFactory(this.container, {
2580
- instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
2581
- options
2582
- });
2583
- this.instances.set(instanceIdentifier, instance);
2584
- this.instancesOptions.set(instanceIdentifier, options);
2585
- /**
2586
- * Invoke onInit listeners.
2587
- * Note this.component.onInstanceCreated is different, which is used by the component creator,
2588
- * while onInit listeners are registered by consumers of the provider.
2589
- */
2590
- this.invokeOnInitCallbacks(instance, instanceIdentifier);
2591
- /**
2592
- * Order is important
2593
- * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
2594
- * makes `isInitialized()` return true.
2595
- */
2596
- if (this.component.onInstanceCreated) {
2597
- try {
2598
- this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
2599
- }
2600
- catch {
2601
- // ignore errors in the onInstanceCreatedCallback
2602
- }
2603
- }
2604
- }
2605
- return instance || null;
2606
- }
2607
- normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) {
2608
- if (this.component) {
2609
- return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1;
2610
- }
2611
- else {
2612
- return identifier; // assume multiple instances are supported before the component is provided.
2613
- }
2614
- }
2615
- shouldAutoInitialize() {
2616
- return (!!this.component &&
2617
- this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */);
2618
- }
2619
- }
2620
- // undefined should be passed to the service factory for the default instance
2621
- function normalizeIdentifierForFactory(identifier) {
2622
- return identifier === DEFAULT_ENTRY_NAME$1 ? undefined : identifier;
2623
- }
2624
- function isComponentEager(component) {
2625
- return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */;
2626
- }
2627
-
2628
- /**
2629
- * @license
2630
- * Copyright 2019 Google LLC
2631
- *
2632
- * Licensed under the Apache License, Version 2.0 (the "License");
2633
- * you may not use this file except in compliance with the License.
2634
- * You may obtain a copy of the License at
2635
- *
2636
- * http://www.apache.org/licenses/LICENSE-2.0
2637
- *
2638
- * Unless required by applicable law or agreed to in writing, software
2639
- * distributed under the License is distributed on an "AS IS" BASIS,
2640
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2641
- * See the License for the specific language governing permissions and
2642
- * limitations under the License.
2643
- */
2644
- /**
2645
- * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
2646
- */
2647
- class ComponentContainer {
2648
- constructor(name) {
2649
- this.name = name;
2650
- this.providers = new Map();
2651
- }
2652
- /**
2653
- *
2654
- * @param component Component being added
2655
- * @param overwrite When a component with the same name has already been registered,
2656
- * if overwrite is true: overwrite the existing component with the new component and create a new
2657
- * provider with the new component. It can be useful in tests where you want to use different mocks
2658
- * for different tests.
2659
- * if overwrite is false: throw an exception
2660
- */
2661
- addComponent(component) {
2662
- const provider = this.getProvider(component.name);
2663
- if (provider.isComponentSet()) {
2664
- throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
2665
- }
2666
- provider.setComponent(component);
2667
- }
2668
- addOrOverwriteComponent(component) {
2669
- const provider = this.getProvider(component.name);
2670
- if (provider.isComponentSet()) {
2671
- // delete the existing provider from the container, so we can register the new component
2672
- this.providers.delete(component.name);
2673
- }
2674
- this.addComponent(component);
2675
- }
2676
- /**
2677
- * getProvider provides a type safe interface where it can only be called with a field name
2678
- * present in NameServiceMapping interface.
2679
- *
2680
- * Firebase SDKs providing services should extend NameServiceMapping interface to register
2681
- * themselves.
2682
- */
2683
- getProvider(name) {
2684
- if (this.providers.has(name)) {
2685
- return this.providers.get(name);
2686
- }
2687
- // create a Provider for a service that hasn't registered with Firebase
2688
- const provider = new Provider(name, this);
2689
- this.providers.set(name, provider);
2690
- return provider;
2691
- }
2692
- getProviders() {
2693
- return Array.from(this.providers.values());
2694
- }
2695
- }
2696
-
2697
- /**
2698
- * @license
2699
- * Copyright 2017 Google LLC
2700
- *
2701
- * Licensed under the Apache License, Version 2.0 (the "License");
2702
- * you may not use this file except in compliance with the License.
2703
- * You may obtain a copy of the License at
2704
- *
2705
- * http://www.apache.org/licenses/LICENSE-2.0
2706
- *
2707
- * Unless required by applicable law or agreed to in writing, software
2708
- * distributed under the License is distributed on an "AS IS" BASIS,
2709
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2710
- * See the License for the specific language governing permissions and
2711
- * limitations under the License.
2712
- */
2713
- /**
2714
- * The JS SDK supports 5 log levels and also allows a user the ability to
2715
- * silence the logs altogether.
2716
- *
2717
- * The order is a follows:
2718
- * DEBUG < VERBOSE < INFO < WARN < ERROR
2719
- *
2720
- * All of the log types above the current log level will be captured (i.e. if
2721
- * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
2722
- * `VERBOSE` logs will not)
2723
- */
2724
- var LogLevel;
2725
- (function (LogLevel) {
2726
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
2727
- LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
2728
- LogLevel[LogLevel["INFO"] = 2] = "INFO";
2729
- LogLevel[LogLevel["WARN"] = 3] = "WARN";
2730
- LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
2731
- LogLevel[LogLevel["SILENT"] = 5] = "SILENT";
2732
- })(LogLevel || (LogLevel = {}));
2733
- const levelStringToEnum = {
2734
- 'debug': LogLevel.DEBUG,
2735
- 'verbose': LogLevel.VERBOSE,
2736
- 'info': LogLevel.INFO,
2737
- 'warn': LogLevel.WARN,
2738
- 'error': LogLevel.ERROR,
2739
- 'silent': LogLevel.SILENT
2740
- };
2741
- /**
2742
- * The default log level
2743
- */
2744
- const defaultLogLevel = LogLevel.INFO;
2745
- /**
2746
- * By default, `console.debug` is not displayed in the developer console (in
2747
- * chrome). To avoid forcing users to have to opt-in to these logs twice
2748
- * (i.e. once for firebase, and once in the console), we are sending `DEBUG`
2749
- * logs to the `console.log` function.
2750
- */
2751
- const ConsoleMethod = {
2752
- [LogLevel.DEBUG]: 'log',
2753
- [LogLevel.VERBOSE]: 'log',
2754
- [LogLevel.INFO]: 'info',
2755
- [LogLevel.WARN]: 'warn',
2756
- [LogLevel.ERROR]: 'error'
2757
- };
2758
- /**
2759
- * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
2760
- * messages on to their corresponding console counterparts (if the log method
2761
- * is supported by the current log level)
2762
- */
2763
- const defaultLogHandler = (instance, logType, ...args) => {
2764
- if (logType < instance.logLevel) {
2765
- return;
2766
- }
2767
- const now = new Date().toISOString();
2768
- const method = ConsoleMethod[logType];
2769
- if (method) {
2770
- console[method](`[${now}] ${instance.name}:`, ...args);
2771
- }
2772
- else {
2773
- throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
2774
- }
2775
- };
2776
- class Logger {
2777
- /**
2778
- * Gives you an instance of a Logger to capture messages according to
2779
- * Firebase's logging scheme.
2780
- *
2781
- * @param name The name that the logs will be associated with
2782
- */
2783
- constructor(name) {
2784
- this.name = name;
2785
- /**
2786
- * The log level of the given Logger instance.
2787
- */
2788
- this._logLevel = defaultLogLevel;
2789
- /**
2790
- * The main (internal) log handler for the Logger instance.
2791
- * Can be set to a new function in internal package code but not by user.
2792
- */
2793
- this._logHandler = defaultLogHandler;
2794
- /**
2795
- * The optional, additional, user-defined log handler for the Logger instance.
2796
- */
2797
- this._userLogHandler = null;
2798
- }
2799
- get logLevel() {
2800
- return this._logLevel;
2801
- }
2802
- set logLevel(val) {
2803
- if (!(val in LogLevel)) {
2804
- throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
2805
- }
2806
- this._logLevel = val;
2807
- }
2808
- // Workaround for setter/getter having to be the same type.
2809
- setLogLevel(val) {
2810
- this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;
2811
- }
2812
- get logHandler() {
2813
- return this._logHandler;
2814
- }
2815
- set logHandler(val) {
2816
- if (typeof val !== 'function') {
2817
- throw new TypeError('Value assigned to `logHandler` must be a function');
2818
- }
2819
- this._logHandler = val;
2820
- }
2821
- get userLogHandler() {
2822
- return this._userLogHandler;
2823
- }
2824
- set userLogHandler(val) {
2825
- this._userLogHandler = val;
2826
- }
2827
- /**
2828
- * The functions below are all based on the `console` interface
2829
- */
2830
- debug(...args) {
2831
- this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
2832
- this._logHandler(this, LogLevel.DEBUG, ...args);
2833
- }
2834
- log(...args) {
2835
- this._userLogHandler &&
2836
- this._userLogHandler(this, LogLevel.VERBOSE, ...args);
2837
- this._logHandler(this, LogLevel.VERBOSE, ...args);
2838
- }
2839
- info(...args) {
2840
- this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
2841
- this._logHandler(this, LogLevel.INFO, ...args);
2842
- }
2843
- warn(...args) {
2844
- this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
2845
- this._logHandler(this, LogLevel.WARN, ...args);
2846
- }
2847
- error(...args) {
2848
- this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
2849
- this._logHandler(this, LogLevel.ERROR, ...args);
2850
- }
2851
- }
2852
-
2853
- const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
2854
-
2855
- let idbProxyableTypes;
2856
- let cursorAdvanceMethods;
2857
- // This is a function to prevent it throwing up in node environments.
2858
- function getIdbProxyableTypes() {
2859
- return (idbProxyableTypes ||
2860
- (idbProxyableTypes = [
2861
- IDBDatabase,
2862
- IDBObjectStore,
2863
- IDBIndex,
2864
- IDBCursor,
2865
- IDBTransaction,
2866
- ]));
2867
- }
2868
- // This is a function to prevent it throwing up in node environments.
2869
- function getCursorAdvanceMethods() {
2870
- return (cursorAdvanceMethods ||
2871
- (cursorAdvanceMethods = [
2872
- IDBCursor.prototype.advance,
2873
- IDBCursor.prototype.continue,
2874
- IDBCursor.prototype.continuePrimaryKey,
2875
- ]));
2876
- }
2877
- const cursorRequestMap = new WeakMap();
2878
- const transactionDoneMap = new WeakMap();
2879
- const transactionStoreNamesMap = new WeakMap();
2880
- const transformCache = new WeakMap();
2881
- const reverseTransformCache = new WeakMap();
2882
- function promisifyRequest(request) {
2883
- const promise = new Promise((resolve, reject) => {
2884
- const unlisten = () => {
2885
- request.removeEventListener('success', success);
2886
- request.removeEventListener('error', error);
2887
- };
2888
- const success = () => {
2889
- resolve(wrap(request.result));
2890
- unlisten();
2891
- };
2892
- const error = () => {
2893
- reject(request.error);
2894
- unlisten();
2895
- };
2896
- request.addEventListener('success', success);
2897
- request.addEventListener('error', error);
2898
- });
2899
- promise
2900
- .then((value) => {
2901
- // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
2902
- // (see wrapFunction).
2903
- if (value instanceof IDBCursor) {
2904
- cursorRequestMap.set(value, request);
2905
- }
2906
- // Catching to avoid "Uncaught Promise exceptions"
2907
- })
2908
- .catch(() => { });
2909
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
2910
- // is because we create many promises from a single IDBRequest.
2911
- reverseTransformCache.set(promise, request);
2912
- return promise;
2913
- }
2914
- function cacheDonePromiseForTransaction(tx) {
2915
- // Early bail if we've already created a done promise for this transaction.
2916
- if (transactionDoneMap.has(tx))
2917
- return;
2918
- const done = new Promise((resolve, reject) => {
2919
- const unlisten = () => {
2920
- tx.removeEventListener('complete', complete);
2921
- tx.removeEventListener('error', error);
2922
- tx.removeEventListener('abort', error);
2923
- };
2924
- const complete = () => {
2925
- resolve();
2926
- unlisten();
2927
- };
2928
- const error = () => {
2929
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
2930
- unlisten();
2931
- };
2932
- tx.addEventListener('complete', complete);
2933
- tx.addEventListener('error', error);
2934
- tx.addEventListener('abort', error);
2935
- });
2936
- // Cache it for later retrieval.
2937
- transactionDoneMap.set(tx, done);
2938
- }
2939
- let idbProxyTraps = {
2940
- get(target, prop, receiver) {
2941
- if (target instanceof IDBTransaction) {
2942
- // Special handling for transaction.done.
2943
- if (prop === 'done')
2944
- return transactionDoneMap.get(target);
2945
- // Polyfill for objectStoreNames because of Edge.
2946
- if (prop === 'objectStoreNames') {
2947
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
2948
- }
2949
- // Make tx.store return the only store in the transaction, or undefined if there are many.
2950
- if (prop === 'store') {
2951
- return receiver.objectStoreNames[1]
2952
- ? undefined
2953
- : receiver.objectStore(receiver.objectStoreNames[0]);
2954
- }
2955
- }
2956
- // Else transform whatever we get back.
2957
- return wrap(target[prop]);
2958
- },
2959
- set(target, prop, value) {
2960
- target[prop] = value;
2961
- return true;
2962
- },
2963
- has(target, prop) {
2964
- if (target instanceof IDBTransaction &&
2965
- (prop === 'done' || prop === 'store')) {
2966
- return true;
2967
- }
2968
- return prop in target;
2969
- },
2970
- };
2971
- function replaceTraps(callback) {
2972
- idbProxyTraps = callback(idbProxyTraps);
2973
- }
2974
- function wrapFunction(func) {
2975
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
2976
- // only create one new func per func.
2977
- // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
2978
- if (func === IDBDatabase.prototype.transaction &&
2979
- !('objectStoreNames' in IDBTransaction.prototype)) {
2980
- return function (storeNames, ...args) {
2981
- const tx = func.call(unwrap(this), storeNames, ...args);
2982
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
2983
- return wrap(tx);
2984
- };
2985
- }
2986
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
2987
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
2988
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
2989
- // with real promises, so each advance methods returns a new promise for the cursor object, or
2990
- // undefined if the end of the cursor has been reached.
2991
- if (getCursorAdvanceMethods().includes(func)) {
2992
- return function (...args) {
2993
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
2994
- // the original object.
2995
- func.apply(unwrap(this), args);
2996
- return wrap(cursorRequestMap.get(this));
2997
- };
2998
- }
2999
- return function (...args) {
3000
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
3001
- // the original object.
3002
- return wrap(func.apply(unwrap(this), args));
3003
- };
3004
- }
3005
- function transformCachableValue(value) {
3006
- if (typeof value === 'function')
3007
- return wrapFunction(value);
3008
- // This doesn't return, it just creates a 'done' promise for the transaction,
3009
- // which is later returned for transaction.done (see idbObjectHandler).
3010
- if (value instanceof IDBTransaction)
3011
- cacheDonePromiseForTransaction(value);
3012
- if (instanceOfAny(value, getIdbProxyableTypes()))
3013
- return new Proxy(value, idbProxyTraps);
3014
- // Return the same value back if we're not going to transform it.
3015
- return value;
3016
- }
3017
- function wrap(value) {
3018
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
3019
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
3020
- if (value instanceof IDBRequest)
3021
- return promisifyRequest(value);
3022
- // If we've already transformed this value before, reuse the transformed value.
3023
- // This is faster, but it also provides object equality.
3024
- if (transformCache.has(value))
3025
- return transformCache.get(value);
3026
- const newValue = transformCachableValue(value);
3027
- // Not all types are transformed.
3028
- // These may be primitive types, so they can't be WeakMap keys.
3029
- if (newValue !== value) {
3030
- transformCache.set(value, newValue);
3031
- reverseTransformCache.set(newValue, value);
3032
- }
3033
- return newValue;
3034
- }
3035
- const unwrap = (value) => reverseTransformCache.get(value);
3036
-
3037
- /**
3038
- * Open a database.
3039
- *
3040
- * @param name Name of the database.
3041
- * @param version Schema version.
3042
- * @param callbacks Additional callbacks.
3043
- */
3044
- function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
3045
- const request = indexedDB.open(name, version);
3046
- const openPromise = wrap(request);
3047
- if (upgrade) {
3048
- request.addEventListener('upgradeneeded', (event) => {
3049
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
3050
- });
3051
- }
3052
- if (blocked) {
3053
- request.addEventListener('blocked', (event) => blocked(
3054
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
3055
- event.oldVersion, event.newVersion, event));
3056
- }
3057
- openPromise
3058
- .then((db) => {
3059
- if (terminated)
3060
- db.addEventListener('close', () => terminated());
3061
- if (blocking) {
3062
- db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
3063
- }
3064
- })
3065
- .catch(() => { });
3066
- return openPromise;
3067
- }
3068
- /**
3069
- * Delete a database.
3070
- *
3071
- * @param name Name of the database.
3072
- */
3073
- function deleteDB(name, { blocked } = {}) {
3074
- const request = indexedDB.deleteDatabase(name);
3075
- if (blocked) {
3076
- request.addEventListener('blocked', (event) => blocked(
3077
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
3078
- event.oldVersion, event));
3079
- }
3080
- return wrap(request).then(() => undefined);
3081
- }
3082
-
3083
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
3084
- const writeMethods = ['put', 'add', 'delete', 'clear'];
3085
- const cachedMethods = new Map();
3086
- function getMethod(target, prop) {
3087
- if (!(target instanceof IDBDatabase &&
3088
- !(prop in target) &&
3089
- typeof prop === 'string')) {
3090
- return;
3091
- }
3092
- if (cachedMethods.get(prop))
3093
- return cachedMethods.get(prop);
3094
- const targetFuncName = prop.replace(/FromIndex$/, '');
3095
- const useIndex = prop !== targetFuncName;
3096
- const isWrite = writeMethods.includes(targetFuncName);
3097
- if (
3098
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
3099
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
3100
- !(isWrite || readMethods.includes(targetFuncName))) {
3101
- return;
3102
- }
3103
- const method = async function (storeName, ...args) {
3104
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
3105
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
3106
- let target = tx.store;
3107
- if (useIndex)
3108
- target = target.index(args.shift());
3109
- // Must reject if op rejects.
3110
- // If it's a write operation, must reject if tx.done rejects.
3111
- // Must reject with op rejection first.
3112
- // Must resolve with op value.
3113
- // Must handle both promises (no unhandled rejections)
3114
- return (await Promise.all([
3115
- target[targetFuncName](...args),
3116
- isWrite && tx.done,
3117
- ]))[0];
3118
- };
3119
- cachedMethods.set(prop, method);
3120
- return method;
3121
- }
3122
- replaceTraps((oldTraps) => ({
3123
- ...oldTraps,
3124
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
3125
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
3126
- }));
3127
-
3128
- /**
3129
- * @license
3130
- * Copyright 2019 Google LLC
3131
- *
3132
- * Licensed under the Apache License, Version 2.0 (the "License");
3133
- * you may not use this file except in compliance with the License.
3134
- * You may obtain a copy of the License at
3135
- *
3136
- * http://www.apache.org/licenses/LICENSE-2.0
3137
- *
3138
- * Unless required by applicable law or agreed to in writing, software
3139
- * distributed under the License is distributed on an "AS IS" BASIS,
3140
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3141
- * See the License for the specific language governing permissions and
3142
- * limitations under the License.
3143
- */
3144
- class PlatformLoggerServiceImpl {
3145
- constructor(container) {
3146
- this.container = container;
3147
- }
3148
- // In initial implementation, this will be called by installations on
3149
- // auth token refresh, and installations will send this string.
3150
- getPlatformInfoString() {
3151
- const providers = this.container.getProviders();
3152
- // Loop through providers and get library/version pairs from any that are
3153
- // version components.
3154
- return providers
3155
- .map(provider => {
3156
- if (isVersionServiceProvider(provider)) {
3157
- const service = provider.getImmediate();
3158
- return `${service.library}/${service.version}`;
3159
- }
3160
- else {
3161
- return null;
3162
- }
3163
- })
3164
- .filter(logString => logString)
3165
- .join(' ');
3166
- }
3167
- }
3168
- /**
3169
- *
3170
- * @param provider check if this provider provides a VersionService
3171
- *
3172
- * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
3173
- * provides VersionService. The provider is not necessarily a 'app-version'
3174
- * provider.
3175
- */
3176
- function isVersionServiceProvider(provider) {
3177
- const component = provider.getComponent();
3178
- return component?.type === "VERSION" /* ComponentType.VERSION */;
3179
- }
3180
-
3181
- const name$q = "@firebase/app";
3182
- const version$1$1 = "0.14.4";
3183
-
3184
- /**
3185
- * @license
3186
- * Copyright 2019 Google LLC
3187
- *
3188
- * Licensed under the Apache License, Version 2.0 (the "License");
3189
- * you may not use this file except in compliance with the License.
3190
- * You may obtain a copy of the License at
3191
- *
3192
- * http://www.apache.org/licenses/LICENSE-2.0
3193
- *
3194
- * Unless required by applicable law or agreed to in writing, software
3195
- * distributed under the License is distributed on an "AS IS" BASIS,
3196
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3197
- * See the License for the specific language governing permissions and
3198
- * limitations under the License.
3199
- */
3200
- const logger = new Logger('@firebase/app');
3201
-
3202
- const name$p = "@firebase/app-compat";
3203
-
3204
- const name$o = "@firebase/analytics-compat";
3205
-
3206
- const name$n = "@firebase/analytics";
3207
-
3208
- const name$m = "@firebase/app-check-compat";
3209
-
3210
- const name$l = "@firebase/app-check";
3211
-
3212
- const name$k = "@firebase/auth";
3213
-
3214
- const name$j = "@firebase/auth-compat";
3215
-
3216
- const name$i = "@firebase/database";
3217
-
3218
- const name$h = "@firebase/data-connect";
3219
-
3220
- const name$g = "@firebase/database-compat";
3221
-
3222
- const name$f = "@firebase/functions";
3223
-
3224
- const name$e = "@firebase/functions-compat";
3225
-
3226
- const name$d = "@firebase/installations";
3227
-
3228
- const name$c = "@firebase/installations-compat";
3229
-
3230
- const name$b = "@firebase/messaging";
3231
-
3232
- const name$a = "@firebase/messaging-compat";
3233
-
3234
- const name$9 = "@firebase/performance";
3235
-
3236
- const name$8 = "@firebase/performance-compat";
3237
-
3238
- const name$7 = "@firebase/remote-config";
3239
-
3240
- const name$6 = "@firebase/remote-config-compat";
3241
-
3242
- const name$5 = "@firebase/storage";
3243
-
3244
- const name$4 = "@firebase/storage-compat";
3245
-
3246
- const name$3 = "@firebase/firestore";
3247
-
3248
- const name$2$1 = "@firebase/ai";
3249
-
3250
- const name$1$1 = "@firebase/firestore-compat";
3251
-
3252
- const name$r = "firebase";
3253
-
3254
- /**
3255
- * @license
3256
- * Copyright 2019 Google LLC
3257
- *
3258
- * Licensed under the Apache License, Version 2.0 (the "License");
3259
- * you may not use this file except in compliance with the License.
3260
- * You may obtain a copy of the License at
3261
- *
3262
- * http://www.apache.org/licenses/LICENSE-2.0
3263
- *
3264
- * Unless required by applicable law or agreed to in writing, software
3265
- * distributed under the License is distributed on an "AS IS" BASIS,
3266
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3267
- * See the License for the specific language governing permissions and
3268
- * limitations under the License.
3269
- */
3270
- /**
3271
- * The default app name
3272
- *
3273
- * @internal
3274
- */
3275
- const DEFAULT_ENTRY_NAME = '[DEFAULT]';
3276
- const PLATFORM_LOG_STRING = {
3277
- [name$q]: 'fire-core',
3278
- [name$p]: 'fire-core-compat',
3279
- [name$n]: 'fire-analytics',
3280
- [name$o]: 'fire-analytics-compat',
3281
- [name$l]: 'fire-app-check',
3282
- [name$m]: 'fire-app-check-compat',
3283
- [name$k]: 'fire-auth',
3284
- [name$j]: 'fire-auth-compat',
3285
- [name$i]: 'fire-rtdb',
3286
- [name$h]: 'fire-data-connect',
3287
- [name$g]: 'fire-rtdb-compat',
3288
- [name$f]: 'fire-fn',
3289
- [name$e]: 'fire-fn-compat',
3290
- [name$d]: 'fire-iid',
3291
- [name$c]: 'fire-iid-compat',
3292
- [name$b]: 'fire-fcm',
3293
- [name$a]: 'fire-fcm-compat',
3294
- [name$9]: 'fire-perf',
3295
- [name$8]: 'fire-perf-compat',
3296
- [name$7]: 'fire-rc',
3297
- [name$6]: 'fire-rc-compat',
3298
- [name$5]: 'fire-gcs',
3299
- [name$4]: 'fire-gcs-compat',
3300
- [name$3]: 'fire-fst',
3301
- [name$1$1]: 'fire-fst-compat',
3302
- [name$2$1]: 'fire-vertex',
3303
- 'fire-js': 'fire-js', // Platform identifier for JS SDK.
3304
- [name$r]: 'fire-js-all'
3305
- };
3306
-
3307
- /**
3308
- * @license
3309
- * Copyright 2019 Google LLC
3310
- *
3311
- * Licensed under the Apache License, Version 2.0 (the "License");
3312
- * you may not use this file except in compliance with the License.
3313
- * You may obtain a copy of the License at
3314
- *
3315
- * http://www.apache.org/licenses/LICENSE-2.0
3316
- *
3317
- * Unless required by applicable law or agreed to in writing, software
3318
- * distributed under the License is distributed on an "AS IS" BASIS,
3319
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3320
- * See the License for the specific language governing permissions and
3321
- * limitations under the License.
3322
- */
3323
- /**
3324
- * @internal
3325
- */
3326
- const _apps = new Map();
3327
- /**
3328
- * @internal
3329
- */
3330
- const _serverApps = new Map();
3331
- /**
3332
- * Registered components.
3333
- *
3334
- * @internal
3335
- */
3336
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3337
- const _components = new Map();
3338
- /**
3339
- * @param component - the component being added to this app's container
3340
- *
3341
- * @internal
3342
- */
3343
- function _addComponent(app, component) {
3344
- try {
3345
- app.container.addComponent(component);
3346
- }
3347
- catch (e) {
3348
- logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
3349
- }
3350
- }
3351
- /**
3352
- *
3353
- * @param component - the component to register
3354
- * @returns whether or not the component is registered successfully
3355
- *
3356
- * @internal
3357
- */
3358
- function _registerComponent(component) {
3359
- const componentName = component.name;
3360
- if (_components.has(componentName)) {
3361
- logger.debug(`There were multiple attempts to register component ${componentName}.`);
3362
- return false;
3363
- }
3364
- _components.set(componentName, component);
3365
- // add the component to existing app instances
3366
- for (const app of _apps.values()) {
3367
- _addComponent(app, component);
3368
- }
3369
- for (const serverApp of _serverApps.values()) {
3370
- _addComponent(serverApp, component);
3371
- }
3372
- return true;
3373
- }
3374
- /**
3375
- *
3376
- * @param app - FirebaseApp instance
3377
- * @param name - service name
3378
- *
3379
- * @returns the provider for the service with the matching name
3380
- *
3381
- * @internal
3382
- */
3383
- function _getProvider(app, name) {
3384
- const heartbeatController = app.container
3385
- .getProvider('heartbeat')
3386
- .getImmediate({ optional: true });
3387
- if (heartbeatController) {
3388
- void heartbeatController.triggerHeartbeat();
3389
- }
3390
- return app.container.getProvider(name);
3391
- }
3392
-
3393
- /**
3394
- * @license
3395
- * Copyright 2019 Google LLC
3396
- *
3397
- * Licensed under the Apache License, Version 2.0 (the "License");
3398
- * you may not use this file except in compliance with the License.
3399
- * You may obtain a copy of the License at
3400
- *
3401
- * http://www.apache.org/licenses/LICENSE-2.0
3402
- *
3403
- * Unless required by applicable law or agreed to in writing, software
3404
- * distributed under the License is distributed on an "AS IS" BASIS,
3405
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3406
- * See the License for the specific language governing permissions and
3407
- * limitations under the License.
3408
- */
3409
- const ERRORS = {
3410
- ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " +
3411
- 'call initializeApp() first',
3412
- ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'",
3413
- ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config",
3414
- ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted",
3415
- ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',
3416
- ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',
3417
- ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +
3418
- 'Firebase App instance.',
3419
- ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',
3420
- ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
3421
- ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
3422
- ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
3423
- ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
3424
- ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',
3425
- ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'
3426
- };
3427
- const ERROR_FACTORY$2 = new ErrorFactory('app', 'Firebase', ERRORS);
3428
-
3429
- /**
3430
- * @license
3431
- * Copyright 2019 Google LLC
3432
- *
3433
- * Licensed under the Apache License, Version 2.0 (the "License");
3434
- * you may not use this file except in compliance with the License.
3435
- * You may obtain a copy of the License at
3436
- *
3437
- * http://www.apache.org/licenses/LICENSE-2.0
3438
- *
3439
- * Unless required by applicable law or agreed to in writing, software
3440
- * distributed under the License is distributed on an "AS IS" BASIS,
3441
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3442
- * See the License for the specific language governing permissions and
3443
- * limitations under the License.
3444
- */
3445
- class FirebaseAppImpl {
3446
- constructor(options, config, container) {
3447
- this._isDeleted = false;
3448
- this._options = { ...options };
3449
- this._config = { ...config };
3450
- this._name = config.name;
3451
- this._automaticDataCollectionEnabled =
3452
- config.automaticDataCollectionEnabled;
3453
- this._container = container;
3454
- this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */));
3455
- }
3456
- get automaticDataCollectionEnabled() {
3457
- this.checkDestroyed();
3458
- return this._automaticDataCollectionEnabled;
3459
- }
3460
- set automaticDataCollectionEnabled(val) {
3461
- this.checkDestroyed();
3462
- this._automaticDataCollectionEnabled = val;
3463
- }
3464
- get name() {
3465
- this.checkDestroyed();
3466
- return this._name;
3467
- }
3468
- get options() {
3469
- this.checkDestroyed();
3470
- return this._options;
3471
- }
3472
- get config() {
3473
- this.checkDestroyed();
3474
- return this._config;
3475
- }
3476
- get container() {
3477
- return this._container;
3478
- }
3479
- get isDeleted() {
3480
- return this._isDeleted;
3481
- }
3482
- set isDeleted(val) {
3483
- this._isDeleted = val;
3484
- }
3485
- /**
3486
- * This function will throw an Error if the App has already been deleted -
3487
- * use before performing API actions on the App.
3488
- */
3489
- checkDestroyed() {
3490
- if (this.isDeleted) {
3491
- throw ERROR_FACTORY$2.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
3492
- }
3493
- }
3494
- }
3495
- function initializeApp(_options, rawConfig = {}) {
3496
- let options = _options;
3497
- if (typeof rawConfig !== 'object') {
3498
- const name = rawConfig;
3499
- rawConfig = { name };
3500
- }
3501
- const config = {
3502
- name: DEFAULT_ENTRY_NAME,
3503
- automaticDataCollectionEnabled: true,
3504
- ...rawConfig
3505
- };
3506
- const name = config.name;
3507
- if (typeof name !== 'string' || !name) {
3508
- throw ERROR_FACTORY$2.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
3509
- appName: String(name)
3510
- });
3511
- }
3512
- options || (options = getDefaultAppConfig());
3513
- if (!options) {
3514
- throw ERROR_FACTORY$2.create("no-options" /* AppError.NO_OPTIONS */);
3515
- }
3516
- const existingApp = _apps.get(name);
3517
- if (existingApp) {
3518
- // return the existing app if options and config deep equal the ones in the existing app.
3519
- if (deepEqual(options, existingApp.options) &&
3520
- deepEqual(config, existingApp.config)) {
3521
- return existingApp;
3522
- }
3523
- else {
3524
- throw ERROR_FACTORY$2.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
3525
- }
3526
- }
3527
- const container = new ComponentContainer(name);
3528
- for (const component of _components.values()) {
3529
- container.addComponent(component);
3530
- }
3531
- const newApp = new FirebaseAppImpl(options, config, container);
3532
- _apps.set(name, newApp);
3533
- return newApp;
3534
- }
3535
- /**
3536
- * Retrieves a {@link @firebase/app#FirebaseApp} instance.
3537
- *
3538
- * When called with no arguments, the default app is returned. When an app name
3539
- * is provided, the app corresponding to that name is returned.
3540
- *
3541
- * An exception is thrown if the app being retrieved has not yet been
3542
- * initialized.
3543
- *
3544
- * @example
3545
- * ```javascript
3546
- * // Return the default app
3547
- * const app = getApp();
3548
- * ```
3549
- *
3550
- * @example
3551
- * ```javascript
3552
- * // Return a named app
3553
- * const otherApp = getApp("otherApp");
3554
- * ```
3555
- *
3556
- * @param name - Optional name of the app to return. If no name is
3557
- * provided, the default is `"[DEFAULT]"`.
3558
- *
3559
- * @returns The app corresponding to the provided app name.
3560
- * If no app name is provided, the default app is returned.
3561
- *
3562
- * @public
3563
- */
3564
- function getApp(name = DEFAULT_ENTRY_NAME) {
3565
- const app = _apps.get(name);
3566
- if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
3567
- return initializeApp();
3568
- }
3569
- if (!app) {
3570
- throw ERROR_FACTORY$2.create("no-app" /* AppError.NO_APP */, { appName: name });
3571
- }
3572
- return app;
3573
- }
3574
- /**
3575
- * Registers a library's name and version for platform logging purposes.
3576
- * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
3577
- * @param version - Current version of that library.
3578
- * @param variant - Bundle variant, e.g., node, rn, etc.
3579
- *
3580
- * @public
3581
- */
3582
- function registerVersion(libraryKeyOrName, version, variant) {
3583
- // TODO: We can use this check to whitelist strings when/if we set up
3584
- // a good whitelist system.
3585
- let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;
3586
- if (variant) {
3587
- library += `-${variant}`;
3588
- }
3589
- const libraryMismatch = library.match(/\s|\//);
3590
- const versionMismatch = version.match(/\s|\//);
3591
- if (libraryMismatch || versionMismatch) {
3592
- const warning = [
3593
- `Unable to register library "${library}" with version "${version}":`
3594
- ];
3595
- if (libraryMismatch) {
3596
- warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
3597
- }
3598
- if (libraryMismatch && versionMismatch) {
3599
- warning.push('and');
3600
- }
3601
- if (versionMismatch) {
3602
- warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`);
3603
- }
3604
- logger.warn(warning.join(' '));
3605
- return;
3606
- }
3607
- _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */));
3608
- }
3609
-
3610
- /**
3611
- * @license
3612
- * Copyright 2021 Google LLC
3613
- *
3614
- * Licensed under the Apache License, Version 2.0 (the "License");
3615
- * you may not use this file except in compliance with the License.
3616
- * You may obtain a copy of the License at
3617
- *
3618
- * http://www.apache.org/licenses/LICENSE-2.0
3619
- *
3620
- * Unless required by applicable law or agreed to in writing, software
3621
- * distributed under the License is distributed on an "AS IS" BASIS,
3622
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3623
- * See the License for the specific language governing permissions and
3624
- * limitations under the License.
3625
- */
3626
- const DB_NAME = 'firebase-heartbeat-database';
3627
- const DB_VERSION = 1;
3628
- const STORE_NAME = 'firebase-heartbeat-store';
3629
- let dbPromise$2 = null;
3630
- function getDbPromise$2() {
3631
- if (!dbPromise$2) {
3632
- dbPromise$2 = openDB(DB_NAME, DB_VERSION, {
3633
- upgrade: (db, oldVersion) => {
3634
- // We don't use 'break' in this switch statement, the fall-through
3635
- // behavior is what we want, because if there are multiple versions between
3636
- // the old version and the current version, we want ALL the migrations
3637
- // that correspond to those versions to run, not only the last one.
3638
- // eslint-disable-next-line default-case
3639
- switch (oldVersion) {
3640
- case 0:
3641
- try {
3642
- db.createObjectStore(STORE_NAME);
3643
- }
3644
- catch (e) {
3645
- // Safari/iOS browsers throw occasional exceptions on
3646
- // db.createObjectStore() that may be a bug. Avoid blocking
3647
- // the rest of the app functionality.
3648
- console.warn(e);
3649
- }
3650
- }
3651
- }
3652
- }).catch(e => {
3653
- throw ERROR_FACTORY$2.create("idb-open" /* AppError.IDB_OPEN */, {
3654
- originalErrorMessage: e.message
3655
- });
3656
- });
3657
- }
3658
- return dbPromise$2;
3659
- }
3660
- async function readHeartbeatsFromIndexedDB(app) {
3661
- try {
3662
- const db = await getDbPromise$2();
3663
- const tx = db.transaction(STORE_NAME);
3664
- const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
3665
- // We already have the value but tx.done can throw,
3666
- // so we need to await it here to catch errors
3667
- await tx.done;
3668
- return result;
3669
- }
3670
- catch (e) {
3671
- if (e instanceof FirebaseError) {
3672
- logger.warn(e.message);
3673
- }
3674
- else {
3675
- const idbGetError = ERROR_FACTORY$2.create("idb-get" /* AppError.IDB_GET */, {
3676
- originalErrorMessage: e?.message
3677
- });
3678
- logger.warn(idbGetError.message);
3679
- }
3680
- }
3681
- }
3682
- async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
3683
- try {
3684
- const db = await getDbPromise$2();
3685
- const tx = db.transaction(STORE_NAME, 'readwrite');
3686
- const objectStore = tx.objectStore(STORE_NAME);
3687
- await objectStore.put(heartbeatObject, computeKey(app));
3688
- await tx.done;
3689
- }
3690
- catch (e) {
3691
- if (e instanceof FirebaseError) {
3692
- logger.warn(e.message);
3693
- }
3694
- else {
3695
- const idbGetError = ERROR_FACTORY$2.create("idb-set" /* AppError.IDB_WRITE */, {
3696
- originalErrorMessage: e?.message
3697
- });
3698
- logger.warn(idbGetError.message);
3699
- }
3700
- }
3701
- }
3702
- function computeKey(app) {
3703
- return `${app.name}!${app.options.appId}`;
3704
- }
3705
-
3706
- /**
3707
- * @license
3708
- * Copyright 2021 Google LLC
3709
- *
3710
- * Licensed under the Apache License, Version 2.0 (the "License");
3711
- * you may not use this file except in compliance with the License.
3712
- * You may obtain a copy of the License at
3713
- *
3714
- * http://www.apache.org/licenses/LICENSE-2.0
3715
- *
3716
- * Unless required by applicable law or agreed to in writing, software
3717
- * distributed under the License is distributed on an "AS IS" BASIS,
3718
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3719
- * See the License for the specific language governing permissions and
3720
- * limitations under the License.
3721
- */
3722
- const MAX_HEADER_BYTES = 1024;
3723
- const MAX_NUM_STORED_HEARTBEATS = 30;
3724
- class HeartbeatServiceImpl {
3725
- constructor(container) {
3726
- this.container = container;
3727
- /**
3728
- * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
3729
- * the header string.
3730
- * Stores one record per date. This will be consolidated into the standard
3731
- * format of one record per user agent string before being sent as a header.
3732
- * Populated from indexedDB when the controller is instantiated and should
3733
- * be kept in sync with indexedDB.
3734
- * Leave public for easier testing.
3735
- */
3736
- this._heartbeatsCache = null;
3737
- const app = this.container.getProvider('app').getImmediate();
3738
- this._storage = new HeartbeatStorageImpl(app);
3739
- this._heartbeatsCachePromise = this._storage.read().then(result => {
3740
- this._heartbeatsCache = result;
3741
- return result;
3742
- });
3743
- }
3744
- /**
3745
- * Called to report a heartbeat. The function will generate
3746
- * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
3747
- * to IndexedDB.
3748
- * Note that we only store one heartbeat per day. So if a heartbeat for today is
3749
- * already logged, subsequent calls to this function in the same day will be ignored.
3750
- */
3751
- async triggerHeartbeat() {
3752
- try {
3753
- const platformLogger = this.container
3754
- .getProvider('platform-logger')
3755
- .getImmediate();
3756
- // This is the "Firebase user agent" string from the platform logger
3757
- // service, not the browser user agent.
3758
- const agent = platformLogger.getPlatformInfoString();
3759
- const date = getUTCDateString();
3760
- if (this._heartbeatsCache?.heartbeats == null) {
3761
- this._heartbeatsCache = await this._heartbeatsCachePromise;
3762
- // If we failed to construct a heartbeats cache, then return immediately.
3763
- if (this._heartbeatsCache?.heartbeats == null) {
3764
- return;
3765
- }
3766
- }
3767
- // Do not store a heartbeat if one is already stored for this day
3768
- // or if a header has already been sent today.
3769
- if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
3770
- this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
3771
- return;
3772
- }
3773
- else {
3774
- // There is no entry for this date. Create one.
3775
- this._heartbeatsCache.heartbeats.push({ date, agent });
3776
- // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.
3777
- // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.
3778
- if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
3779
- const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
3780
- this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
3781
- }
3782
- }
3783
- return this._storage.overwrite(this._heartbeatsCache);
3784
- }
3785
- catch (e) {
3786
- logger.warn(e);
3787
- }
3788
- }
3789
- /**
3790
- * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
3791
- * It also clears all heartbeats from memory as well as in IndexedDB.
3792
- *
3793
- * NOTE: Consuming product SDKs should not send the header if this method
3794
- * returns an empty string.
3795
- */
3796
- async getHeartbeatsHeader() {
3797
- try {
3798
- if (this._heartbeatsCache === null) {
3799
- await this._heartbeatsCachePromise;
3800
- }
3801
- // If it's still null or the array is empty, there is no data to send.
3802
- if (this._heartbeatsCache?.heartbeats == null ||
3803
- this._heartbeatsCache.heartbeats.length === 0) {
3804
- return '';
3805
- }
3806
- const date = getUTCDateString();
3807
- // Extract as many heartbeats from the cache as will fit under the size limit.
3808
- const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
3809
- const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
3810
- // Store last sent date to prevent another being logged/sent for the same day.
3811
- this._heartbeatsCache.lastSentHeartbeatDate = date;
3812
- if (unsentEntries.length > 0) {
3813
- // Store any unsent entries if they exist.
3814
- this._heartbeatsCache.heartbeats = unsentEntries;
3815
- // This seems more likely than emptying the array (below) to lead to some odd state
3816
- // since the cache isn't empty and this will be called again on the next request,
3817
- // and is probably safest if we await it.
3818
- await this._storage.overwrite(this._heartbeatsCache);
3819
- }
3820
- else {
3821
- this._heartbeatsCache.heartbeats = [];
3822
- // Do not wait for this, to reduce latency.
3823
- void this._storage.overwrite(this._heartbeatsCache);
3824
- }
3825
- return headerString;
3826
- }
3827
- catch (e) {
3828
- logger.warn(e);
3829
- return '';
3830
- }
3831
- }
3832
- }
3833
- function getUTCDateString() {
3834
- const today = new Date();
3835
- // Returns date format 'YYYY-MM-DD'
3836
- return today.toISOString().substring(0, 10);
3837
- }
3838
- function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
3839
- // Heartbeats grouped by user agent in the standard format to be sent in
3840
- // the header.
3841
- const heartbeatsToSend = [];
3842
- // Single date format heartbeats that are not sent.
3843
- let unsentEntries = heartbeatsCache.slice();
3844
- for (const singleDateHeartbeat of heartbeatsCache) {
3845
- // Look for an existing entry with the same user agent.
3846
- const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
3847
- if (!heartbeatEntry) {
3848
- // If no entry for this user agent exists, create one.
3849
- heartbeatsToSend.push({
3850
- agent: singleDateHeartbeat.agent,
3851
- dates: [singleDateHeartbeat.date]
3852
- });
3853
- if (countBytes(heartbeatsToSend) > maxSize) {
3854
- // If the header would exceed max size, remove the added heartbeat
3855
- // entry and stop adding to the header.
3856
- heartbeatsToSend.pop();
3857
- break;
3858
- }
3859
- }
3860
- else {
3861
- heartbeatEntry.dates.push(singleDateHeartbeat.date);
3862
- // If the header would exceed max size, remove the added date
3863
- // and stop adding to the header.
3864
- if (countBytes(heartbeatsToSend) > maxSize) {
3865
- heartbeatEntry.dates.pop();
3866
- break;
3867
- }
3868
- }
3869
- // Pop unsent entry from queue. (Skipped if adding the entry exceeded
3870
- // quota and the loop breaks early.)
3871
- unsentEntries = unsentEntries.slice(1);
3872
- }
3873
- return {
3874
- heartbeatsToSend,
3875
- unsentEntries
3876
- };
3877
- }
3878
- class HeartbeatStorageImpl {
3879
- constructor(app) {
3880
- this.app = app;
3881
- this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
3882
- }
3883
- async runIndexedDBEnvironmentCheck() {
3884
- if (!isIndexedDBAvailable()) {
3885
- return false;
3886
- }
3887
- else {
3888
- return validateIndexedDBOpenable()
3889
- .then(() => true)
3890
- .catch(() => false);
3891
- }
3892
- }
3893
- /**
3894
- * Read all heartbeats.
3895
- */
3896
- async read() {
3897
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
3898
- if (!canUseIndexedDB) {
3899
- return { heartbeats: [] };
3900
- }
3901
- else {
3902
- const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
3903
- if (idbHeartbeatObject?.heartbeats) {
3904
- return idbHeartbeatObject;
3905
- }
3906
- else {
3907
- return { heartbeats: [] };
3908
- }
3909
- }
3910
- }
3911
- // overwrite the storage with the provided heartbeats
3912
- async overwrite(heartbeatsObject) {
3913
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
3914
- if (!canUseIndexedDB) {
3915
- return;
3916
- }
3917
- else {
3918
- const existingHeartbeatsObject = await this.read();
3919
- return writeHeartbeatsToIndexedDB(this.app, {
3920
- lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
3921
- existingHeartbeatsObject.lastSentHeartbeatDate,
3922
- heartbeats: heartbeatsObject.heartbeats
3923
- });
3924
- }
3925
- }
3926
- // add heartbeats
3927
- async add(heartbeatsObject) {
3928
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
3929
- if (!canUseIndexedDB) {
3930
- return;
3931
- }
3932
- else {
3933
- const existingHeartbeatsObject = await this.read();
3934
- return writeHeartbeatsToIndexedDB(this.app, {
3935
- lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
3936
- existingHeartbeatsObject.lastSentHeartbeatDate,
3937
- heartbeats: [
3938
- ...existingHeartbeatsObject.heartbeats,
3939
- ...heartbeatsObject.heartbeats
3940
- ]
3941
- });
3942
- }
3943
- }
3944
- }
3945
- /**
3946
- * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
3947
- * in a platform logging header JSON object, stringified, and converted
3948
- * to base 64.
3949
- */
3950
- function countBytes(heartbeatsCache) {
3951
- // base64 has a restricted set of characters, all of which should be 1 byte.
3952
- return base64urlEncodeWithoutPadding(
3953
- // heartbeatsCache wrapper properties
3954
- JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
3955
- }
3956
- /**
3957
- * Returns the index of the heartbeat with the earliest date.
3958
- * If the heartbeats array is empty, -1 is returned.
3959
- */
3960
- function getEarliestHeartbeatIdx(heartbeats) {
3961
- if (heartbeats.length === 0) {
3962
- return -1;
3963
- }
3964
- let earliestHeartbeatIdx = 0;
3965
- let earliestHeartbeatDate = heartbeats[0].date;
3966
- for (let i = 1; i < heartbeats.length; i++) {
3967
- if (heartbeats[i].date < earliestHeartbeatDate) {
3968
- earliestHeartbeatDate = heartbeats[i].date;
3969
- earliestHeartbeatIdx = i;
3970
- }
3971
- }
3972
- return earliestHeartbeatIdx;
3973
- }
3974
-
3975
- /**
3976
- * @license
3977
- * Copyright 2019 Google LLC
3978
- *
3979
- * Licensed under the Apache License, Version 2.0 (the "License");
3980
- * you may not use this file except in compliance with the License.
3981
- * You may obtain a copy of the License at
3982
- *
3983
- * http://www.apache.org/licenses/LICENSE-2.0
3984
- *
3985
- * Unless required by applicable law or agreed to in writing, software
3986
- * distributed under the License is distributed on an "AS IS" BASIS,
3987
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3988
- * See the License for the specific language governing permissions and
3989
- * limitations under the License.
3990
- */
3991
- function registerCoreComponents(variant) {
3992
- _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
3993
- _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
3994
- // Register `app` package.
3995
- registerVersion(name$q, version$1$1, variant);
3996
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
3997
- registerVersion(name$q, version$1$1, 'esm2020');
3998
- // Register platform SDK identifier (no version).
3999
- registerVersion('fire-js', '');
4000
- }
4001
-
4002
- /**
4003
- * Firebase App
4004
- *
4005
- * @remarks This package coordinates the communication between the different Firebase components
4006
- * @packageDocumentation
4007
- */
4008
- registerCoreComponents('');
4009
-
4010
- var name$2 = "firebase";
4011
- var version$2 = "12.4.0";
4012
-
4013
- /**
4014
- * @license
4015
- * Copyright 2020 Google LLC
4016
- *
4017
- * Licensed under the Apache License, Version 2.0 (the "License");
4018
- * you may not use this file except in compliance with the License.
4019
- * You may obtain a copy of the License at
4020
- *
4021
- * http://www.apache.org/licenses/LICENSE-2.0
4022
- *
4023
- * Unless required by applicable law or agreed to in writing, software
4024
- * distributed under the License is distributed on an "AS IS" BASIS,
4025
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4026
- * See the License for the specific language governing permissions and
4027
- * limitations under the License.
4028
- */
4029
- registerVersion(name$2, version$2, 'app');
4030
-
4031
- const name$1 = "@firebase/installations";
4032
- const version$1 = "0.6.19";
4033
-
4034
- /**
4035
- * @license
4036
- * Copyright 2019 Google LLC
4037
- *
4038
- * Licensed under the Apache License, Version 2.0 (the "License");
4039
- * you may not use this file except in compliance with the License.
4040
- * You may obtain a copy of the License at
4041
- *
4042
- * http://www.apache.org/licenses/LICENSE-2.0
4043
- *
4044
- * Unless required by applicable law or agreed to in writing, software
4045
- * distributed under the License is distributed on an "AS IS" BASIS,
4046
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4047
- * See the License for the specific language governing permissions and
4048
- * limitations under the License.
4049
- */
4050
- const PENDING_TIMEOUT_MS = 10000;
4051
- const PACKAGE_VERSION = `w:${version$1}`;
4052
- const INTERNAL_AUTH_VERSION = 'FIS_v2';
4053
- const INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';
4054
- const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour
4055
- const SERVICE = 'installations';
4056
- const SERVICE_NAME = 'Installations';
4057
-
4058
- /**
4059
- * @license
4060
- * Copyright 2019 Google LLC
4061
- *
4062
- * Licensed under the Apache License, Version 2.0 (the "License");
4063
- * you may not use this file except in compliance with the License.
4064
- * You may obtain a copy of the License at
4065
- *
4066
- * http://www.apache.org/licenses/LICENSE-2.0
4067
- *
4068
- * Unless required by applicable law or agreed to in writing, software
4069
- * distributed under the License is distributed on an "AS IS" BASIS,
4070
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4071
- * See the License for the specific language governing permissions and
4072
- * limitations under the License.
4073
- */
4074
- const ERROR_DESCRIPTION_MAP = {
4075
- ["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
4076
- ["not-registered" /* ErrorCode.NOT_REGISTERED */]: 'Firebase Installation is not registered.',
4077
- ["installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',
4078
- ["request-failed" /* ErrorCode.REQUEST_FAILED */]: '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',
4079
- ["app-offline" /* ErrorCode.APP_OFFLINE */]: 'Could not process request. Application offline.',
4080
- ["delete-pending-registration" /* ErrorCode.DELETE_PENDING_REGISTRATION */]: "Can't delete installation while there is a pending registration request."
4081
- };
4082
- const ERROR_FACTORY$1 = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
4083
- /** Returns true if error is a FirebaseError that is based on an error from the server. */
4084
- function isServerError(error) {
4085
- return (error instanceof FirebaseError &&
4086
- error.code.includes("request-failed" /* ErrorCode.REQUEST_FAILED */));
4087
- }
4088
-
4089
- /**
4090
- * @license
4091
- * Copyright 2019 Google LLC
4092
- *
4093
- * Licensed under the Apache License, Version 2.0 (the "License");
4094
- * you may not use this file except in compliance with the License.
4095
- * You may obtain a copy of the License at
4096
- *
4097
- * http://www.apache.org/licenses/LICENSE-2.0
4098
- *
4099
- * Unless required by applicable law or agreed to in writing, software
4100
- * distributed under the License is distributed on an "AS IS" BASIS,
4101
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4102
- * See the License for the specific language governing permissions and
4103
- * limitations under the License.
4104
- */
4105
- function getInstallationsEndpoint({ projectId }) {
4106
- return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;
4107
- }
4108
- function extractAuthTokenInfoFromResponse(response) {
4109
- return {
4110
- token: response.token,
4111
- requestStatus: 2 /* RequestStatus.COMPLETED */,
4112
- expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),
4113
- creationTime: Date.now()
4114
- };
4115
- }
4116
- async function getErrorFromResponse(requestName, response) {
4117
- const responseJson = await response.json();
4118
- const errorData = responseJson.error;
4119
- return ERROR_FACTORY$1.create("request-failed" /* ErrorCode.REQUEST_FAILED */, {
4120
- requestName,
4121
- serverCode: errorData.code,
4122
- serverMessage: errorData.message,
4123
- serverStatus: errorData.status
4124
- });
4125
- }
4126
- function getHeaders$1({ apiKey }) {
4127
- return new Headers({
4128
- 'Content-Type': 'application/json',
4129
- Accept: 'application/json',
4130
- 'x-goog-api-key': apiKey
4131
- });
4132
- }
4133
- function getHeadersWithAuth(appConfig, { refreshToken }) {
4134
- const headers = getHeaders$1(appConfig);
4135
- headers.append('Authorization', getAuthorizationHeader(refreshToken));
4136
- return headers;
4137
- }
4138
- /**
4139
- * Calls the passed in fetch wrapper and returns the response.
4140
- * If the returned response has a status of 5xx, re-runs the function once and
4141
- * returns the response.
4142
- */
4143
- async function retryIfServerError(fn) {
4144
- const result = await fn();
4145
- if (result.status >= 500 && result.status < 600) {
4146
- // Internal Server Error. Retry request.
4147
- return fn();
4148
- }
4149
- return result;
4150
- }
4151
- function getExpiresInFromResponseExpiresIn(responseExpiresIn) {
4152
- // This works because the server will never respond with fractions of a second.
4153
- return Number(responseExpiresIn.replace('s', '000'));
4154
- }
4155
- function getAuthorizationHeader(refreshToken) {
4156
- return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;
4157
- }
4158
-
4159
- /**
4160
- * @license
4161
- * Copyright 2019 Google LLC
4162
- *
4163
- * Licensed under the Apache License, Version 2.0 (the "License");
4164
- * you may not use this file except in compliance with the License.
4165
- * You may obtain a copy of the License at
4166
- *
4167
- * http://www.apache.org/licenses/LICENSE-2.0
4168
- *
4169
- * Unless required by applicable law or agreed to in writing, software
4170
- * distributed under the License is distributed on an "AS IS" BASIS,
4171
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4172
- * See the License for the specific language governing permissions and
4173
- * limitations under the License.
4174
- */
4175
- async function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {
4176
- const endpoint = getInstallationsEndpoint(appConfig);
4177
- const headers = getHeaders$1(appConfig);
4178
- // If heartbeat service exists, add the heartbeat string to the header.
4179
- const heartbeatService = heartbeatServiceProvider.getImmediate({
4180
- optional: true
4181
- });
4182
- if (heartbeatService) {
4183
- const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
4184
- if (heartbeatsHeader) {
4185
- headers.append('x-firebase-client', heartbeatsHeader);
4186
- }
4187
- }
4188
- const body = {
4189
- fid,
4190
- authVersion: INTERNAL_AUTH_VERSION,
4191
- appId: appConfig.appId,
4192
- sdkVersion: PACKAGE_VERSION
4193
- };
4194
- const request = {
4195
- method: 'POST',
4196
- headers,
4197
- body: JSON.stringify(body)
4198
- };
4199
- const response = await retryIfServerError(() => fetch(endpoint, request));
4200
- if (response.ok) {
4201
- const responseValue = await response.json();
4202
- const registeredInstallationEntry = {
4203
- fid: responseValue.fid || fid,
4204
- registrationStatus: 2 /* RequestStatus.COMPLETED */,
4205
- refreshToken: responseValue.refreshToken,
4206
- authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)
4207
- };
4208
- return registeredInstallationEntry;
4209
- }
4210
- else {
4211
- throw await getErrorFromResponse('Create Installation', response);
4212
- }
4213
- }
4214
-
4215
- /**
4216
- * @license
4217
- * Copyright 2019 Google LLC
4218
- *
4219
- * Licensed under the Apache License, Version 2.0 (the "License");
4220
- * you may not use this file except in compliance with the License.
4221
- * You may obtain a copy of the License at
4222
- *
4223
- * http://www.apache.org/licenses/LICENSE-2.0
4224
- *
4225
- * Unless required by applicable law or agreed to in writing, software
4226
- * distributed under the License is distributed on an "AS IS" BASIS,
4227
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4228
- * See the License for the specific language governing permissions and
4229
- * limitations under the License.
4230
- */
4231
- /** Returns a promise that resolves after given time passes. */
4232
- function sleep(ms) {
4233
- return new Promise(resolve => {
4234
- setTimeout(resolve, ms);
4235
- });
4236
- }
4237
-
4238
- /**
4239
- * @license
4240
- * Copyright 2019 Google LLC
4241
- *
4242
- * Licensed under the Apache License, Version 2.0 (the "License");
4243
- * you may not use this file except in compliance with the License.
4244
- * You may obtain a copy of the License at
4245
- *
4246
- * http://www.apache.org/licenses/LICENSE-2.0
4247
- *
4248
- * Unless required by applicable law or agreed to in writing, software
4249
- * distributed under the License is distributed on an "AS IS" BASIS,
4250
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4251
- * See the License for the specific language governing permissions and
4252
- * limitations under the License.
4253
- */
4254
- function bufferToBase64UrlSafe(array) {
4255
- const b64 = btoa(String.fromCharCode(...array));
4256
- return b64.replace(/\+/g, '-').replace(/\//g, '_');
4257
- }
4258
-
4259
- /**
4260
- * @license
4261
- * Copyright 2019 Google LLC
4262
- *
4263
- * Licensed under the Apache License, Version 2.0 (the "License");
4264
- * you may not use this file except in compliance with the License.
4265
- * You may obtain a copy of the License at
4266
- *
4267
- * http://www.apache.org/licenses/LICENSE-2.0
4268
- *
4269
- * Unless required by applicable law or agreed to in writing, software
4270
- * distributed under the License is distributed on an "AS IS" BASIS,
4271
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4272
- * See the License for the specific language governing permissions and
4273
- * limitations under the License.
4274
- */
4275
- const VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
4276
- const INVALID_FID = '';
4277
- /**
4278
- * Generates a new FID using random values from Web Crypto API.
4279
- * Returns an empty string if FID generation fails for any reason.
4280
- */
4281
- function generateFid() {
4282
- try {
4283
- // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
4284
- // bytes. our implementation generates a 17 byte array instead.
4285
- const fidByteArray = new Uint8Array(17);
4286
- const crypto = self.crypto || self.msCrypto;
4287
- crypto.getRandomValues(fidByteArray);
4288
- // Replace the first 4 random bits with the constant FID header of 0b0111.
4289
- fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);
4290
- const fid = encode(fidByteArray);
4291
- return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
4292
- }
4293
- catch {
4294
- // FID generation errored
4295
- return INVALID_FID;
4296
- }
4297
- }
4298
- /** Converts a FID Uint8Array to a base64 string representation. */
4299
- function encode(fidByteArray) {
4300
- const b64String = bufferToBase64UrlSafe(fidByteArray);
4301
- // Remove the 23rd character that was added because of the extra 4 bits at the
4302
- // end of our 17 byte array, and the '=' padding.
4303
- return b64String.substr(0, 22);
4304
- }
4305
-
4306
- /**
4307
- * @license
4308
- * Copyright 2019 Google LLC
4309
- *
4310
- * Licensed under the Apache License, Version 2.0 (the "License");
4311
- * you may not use this file except in compliance with the License.
4312
- * You may obtain a copy of the License at
4313
- *
4314
- * http://www.apache.org/licenses/LICENSE-2.0
4315
- *
4316
- * Unless required by applicable law or agreed to in writing, software
4317
- * distributed under the License is distributed on an "AS IS" BASIS,
4318
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4319
- * See the License for the specific language governing permissions and
4320
- * limitations under the License.
4321
- */
4322
- /** Returns a string key that can be used to identify the app. */
4323
- function getKey$1(appConfig) {
4324
- return `${appConfig.appName}!${appConfig.appId}`;
4325
- }
4326
-
4327
- /**
4328
- * @license
4329
- * Copyright 2019 Google LLC
4330
- *
4331
- * Licensed under the Apache License, Version 2.0 (the "License");
4332
- * you may not use this file except in compliance with the License.
4333
- * You may obtain a copy of the License at
4334
- *
4335
- * http://www.apache.org/licenses/LICENSE-2.0
4336
- *
4337
- * Unless required by applicable law or agreed to in writing, software
4338
- * distributed under the License is distributed on an "AS IS" BASIS,
4339
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4340
- * See the License for the specific language governing permissions and
4341
- * limitations under the License.
4342
- */
4343
- const fidChangeCallbacks = new Map();
4344
- /**
4345
- * Calls the onIdChange callbacks with the new FID value, and broadcasts the
4346
- * change to other tabs.
4347
- */
4348
- function fidChanged(appConfig, fid) {
4349
- const key = getKey$1(appConfig);
4350
- callFidChangeCallbacks(key, fid);
4351
- broadcastFidChange(key, fid);
4352
- }
4353
- function callFidChangeCallbacks(key, fid) {
4354
- const callbacks = fidChangeCallbacks.get(key);
4355
- if (!callbacks) {
4356
- return;
4357
- }
4358
- for (const callback of callbacks) {
4359
- callback(fid);
4360
- }
4361
- }
4362
- function broadcastFidChange(key, fid) {
4363
- const channel = getBroadcastChannel();
4364
- if (channel) {
4365
- channel.postMessage({ key, fid });
4366
- }
4367
- closeBroadcastChannel();
4368
- }
4369
- let broadcastChannel = null;
4370
- /** Opens and returns a BroadcastChannel if it is supported by the browser. */
4371
- function getBroadcastChannel() {
4372
- if (!broadcastChannel && 'BroadcastChannel' in self) {
4373
- broadcastChannel = new BroadcastChannel('[Firebase] FID Change');
4374
- broadcastChannel.onmessage = e => {
4375
- callFidChangeCallbacks(e.data.key, e.data.fid);
4376
- };
4377
- }
4378
- return broadcastChannel;
4379
- }
4380
- function closeBroadcastChannel() {
4381
- if (fidChangeCallbacks.size === 0 && broadcastChannel) {
4382
- broadcastChannel.close();
4383
- broadcastChannel = null;
4384
- }
4385
- }
4386
-
4387
- /**
4388
- * @license
4389
- * Copyright 2019 Google LLC
4390
- *
4391
- * Licensed under the Apache License, Version 2.0 (the "License");
4392
- * you may not use this file except in compliance with the License.
4393
- * You may obtain a copy of the License at
4394
- *
4395
- * http://www.apache.org/licenses/LICENSE-2.0
4396
- *
4397
- * Unless required by applicable law or agreed to in writing, software
4398
- * distributed under the License is distributed on an "AS IS" BASIS,
4399
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4400
- * See the License for the specific language governing permissions and
4401
- * limitations under the License.
4402
- */
4403
- const DATABASE_NAME$1 = 'firebase-installations-database';
4404
- const DATABASE_VERSION$1 = 1;
4405
- const OBJECT_STORE_NAME$1 = 'firebase-installations-store';
4406
- let dbPromise$1 = null;
4407
- function getDbPromise$1() {
4408
- if (!dbPromise$1) {
4409
- dbPromise$1 = openDB(DATABASE_NAME$1, DATABASE_VERSION$1, {
4410
- upgrade: (db, oldVersion) => {
4411
- // We don't use 'break' in this switch statement, the fall-through
4412
- // behavior is what we want, because if there are multiple versions between
4413
- // the old version and the current version, we want ALL the migrations
4414
- // that correspond to those versions to run, not only the last one.
4415
- // eslint-disable-next-line default-case
4416
- switch (oldVersion) {
4417
- case 0:
4418
- db.createObjectStore(OBJECT_STORE_NAME$1);
4419
- }
4420
- }
4421
- });
4422
- }
4423
- return dbPromise$1;
4424
- }
4425
- /** Assigns or overwrites the record for the given key with the given value. */
4426
- async function set(appConfig, value) {
4427
- const key = getKey$1(appConfig);
4428
- const db = await getDbPromise$1();
4429
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
4430
- const objectStore = tx.objectStore(OBJECT_STORE_NAME$1);
4431
- const oldValue = (await objectStore.get(key));
4432
- await objectStore.put(value, key);
4433
- await tx.done;
4434
- if (!oldValue || oldValue.fid !== value.fid) {
4435
- fidChanged(appConfig, value.fid);
4436
- }
4437
- return value;
4438
- }
4439
- /** Removes record(s) from the objectStore that match the given key. */
4440
- async function remove(appConfig) {
4441
- const key = getKey$1(appConfig);
4442
- const db = await getDbPromise$1();
4443
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
4444
- await tx.objectStore(OBJECT_STORE_NAME$1).delete(key);
4445
- await tx.done;
4446
- }
4447
- /**
4448
- * Atomically updates a record with the result of updateFn, which gets
4449
- * called with the current value. If newValue is undefined, the record is
4450
- * deleted instead.
4451
- * @return Updated value
4452
- */
4453
- async function update(appConfig, updateFn) {
4454
- const key = getKey$1(appConfig);
4455
- const db = await getDbPromise$1();
4456
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
4457
- const store = tx.objectStore(OBJECT_STORE_NAME$1);
4458
- const oldValue = (await store.get(key));
4459
- const newValue = updateFn(oldValue);
4460
- if (newValue === undefined) {
4461
- await store.delete(key);
4462
- }
4463
- else {
4464
- await store.put(newValue, key);
4465
- }
4466
- await tx.done;
4467
- if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {
4468
- fidChanged(appConfig, newValue.fid);
4469
- }
4470
- return newValue;
4471
- }
4472
-
4473
- /**
4474
- * @license
4475
- * Copyright 2019 Google LLC
4476
- *
4477
- * Licensed under the Apache License, Version 2.0 (the "License");
4478
- * you may not use this file except in compliance with the License.
4479
- * You may obtain a copy of the License at
4480
- *
4481
- * http://www.apache.org/licenses/LICENSE-2.0
4482
- *
4483
- * Unless required by applicable law or agreed to in writing, software
4484
- * distributed under the License is distributed on an "AS IS" BASIS,
4485
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4486
- * See the License for the specific language governing permissions and
4487
- * limitations under the License.
4488
- */
4489
- /**
4490
- * Updates and returns the InstallationEntry from the database.
4491
- * Also triggers a registration request if it is necessary and possible.
4492
- */
4493
- async function getInstallationEntry(installations) {
4494
- let registrationPromise;
4495
- const installationEntry = await update(installations.appConfig, oldEntry => {
4496
- const installationEntry = updateOrCreateInstallationEntry(oldEntry);
4497
- const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);
4498
- registrationPromise = entryWithPromise.registrationPromise;
4499
- return entryWithPromise.installationEntry;
4500
- });
4501
- if (installationEntry.fid === INVALID_FID) {
4502
- // FID generation failed. Waiting for the FID from the server.
4503
- return { installationEntry: await registrationPromise };
4504
- }
4505
- return {
4506
- installationEntry,
4507
- registrationPromise
4508
- };
4509
- }
4510
- /**
4511
- * Creates a new Installation Entry if one does not exist.
4512
- * Also clears timed out pending requests.
4513
- */
4514
- function updateOrCreateInstallationEntry(oldEntry) {
4515
- const entry = oldEntry || {
4516
- fid: generateFid(),
4517
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
4518
- };
4519
- return clearTimedOutRequest(entry);
4520
- }
4521
- /**
4522
- * If the Firebase Installation is not registered yet, this will trigger the
4523
- * registration and return an InProgressInstallationEntry.
4524
- *
4525
- * If registrationPromise does not exist, the installationEntry is guaranteed
4526
- * to be registered.
4527
- */
4528
- function triggerRegistrationIfNecessary(installations, installationEntry) {
4529
- if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
4530
- if (!navigator.onLine) {
4531
- // Registration required but app is offline.
4532
- const registrationPromiseWithError = Promise.reject(ERROR_FACTORY$1.create("app-offline" /* ErrorCode.APP_OFFLINE */));
4533
- return {
4534
- installationEntry,
4535
- registrationPromise: registrationPromiseWithError
4536
- };
4537
- }
4538
- // Try registering. Change status to IN_PROGRESS.
4539
- const inProgressEntry = {
4540
- fid: installationEntry.fid,
4541
- registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,
4542
- registrationTime: Date.now()
4543
- };
4544
- const registrationPromise = registerInstallation(installations, inProgressEntry);
4545
- return { installationEntry: inProgressEntry, registrationPromise };
4546
- }
4547
- else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {
4548
- return {
4549
- installationEntry,
4550
- registrationPromise: waitUntilFidRegistration(installations)
4551
- };
4552
- }
4553
- else {
4554
- return { installationEntry };
4555
- }
4556
- }
4557
- /** This will be executed only once for each new Firebase Installation. */
4558
- async function registerInstallation(installations, installationEntry) {
4559
- try {
4560
- const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);
4561
- return set(installations.appConfig, registeredInstallationEntry);
4562
- }
4563
- catch (e) {
4564
- if (isServerError(e) && e.customData.serverCode === 409) {
4565
- // Server returned a "FID cannot be used" error.
4566
- // Generate a new ID next time.
4567
- await remove(installations.appConfig);
4568
- }
4569
- else {
4570
- // Registration failed. Set FID as not registered.
4571
- await set(installations.appConfig, {
4572
- fid: installationEntry.fid,
4573
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
4574
- });
4575
- }
4576
- throw e;
4577
- }
4578
- }
4579
- /** Call if FID registration is pending in another request. */
4580
- async function waitUntilFidRegistration(installations) {
4581
- // Unfortunately, there is no way of reliably observing when a value in
4582
- // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
4583
- // so we need to poll.
4584
- let entry = await updateInstallationRequest(installations.appConfig);
4585
- while (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {
4586
- // createInstallation request still in progress.
4587
- await sleep(100);
4588
- entry = await updateInstallationRequest(installations.appConfig);
4589
- }
4590
- if (entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
4591
- // The request timed out or failed in a different call. Try again.
4592
- const { installationEntry, registrationPromise } = await getInstallationEntry(installations);
4593
- if (registrationPromise) {
4594
- return registrationPromise;
4595
- }
4596
- else {
4597
- // if there is no registrationPromise, entry is registered.
4598
- return installationEntry;
4599
- }
4600
- }
4601
- return entry;
4602
- }
4603
- /**
4604
- * Called only if there is a CreateInstallation request in progress.
4605
- *
4606
- * Updates the InstallationEntry in the DB based on the status of the
4607
- * CreateInstallation request.
4608
- *
4609
- * Returns the updated InstallationEntry.
4610
- */
4611
- function updateInstallationRequest(appConfig) {
4612
- return update(appConfig, oldEntry => {
4613
- if (!oldEntry) {
4614
- throw ERROR_FACTORY$1.create("installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */);
4615
- }
4616
- return clearTimedOutRequest(oldEntry);
4617
- });
4618
- }
4619
- function clearTimedOutRequest(entry) {
4620
- if (hasInstallationRequestTimedOut(entry)) {
4621
- return {
4622
- fid: entry.fid,
4623
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
4624
- };
4625
- }
4626
- return entry;
4627
- }
4628
- function hasInstallationRequestTimedOut(installationEntry) {
4629
- return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
4630
- installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());
4631
- }
4632
-
4633
- /**
4634
- * @license
4635
- * Copyright 2019 Google LLC
4636
- *
4637
- * Licensed under the Apache License, Version 2.0 (the "License");
4638
- * you may not use this file except in compliance with the License.
4639
- * You may obtain a copy of the License at
4640
- *
4641
- * http://www.apache.org/licenses/LICENSE-2.0
4642
- *
4643
- * Unless required by applicable law or agreed to in writing, software
4644
- * distributed under the License is distributed on an "AS IS" BASIS,
4645
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4646
- * See the License for the specific language governing permissions and
4647
- * limitations under the License.
4648
- */
4649
- async function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {
4650
- const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);
4651
- const headers = getHeadersWithAuth(appConfig, installationEntry);
4652
- // If heartbeat service exists, add the heartbeat string to the header.
4653
- const heartbeatService = heartbeatServiceProvider.getImmediate({
4654
- optional: true
4655
- });
4656
- if (heartbeatService) {
4657
- const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
4658
- if (heartbeatsHeader) {
4659
- headers.append('x-firebase-client', heartbeatsHeader);
4660
- }
4661
- }
4662
- const body = {
4663
- installation: {
4664
- sdkVersion: PACKAGE_VERSION,
4665
- appId: appConfig.appId
4666
- }
4667
- };
4668
- const request = {
4669
- method: 'POST',
4670
- headers,
4671
- body: JSON.stringify(body)
4672
- };
4673
- const response = await retryIfServerError(() => fetch(endpoint, request));
4674
- if (response.ok) {
4675
- const responseValue = await response.json();
4676
- const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);
4677
- return completedAuthToken;
4678
- }
4679
- else {
4680
- throw await getErrorFromResponse('Generate Auth Token', response);
4681
- }
4682
- }
4683
- function getGenerateAuthTokenEndpoint(appConfig, { fid }) {
4684
- return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;
4685
- }
4686
-
4687
- /**
4688
- * @license
4689
- * Copyright 2019 Google LLC
4690
- *
4691
- * Licensed under the Apache License, Version 2.0 (the "License");
4692
- * you may not use this file except in compliance with the License.
4693
- * You may obtain a copy of the License at
4694
- *
4695
- * http://www.apache.org/licenses/LICENSE-2.0
4696
- *
4697
- * Unless required by applicable law or agreed to in writing, software
4698
- * distributed under the License is distributed on an "AS IS" BASIS,
4699
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4700
- * See the License for the specific language governing permissions and
4701
- * limitations under the License.
4702
- */
4703
- /**
4704
- * Returns a valid authentication token for the installation. Generates a new
4705
- * token if one doesn't exist, is expired or about to expire.
4706
- *
4707
- * Should only be called if the Firebase Installation is registered.
4708
- */
4709
- async function refreshAuthToken(installations, forceRefresh = false) {
4710
- let tokenPromise;
4711
- const entry = await update(installations.appConfig, oldEntry => {
4712
- if (!isEntryRegistered(oldEntry)) {
4713
- throw ERROR_FACTORY$1.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
4714
- }
4715
- const oldAuthToken = oldEntry.authToken;
4716
- if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {
4717
- // There is a valid token in the DB.
4718
- return oldEntry;
4719
- }
4720
- else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {
4721
- // There already is a token request in progress.
4722
- tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);
4723
- return oldEntry;
4724
- }
4725
- else {
4726
- // No token or token expired.
4727
- if (!navigator.onLine) {
4728
- throw ERROR_FACTORY$1.create("app-offline" /* ErrorCode.APP_OFFLINE */);
4729
- }
4730
- const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);
4731
- tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);
4732
- return inProgressEntry;
4733
- }
4734
- });
4735
- const authToken = tokenPromise
4736
- ? await tokenPromise
4737
- : entry.authToken;
4738
- return authToken;
4739
- }
4740
- /**
4741
- * Call only if FID is registered and Auth Token request is in progress.
4742
- *
4743
- * Waits until the current pending request finishes. If the request times out,
4744
- * tries once in this thread as well.
4745
- */
4746
- async function waitUntilAuthTokenRequest(installations, forceRefresh) {
4747
- // Unfortunately, there is no way of reliably observing when a value in
4748
- // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
4749
- // so we need to poll.
4750
- let entry = await updateAuthTokenRequest(installations.appConfig);
4751
- while (entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {
4752
- // generateAuthToken still in progress.
4753
- await sleep(100);
4754
- entry = await updateAuthTokenRequest(installations.appConfig);
4755
- }
4756
- const authToken = entry.authToken;
4757
- if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {
4758
- // The request timed out or failed in a different call. Try again.
4759
- return refreshAuthToken(installations, forceRefresh);
4760
- }
4761
- else {
4762
- return authToken;
4763
- }
4764
- }
4765
- /**
4766
- * Called only if there is a GenerateAuthToken request in progress.
4767
- *
4768
- * Updates the InstallationEntry in the DB based on the status of the
4769
- * GenerateAuthToken request.
4770
- *
4771
- * Returns the updated InstallationEntry.
4772
- */
4773
- function updateAuthTokenRequest(appConfig) {
4774
- return update(appConfig, oldEntry => {
4775
- if (!isEntryRegistered(oldEntry)) {
4776
- throw ERROR_FACTORY$1.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
4777
- }
4778
- const oldAuthToken = oldEntry.authToken;
4779
- if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
4780
- return {
4781
- ...oldEntry,
4782
- authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ }
4783
- };
4784
- }
4785
- return oldEntry;
4786
- });
4787
- }
4788
- async function fetchAuthTokenFromServer(installations, installationEntry) {
4789
- try {
4790
- const authToken = await generateAuthTokenRequest(installations, installationEntry);
4791
- const updatedInstallationEntry = {
4792
- ...installationEntry,
4793
- authToken
4794
- };
4795
- await set(installations.appConfig, updatedInstallationEntry);
4796
- return authToken;
4797
- }
4798
- catch (e) {
4799
- if (isServerError(e) &&
4800
- (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {
4801
- // Server returned a "FID not found" or a "Invalid authentication" error.
4802
- // Generate a new ID next time.
4803
- await remove(installations.appConfig);
4804
- }
4805
- else {
4806
- const updatedInstallationEntry = {
4807
- ...installationEntry,
4808
- authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ }
4809
- };
4810
- await set(installations.appConfig, updatedInstallationEntry);
4811
- }
4812
- throw e;
4813
- }
4814
- }
4815
- function isEntryRegistered(installationEntry) {
4816
- return (installationEntry !== undefined &&
4817
- installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);
4818
- }
4819
- function isAuthTokenValid(authToken) {
4820
- return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&
4821
- !isAuthTokenExpired(authToken));
4822
- }
4823
- function isAuthTokenExpired(authToken) {
4824
- const now = Date.now();
4825
- return (now < authToken.creationTime ||
4826
- authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);
4827
- }
4828
- /** Returns an updated InstallationEntry with an InProgressAuthToken. */
4829
- function makeAuthTokenRequestInProgressEntry(oldEntry) {
4830
- const inProgressAuthToken = {
4831
- requestStatus: 1 /* RequestStatus.IN_PROGRESS */,
4832
- requestTime: Date.now()
4833
- };
4834
- return {
4835
- ...oldEntry,
4836
- authToken: inProgressAuthToken
4837
- };
4838
- }
4839
- function hasAuthTokenRequestTimedOut(authToken) {
4840
- return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
4841
- authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());
4842
- }
4843
-
4844
- /**
4845
- * @license
4846
- * Copyright 2019 Google LLC
4847
- *
4848
- * Licensed under the Apache License, Version 2.0 (the "License");
4849
- * you may not use this file except in compliance with the License.
4850
- * You may obtain a copy of the License at
4851
- *
4852
- * http://www.apache.org/licenses/LICENSE-2.0
4853
- *
4854
- * Unless required by applicable law or agreed to in writing, software
4855
- * distributed under the License is distributed on an "AS IS" BASIS,
4856
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4857
- * See the License for the specific language governing permissions and
4858
- * limitations under the License.
4859
- */
4860
- /**
4861
- * Creates a Firebase Installation if there isn't one for the app and
4862
- * returns the Installation ID.
4863
- * @param installations - The `Installations` instance.
4864
- *
4865
- * @public
4866
- */
4867
- async function getId(installations) {
4868
- const installationsImpl = installations;
4869
- const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);
4870
- if (registrationPromise) {
4871
- registrationPromise.catch(console.error);
4872
- }
4873
- else {
4874
- // If the installation is already registered, update the authentication
4875
- // token if needed.
4876
- refreshAuthToken(installationsImpl).catch(console.error);
4877
- }
4878
- return installationEntry.fid;
4879
- }
4880
-
4881
- /**
4882
- * @license
4883
- * Copyright 2019 Google LLC
4884
- *
4885
- * Licensed under the Apache License, Version 2.0 (the "License");
4886
- * you may not use this file except in compliance with the License.
4887
- * You may obtain a copy of the License at
4888
- *
4889
- * http://www.apache.org/licenses/LICENSE-2.0
4890
- *
4891
- * Unless required by applicable law or agreed to in writing, software
4892
- * distributed under the License is distributed on an "AS IS" BASIS,
4893
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4894
- * See the License for the specific language governing permissions and
4895
- * limitations under the License.
4896
- */
4897
- /**
4898
- * Returns a Firebase Installations auth token, identifying the current
4899
- * Firebase Installation.
4900
- * @param installations - The `Installations` instance.
4901
- * @param forceRefresh - Force refresh regardless of token expiration.
4902
- *
4903
- * @public
4904
- */
4905
- async function getToken$2(installations, forceRefresh = false) {
4906
- const installationsImpl = installations;
4907
- await completeInstallationRegistration(installationsImpl);
4908
- // At this point we either have a Registered Installation in the DB, or we've
4909
- // already thrown an error.
4910
- const authToken = await refreshAuthToken(installationsImpl, forceRefresh);
4911
- return authToken.token;
4912
- }
4913
- async function completeInstallationRegistration(installations) {
4914
- const { registrationPromise } = await getInstallationEntry(installations);
4915
- if (registrationPromise) {
4916
- // A createInstallation request is in progress. Wait until it finishes.
4917
- await registrationPromise;
4918
- }
4919
- }
4920
-
4921
- /**
4922
- * @license
4923
- * Copyright 2019 Google LLC
4924
- *
4925
- * Licensed under the Apache License, Version 2.0 (the "License");
4926
- * you may not use this file except in compliance with the License.
4927
- * You may obtain a copy of the License at
4928
- *
4929
- * http://www.apache.org/licenses/LICENSE-2.0
4930
- *
4931
- * Unless required by applicable law or agreed to in writing, software
4932
- * distributed under the License is distributed on an "AS IS" BASIS,
4933
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4934
- * See the License for the specific language governing permissions and
4935
- * limitations under the License.
4936
- */
4937
- function extractAppConfig$1(app) {
4938
- if (!app || !app.options) {
4939
- throw getMissingValueError$1('App Configuration');
4940
- }
4941
- if (!app.name) {
4942
- throw getMissingValueError$1('App Name');
4943
- }
4944
- // Required app config keys
4945
- const configKeys = [
4946
- 'projectId',
4947
- 'apiKey',
4948
- 'appId'
4949
- ];
4950
- for (const keyName of configKeys) {
4951
- if (!app.options[keyName]) {
4952
- throw getMissingValueError$1(keyName);
4953
- }
4954
- }
4955
- return {
4956
- appName: app.name,
4957
- projectId: app.options.projectId,
4958
- apiKey: app.options.apiKey,
4959
- appId: app.options.appId
4960
- };
4961
- }
4962
- function getMissingValueError$1(valueName) {
4963
- return ERROR_FACTORY$1.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
4964
- valueName
4965
- });
4966
- }
4967
-
4968
- /**
4969
- * @license
4970
- * Copyright 2020 Google LLC
4971
- *
4972
- * Licensed under the Apache License, Version 2.0 (the "License");
4973
- * you may not use this file except in compliance with the License.
4974
- * You may obtain a copy of the License at
4975
- *
4976
- * http://www.apache.org/licenses/LICENSE-2.0
4977
- *
4978
- * Unless required by applicable law or agreed to in writing, software
4979
- * distributed under the License is distributed on an "AS IS" BASIS,
4980
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4981
- * See the License for the specific language governing permissions and
4982
- * limitations under the License.
4983
- */
4984
- const INSTALLATIONS_NAME = 'installations';
4985
- const INSTALLATIONS_NAME_INTERNAL = 'installations-internal';
4986
- const publicFactory = (container) => {
4987
- const app = container.getProvider('app').getImmediate();
4988
- // Throws if app isn't configured properly.
4989
- const appConfig = extractAppConfig$1(app);
4990
- const heartbeatServiceProvider = _getProvider(app, 'heartbeat');
4991
- const installationsImpl = {
4992
- app,
4993
- appConfig,
4994
- heartbeatServiceProvider,
4995
- _delete: () => Promise.resolve()
4996
- };
4997
- return installationsImpl;
4998
- };
4999
- const internalFactory = (container) => {
5000
- const app = container.getProvider('app').getImmediate();
5001
- // Internal FIS instance relies on public FIS instance.
5002
- const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();
5003
- const installationsInternal = {
5004
- getId: () => getId(installations),
5005
- getToken: (forceRefresh) => getToken$2(installations, forceRefresh)
5006
- };
5007
- return installationsInternal;
5008
- };
5009
- function registerInstallations() {
5010
- _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, "PUBLIC" /* ComponentType.PUBLIC */));
5011
- _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
5012
- }
5013
-
5014
- /**
5015
- * The Firebase Installations Web SDK.
5016
- * This SDK does not work in a Node.js environment.
5017
- *
5018
- * @packageDocumentation
5019
- */
5020
- registerInstallations();
5021
- registerVersion(name$1, version$1);
5022
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
5023
- registerVersion(name$1, version$1, 'esm2020');
5024
-
5025
- /**
5026
- * @license
5027
- * Copyright 2019 Google LLC
5028
- *
5029
- * Licensed under the Apache License, Version 2.0 (the "License");
5030
- * you may not use this file except in compliance with the License.
5031
- * You may obtain a copy of the License at
5032
- *
5033
- * http://www.apache.org/licenses/LICENSE-2.0
5034
- *
5035
- * Unless required by applicable law or agreed to in writing, software
5036
- * distributed under the License is distributed on an "AS IS" BASIS,
5037
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5038
- * See the License for the specific language governing permissions and
5039
- * limitations under the License.
5040
- */
5041
- const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';
5042
- const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';
5043
- const DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';
5044
- const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';
5045
- const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';
5046
- const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';
5047
- const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';
5048
- /** Set to '1' if Analytics is enabled for the campaign */
5049
- const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';
5050
- const DEFAULT_REGISTRATION_TIMEOUT = 10000;
5051
- var MessageType$1;
5052
- (function (MessageType) {
5053
- MessageType[MessageType["DATA_MESSAGE"] = 1] = "DATA_MESSAGE";
5054
- MessageType[MessageType["DISPLAY_NOTIFICATION"] = 3] = "DISPLAY_NOTIFICATION";
5055
- })(MessageType$1 || (MessageType$1 = {}));
5056
-
5057
- /**
5058
- * @license
5059
- * Copyright 2018 Google LLC
5060
- *
5061
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5062
- * in compliance with the License. You may obtain a copy of the License at
5063
- *
5064
- * http://www.apache.org/licenses/LICENSE-2.0
5065
- *
5066
- * Unless required by applicable law or agreed to in writing, software distributed under the License
5067
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
5068
- * or implied. See the License for the specific language governing permissions and limitations under
5069
- * the License.
5070
- */
5071
- var MessageType;
5072
- (function (MessageType) {
5073
- MessageType["PUSH_RECEIVED"] = "push-received";
5074
- MessageType["NOTIFICATION_CLICKED"] = "notification-clicked";
5075
- })(MessageType || (MessageType = {}));
5076
-
5077
- /**
5078
- * @license
5079
- * Copyright 2017 Google LLC
5080
- *
5081
- * Licensed under the Apache License, Version 2.0 (the "License");
5082
- * you may not use this file except in compliance with the License.
5083
- * You may obtain a copy of the License at
5084
- *
5085
- * http://www.apache.org/licenses/LICENSE-2.0
5086
- *
5087
- * Unless required by applicable law or agreed to in writing, software
5088
- * distributed under the License is distributed on an "AS IS" BASIS,
5089
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5090
- * See the License for the specific language governing permissions and
5091
- * limitations under the License.
5092
- */
5093
- function arrayToBase64(array) {
5094
- const uint8Array = new Uint8Array(array);
5095
- const base64String = btoa(String.fromCharCode(...uint8Array));
5096
- return base64String.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
5097
- }
5098
- function base64ToArray(base64String) {
5099
- const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
5100
- const base64 = (base64String + padding)
5101
- .replace(/\-/g, '+')
5102
- .replace(/_/g, '/');
5103
- const rawData = atob(base64);
5104
- const outputArray = new Uint8Array(rawData.length);
5105
- for (let i = 0; i < rawData.length; ++i) {
5106
- outputArray[i] = rawData.charCodeAt(i);
5107
- }
5108
- return outputArray;
5109
- }
5110
-
5111
- /**
5112
- * @license
5113
- * Copyright 2019 Google LLC
5114
- *
5115
- * Licensed under the Apache License, Version 2.0 (the "License");
5116
- * you may not use this file except in compliance with the License.
5117
- * You may obtain a copy of the License at
5118
- *
5119
- * http://www.apache.org/licenses/LICENSE-2.0
5120
- *
5121
- * Unless required by applicable law or agreed to in writing, software
5122
- * distributed under the License is distributed on an "AS IS" BASIS,
5123
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5124
- * See the License for the specific language governing permissions and
5125
- * limitations under the License.
5126
- */
5127
- const OLD_DB_NAME = 'fcm_token_details_db';
5128
- /**
5129
- * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade
5130
- * callback is called for all versions of the old DB.
5131
- */
5132
- const OLD_DB_VERSION = 5;
5133
- const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';
5134
- async function migrateOldDatabase(senderId) {
5135
- if ('databases' in indexedDB) {
5136
- // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove
5137
- // typecast when it lands in TS types.
5138
- const databases = await indexedDB.databases();
5139
- const dbNames = databases.map(db => db.name);
5140
- if (!dbNames.includes(OLD_DB_NAME)) {
5141
- // old DB didn't exist, no need to open.
5142
- return null;
5143
- }
5144
- }
5145
- let tokenDetails = null;
5146
- const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {
5147
- upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {
5148
- if (oldVersion < 2) {
5149
- // Database too old, skip migration.
5150
- return;
5151
- }
5152
- if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
5153
- // Database did not exist. Nothing to do.
5154
- return;
5155
- }
5156
- const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);
5157
- const value = await objectStore.index('fcmSenderId').get(senderId);
5158
- await objectStore.clear();
5159
- if (!value) {
5160
- // No entry in the database, nothing to migrate.
5161
- return;
5162
- }
5163
- if (oldVersion === 2) {
5164
- const oldDetails = value;
5165
- if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {
5166
- return;
5167
- }
5168
- tokenDetails = {
5169
- token: oldDetails.fcmToken,
5170
- createTime: oldDetails.createTime ?? Date.now(),
5171
- subscriptionOptions: {
5172
- auth: oldDetails.auth,
5173
- p256dh: oldDetails.p256dh,
5174
- endpoint: oldDetails.endpoint,
5175
- swScope: oldDetails.swScope,
5176
- vapidKey: typeof oldDetails.vapidKey === 'string'
5177
- ? oldDetails.vapidKey
5178
- : arrayToBase64(oldDetails.vapidKey)
5179
- }
5180
- };
5181
- }
5182
- else if (oldVersion === 3) {
5183
- const oldDetails = value;
5184
- tokenDetails = {
5185
- token: oldDetails.fcmToken,
5186
- createTime: oldDetails.createTime,
5187
- subscriptionOptions: {
5188
- auth: arrayToBase64(oldDetails.auth),
5189
- p256dh: arrayToBase64(oldDetails.p256dh),
5190
- endpoint: oldDetails.endpoint,
5191
- swScope: oldDetails.swScope,
5192
- vapidKey: arrayToBase64(oldDetails.vapidKey)
5193
- }
5194
- };
5195
- }
5196
- else if (oldVersion === 4) {
5197
- const oldDetails = value;
5198
- tokenDetails = {
5199
- token: oldDetails.fcmToken,
5200
- createTime: oldDetails.createTime,
5201
- subscriptionOptions: {
5202
- auth: arrayToBase64(oldDetails.auth),
5203
- p256dh: arrayToBase64(oldDetails.p256dh),
5204
- endpoint: oldDetails.endpoint,
5205
- swScope: oldDetails.swScope,
5206
- vapidKey: arrayToBase64(oldDetails.vapidKey)
5207
- }
5208
- };
5209
- }
5210
- }
5211
- });
5212
- db.close();
5213
- // Delete all old databases.
5214
- await deleteDB(OLD_DB_NAME);
5215
- await deleteDB('fcm_vapid_details_db');
5216
- await deleteDB('undefined');
5217
- return checkTokenDetails(tokenDetails) ? tokenDetails : null;
5218
- }
5219
- function checkTokenDetails(tokenDetails) {
5220
- if (!tokenDetails || !tokenDetails.subscriptionOptions) {
5221
- return false;
5222
- }
5223
- const { subscriptionOptions } = tokenDetails;
5224
- return (typeof tokenDetails.createTime === 'number' &&
5225
- tokenDetails.createTime > 0 &&
5226
- typeof tokenDetails.token === 'string' &&
5227
- tokenDetails.token.length > 0 &&
5228
- typeof subscriptionOptions.auth === 'string' &&
5229
- subscriptionOptions.auth.length > 0 &&
5230
- typeof subscriptionOptions.p256dh === 'string' &&
5231
- subscriptionOptions.p256dh.length > 0 &&
5232
- typeof subscriptionOptions.endpoint === 'string' &&
5233
- subscriptionOptions.endpoint.length > 0 &&
5234
- typeof subscriptionOptions.swScope === 'string' &&
5235
- subscriptionOptions.swScope.length > 0 &&
5236
- typeof subscriptionOptions.vapidKey === 'string' &&
5237
- subscriptionOptions.vapidKey.length > 0);
5238
- }
5239
-
5240
- /**
5241
- * @license
5242
- * Copyright 2019 Google LLC
5243
- *
5244
- * Licensed under the Apache License, Version 2.0 (the "License");
5245
- * you may not use this file except in compliance with the License.
5246
- * You may obtain a copy of the License at
5247
- *
5248
- * http://www.apache.org/licenses/LICENSE-2.0
5249
- *
5250
- * Unless required by applicable law or agreed to in writing, software
5251
- * distributed under the License is distributed on an "AS IS" BASIS,
5252
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5253
- * See the License for the specific language governing permissions and
5254
- * limitations under the License.
5255
- */
5256
- // Exported for tests.
5257
- const DATABASE_NAME = 'firebase-messaging-database';
5258
- const DATABASE_VERSION = 1;
5259
- const OBJECT_STORE_NAME = 'firebase-messaging-store';
5260
- let dbPromise = null;
5261
- function getDbPromise() {
5262
- if (!dbPromise) {
5263
- dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {
5264
- upgrade: (upgradeDb, oldVersion) => {
5265
- // We don't use 'break' in this switch statement, the fall-through behavior is what we want,
5266
- // because if there are multiple versions between the old version and the current version, we
5267
- // want ALL the migrations that correspond to those versions to run, not only the last one.
5268
- // eslint-disable-next-line default-case
5269
- switch (oldVersion) {
5270
- case 0:
5271
- upgradeDb.createObjectStore(OBJECT_STORE_NAME);
5272
- }
5273
- }
5274
- });
5275
- }
5276
- return dbPromise;
5277
- }
5278
- /** Gets record(s) from the objectStore that match the given key. */
5279
- async function dbGet(firebaseDependencies) {
5280
- const key = getKey(firebaseDependencies);
5281
- const db = await getDbPromise();
5282
- const tokenDetails = (await db
5283
- .transaction(OBJECT_STORE_NAME)
5284
- .objectStore(OBJECT_STORE_NAME)
5285
- .get(key));
5286
- if (tokenDetails) {
5287
- return tokenDetails;
5288
- }
5289
- else {
5290
- // Check if there is a tokenDetails object in the old DB.
5291
- const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);
5292
- if (oldTokenDetails) {
5293
- await dbSet(firebaseDependencies, oldTokenDetails);
5294
- return oldTokenDetails;
5295
- }
5296
- }
5297
- }
5298
- /** Assigns or overwrites the record for the given key with the given value. */
5299
- async function dbSet(firebaseDependencies, tokenDetails) {
5300
- const key = getKey(firebaseDependencies);
5301
- const db = await getDbPromise();
5302
- const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
5303
- await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);
5304
- await tx.done;
5305
- return tokenDetails;
5306
- }
5307
- function getKey({ appConfig }) {
5308
- return appConfig.appId;
5309
- }
5310
-
5311
- /**
5312
- * @license
5313
- * Copyright 2017 Google LLC
5314
- *
5315
- * Licensed under the Apache License, Version 2.0 (the "License");
5316
- * you may not use this file except in compliance with the License.
5317
- * You may obtain a copy of the License at
5318
- *
5319
- * http://www.apache.org/licenses/LICENSE-2.0
5320
- *
5321
- * Unless required by applicable law or agreed to in writing, software
5322
- * distributed under the License is distributed on an "AS IS" BASIS,
5323
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5324
- * See the License for the specific language governing permissions and
5325
- * limitations under the License.
5326
- */
5327
- const ERROR_MAP = {
5328
- ["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
5329
- ["only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',
5330
- ["only-available-in-sw" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',
5331
- ["permission-default" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',
5332
- ["permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',
5333
- ["unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */]: "This browser doesn't support the API's required to use the Firebase SDK.",
5334
- ["indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: "This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)",
5335
- ["failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',
5336
- ["token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',
5337
- ["token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',
5338
- ["token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +
5339
- 'user from FCM: {$errorInfo}',
5340
- ["token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',
5341
- ["token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',
5342
- ["use-sw-after-get-token" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +
5343
- 'called before calling getToken() to ensure your service worker is used.',
5344
- ["invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',
5345
- ["invalid-bg-handler" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',
5346
- ["invalid-vapid-key" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',
5347
- ["use-vapid-key-after-get-token" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +
5348
- 'called before calling getToken() to ensure your VAPID key is used.'
5349
- };
5350
- const ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);
5351
-
5352
- /**
5353
- * @license
5354
- * Copyright 2019 Google LLC
5355
- *
5356
- * Licensed under the Apache License, Version 2.0 (the "License");
5357
- * you may not use this file except in compliance with the License.
5358
- * You may obtain a copy of the License at
5359
- *
5360
- * http://www.apache.org/licenses/LICENSE-2.0
5361
- *
5362
- * Unless required by applicable law or agreed to in writing, software
5363
- * distributed under the License is distributed on an "AS IS" BASIS,
5364
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5365
- * See the License for the specific language governing permissions and
5366
- * limitations under the License.
5367
- */
5368
- async function requestGetToken(firebaseDependencies, subscriptionOptions) {
5369
- const headers = await getHeaders(firebaseDependencies);
5370
- const body = getBody(subscriptionOptions);
5371
- const subscribeOptions = {
5372
- method: 'POST',
5373
- headers,
5374
- body: JSON.stringify(body)
5375
- };
5376
- let responseData;
5377
- try {
5378
- const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);
5379
- responseData = await response.json();
5380
- }
5381
- catch (err) {
5382
- throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
5383
- errorInfo: err?.toString()
5384
- });
5385
- }
5386
- if (responseData.error) {
5387
- const message = responseData.error.message;
5388
- throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
5389
- errorInfo: message
5390
- });
5391
- }
5392
- if (!responseData.token) {
5393
- throw ERROR_FACTORY.create("token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);
5394
- }
5395
- return responseData.token;
5396
- }
5397
- async function requestUpdateToken(firebaseDependencies, tokenDetails) {
5398
- const headers = await getHeaders(firebaseDependencies);
5399
- const body = getBody(tokenDetails.subscriptionOptions);
5400
- const updateOptions = {
5401
- method: 'PATCH',
5402
- headers,
5403
- body: JSON.stringify(body)
5404
- };
5405
- let responseData;
5406
- try {
5407
- const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);
5408
- responseData = await response.json();
5409
- }
5410
- catch (err) {
5411
- throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
5412
- errorInfo: err?.toString()
5413
- });
5414
- }
5415
- if (responseData.error) {
5416
- const message = responseData.error.message;
5417
- throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
5418
- errorInfo: message
5419
- });
5420
- }
5421
- if (!responseData.token) {
5422
- throw ERROR_FACTORY.create("token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);
5423
- }
5424
- return responseData.token;
5425
- }
5426
- async function requestDeleteToken(firebaseDependencies, token) {
5427
- const headers = await getHeaders(firebaseDependencies);
5428
- const unsubscribeOptions = {
5429
- method: 'DELETE',
5430
- headers
5431
- };
5432
- try {
5433
- const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);
5434
- const responseData = await response.json();
5435
- if (responseData.error) {
5436
- const message = responseData.error.message;
5437
- throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
5438
- errorInfo: message
5439
- });
5440
- }
5441
- }
5442
- catch (err) {
5443
- throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
5444
- errorInfo: err?.toString()
5445
- });
5446
- }
5447
- }
5448
- function getEndpoint({ projectId }) {
5449
- return `${ENDPOINT}/projects/${projectId}/registrations`;
5450
- }
5451
- async function getHeaders({ appConfig, installations }) {
5452
- const authToken = await installations.getToken();
5453
- return new Headers({
5454
- 'Content-Type': 'application/json',
5455
- Accept: 'application/json',
5456
- 'x-goog-api-key': appConfig.apiKey,
5457
- 'x-goog-firebase-installations-auth': `FIS ${authToken}`
5458
- });
5459
- }
5460
- function getBody({ p256dh, auth, endpoint, vapidKey }) {
5461
- const body = {
5462
- web: {
5463
- endpoint,
5464
- auth,
5465
- p256dh
5466
- }
5467
- };
5468
- if (vapidKey !== DEFAULT_VAPID_KEY) {
5469
- body.web.applicationPubKey = vapidKey;
5470
- }
5471
- return body;
5472
- }
5473
-
5474
- /**
5475
- * @license
5476
- * Copyright 2019 Google LLC
5477
- *
5478
- * Licensed under the Apache License, Version 2.0 (the "License");
5479
- * you may not use this file except in compliance with the License.
5480
- * You may obtain a copy of the License at
5481
- *
5482
- * http://www.apache.org/licenses/LICENSE-2.0
5483
- *
5484
- * Unless required by applicable law or agreed to in writing, software
5485
- * distributed under the License is distributed on an "AS IS" BASIS,
5486
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5487
- * See the License for the specific language governing permissions and
5488
- * limitations under the License.
5489
- */
5490
- // UpdateRegistration will be called once every week.
5491
- const TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
5492
- async function getTokenInternal(messaging) {
5493
- const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);
5494
- const subscriptionOptions = {
5495
- vapidKey: messaging.vapidKey,
5496
- swScope: messaging.swRegistration.scope,
5497
- endpoint: pushSubscription.endpoint,
5498
- auth: arrayToBase64(pushSubscription.getKey('auth')),
5499
- p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))
5500
- };
5501
- const tokenDetails = await dbGet(messaging.firebaseDependencies);
5502
- if (!tokenDetails) {
5503
- // No token, get a new one.
5504
- return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
5505
- }
5506
- else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {
5507
- // Invalid token, get a new one.
5508
- try {
5509
- await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);
5510
- }
5511
- catch (e) {
5512
- // Suppress errors because of #2364
5513
- console.warn(e);
5514
- }
5515
- return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
5516
- }
5517
- else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {
5518
- // Weekly token refresh
5519
- return updateToken(messaging, {
5520
- token: tokenDetails.token,
5521
- createTime: Date.now(),
5522
- subscriptionOptions
5523
- });
5524
- }
5525
- else {
5526
- // Valid token, nothing to do.
5527
- return tokenDetails.token;
5528
- }
5529
- }
5530
- async function updateToken(messaging, tokenDetails) {
5531
- try {
5532
- const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);
5533
- const updatedTokenDetails = {
5534
- ...tokenDetails,
5535
- token: updatedToken,
5536
- createTime: Date.now()
5537
- };
5538
- await dbSet(messaging.firebaseDependencies, updatedTokenDetails);
5539
- return updatedToken;
5540
- }
5541
- catch (e) {
5542
- throw e;
5543
- }
5544
- }
5545
- async function getNewToken(firebaseDependencies, subscriptionOptions) {
5546
- const token = await requestGetToken(firebaseDependencies, subscriptionOptions);
5547
- const tokenDetails = {
5548
- token,
5549
- createTime: Date.now(),
5550
- subscriptionOptions
5551
- };
5552
- await dbSet(firebaseDependencies, tokenDetails);
5553
- return tokenDetails.token;
5554
- }
5555
- /**
5556
- * Gets a PushSubscription for the current user.
5557
- */
5558
- async function getPushSubscription(swRegistration, vapidKey) {
5559
- const subscription = await swRegistration.pushManager.getSubscription();
5560
- if (subscription) {
5561
- return subscription;
5562
- }
5563
- return swRegistration.pushManager.subscribe({
5564
- userVisibleOnly: true,
5565
- // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key
5566
- // submitted to pushManager#subscribe must be of type Uint8Array.
5567
- applicationServerKey: base64ToArray(vapidKey)
5568
- });
5569
- }
5570
- /**
5571
- * Checks if the saved tokenDetails object matches the configuration provided.
5572
- */
5573
- function isTokenValid(dbOptions, currentOptions) {
5574
- const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;
5575
- const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;
5576
- const isAuthEqual = currentOptions.auth === dbOptions.auth;
5577
- const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;
5578
- return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;
5579
- }
5580
-
5581
- /**
5582
- * @license
5583
- * Copyright 2020 Google LLC
5584
- *
5585
- * Licensed under the Apache License, Version 2.0 (the "License");
5586
- * you may not use this file except in compliance with the License.
5587
- * You may obtain a copy of the License at
5588
- *
5589
- * http://www.apache.org/licenses/LICENSE-2.0
5590
- *
5591
- * Unless required by applicable law or agreed to in writing, software
5592
- * distributed under the License is distributed on an "AS IS" BASIS,
5593
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5594
- * See the License for the specific language governing permissions and
5595
- * limitations under the License.
5596
- */
5597
- function externalizePayload(internalPayload) {
5598
- const payload = {
5599
- from: internalPayload.from,
5600
- // eslint-disable-next-line camelcase
5601
- collapseKey: internalPayload.collapse_key,
5602
- // eslint-disable-next-line camelcase
5603
- messageId: internalPayload.fcmMessageId
5604
- };
5605
- propagateNotificationPayload(payload, internalPayload);
5606
- propagateDataPayload(payload, internalPayload);
5607
- propagateFcmOptions(payload, internalPayload);
5608
- return payload;
5609
- }
5610
- function propagateNotificationPayload(payload, messagePayloadInternal) {
5611
- if (!messagePayloadInternal.notification) {
5612
- return;
5613
- }
5614
- payload.notification = {};
5615
- const title = messagePayloadInternal.notification.title;
5616
- if (!!title) {
5617
- payload.notification.title = title;
5618
- }
5619
- const body = messagePayloadInternal.notification.body;
5620
- if (!!body) {
5621
- payload.notification.body = body;
5622
- }
5623
- const image = messagePayloadInternal.notification.image;
5624
- if (!!image) {
5625
- payload.notification.image = image;
5626
- }
5627
- const icon = messagePayloadInternal.notification.icon;
5628
- if (!!icon) {
5629
- payload.notification.icon = icon;
5630
- }
5631
- }
5632
- function propagateDataPayload(payload, messagePayloadInternal) {
5633
- if (!messagePayloadInternal.data) {
5634
- return;
5635
- }
5636
- payload.data = messagePayloadInternal.data;
5637
- }
5638
- function propagateFcmOptions(payload, messagePayloadInternal) {
5639
- // fcmOptions.link value is written into notification.click_action. see more in b/232072111
5640
- if (!messagePayloadInternal.fcmOptions &&
5641
- !messagePayloadInternal.notification?.click_action) {
5642
- return;
5643
- }
5644
- payload.fcmOptions = {};
5645
- const link = messagePayloadInternal.fcmOptions?.link ??
5646
- messagePayloadInternal.notification?.click_action;
5647
- if (!!link) {
5648
- payload.fcmOptions.link = link;
5649
- }
5650
- // eslint-disable-next-line camelcase
5651
- const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;
5652
- if (!!analyticsLabel) {
5653
- payload.fcmOptions.analyticsLabel = analyticsLabel;
5654
- }
5655
- }
5656
-
5657
- /**
5658
- * @license
5659
- * Copyright 2019 Google LLC
5660
- *
5661
- * Licensed under the Apache License, Version 2.0 (the "License");
5662
- * you may not use this file except in compliance with the License.
5663
- * You may obtain a copy of the License at
5664
- *
5665
- * http://www.apache.org/licenses/LICENSE-2.0
5666
- *
5667
- * Unless required by applicable law or agreed to in writing, software
5668
- * distributed under the License is distributed on an "AS IS" BASIS,
5669
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5670
- * See the License for the specific language governing permissions and
5671
- * limitations under the License.
5672
- */
5673
- function isConsoleMessage(data) {
5674
- // This message has a campaign ID, meaning it was sent using the Firebase Console.
5675
- return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;
5676
- }
5677
-
5678
- /**
5679
- * @license
5680
- * Copyright 2019 Google LLC
5681
- *
5682
- * Licensed under the Apache License, Version 2.0 (the "License");
5683
- * you may not use this file except in compliance with the License.
5684
- * You may obtain a copy of the License at
5685
- *
5686
- * http://www.apache.org/licenses/LICENSE-2.0
5687
- *
5688
- * Unless required by applicable law or agreed to in writing, software
5689
- * distributed under the License is distributed on an "AS IS" BASIS,
5690
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5691
- * See the License for the specific language governing permissions and
5692
- * limitations under the License.
5693
- */
5694
- _mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');
5695
- function _mergeStrings(s1, s2) {
5696
- const resultArray = [];
5697
- for (let i = 0; i < s1.length; i++) {
5698
- resultArray.push(s1.charAt(i));
5699
- if (i < s2.length) {
5700
- resultArray.push(s2.charAt(i));
5701
- }
5702
- }
5703
- return resultArray.join('');
5704
- }
5705
-
5706
- /**
5707
- * @license
5708
- * Copyright 2019 Google LLC
5709
- *
5710
- * Licensed under the Apache License, Version 2.0 (the "License");
5711
- * you may not use this file except in compliance with the License.
5712
- * You may obtain a copy of the License at
5713
- *
5714
- * http://www.apache.org/licenses/LICENSE-2.0
5715
- *
5716
- * Unless required by applicable law or agreed to in writing, software
5717
- * distributed under the License is distributed on an "AS IS" BASIS,
5718
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5719
- * See the License for the specific language governing permissions and
5720
- * limitations under the License.
5721
- */
5722
- function extractAppConfig(app) {
5723
- if (!app || !app.options) {
5724
- throw getMissingValueError('App Configuration Object');
5725
- }
5726
- if (!app.name) {
5727
- throw getMissingValueError('App Name');
5728
- }
5729
- // Required app config keys
5730
- const configKeys = [
5731
- 'projectId',
5732
- 'apiKey',
5733
- 'appId',
5734
- 'messagingSenderId'
5735
- ];
5736
- const { options } = app;
5737
- for (const keyName of configKeys) {
5738
- if (!options[keyName]) {
5739
- throw getMissingValueError(keyName);
5740
- }
5741
- }
5742
- return {
5743
- appName: app.name,
5744
- projectId: options.projectId,
5745
- apiKey: options.apiKey,
5746
- appId: options.appId,
5747
- senderId: options.messagingSenderId
5748
- };
5749
- }
5750
- function getMissingValueError(valueName) {
5751
- return ERROR_FACTORY.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
5752
- valueName
5753
- });
5754
- }
5755
-
5756
- /**
5757
- * @license
5758
- * Copyright 2020 Google LLC
5759
- *
5760
- * Licensed under the Apache License, Version 2.0 (the "License");
5761
- * you may not use this file except in compliance with the License.
5762
- * You may obtain a copy of the License at
5763
- *
5764
- * http://www.apache.org/licenses/LICENSE-2.0
5765
- *
5766
- * Unless required by applicable law or agreed to in writing, software
5767
- * distributed under the License is distributed on an "AS IS" BASIS,
5768
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5769
- * See the License for the specific language governing permissions and
5770
- * limitations under the License.
5771
- */
5772
- class MessagingService {
5773
- constructor(app, installations, analyticsProvider) {
5774
- // logging is only done with end user consent. Default to false.
5775
- this.deliveryMetricsExportedToBigQueryEnabled = false;
5776
- this.onBackgroundMessageHandler = null;
5777
- this.onMessageHandler = null;
5778
- this.logEvents = [];
5779
- this.isLogServiceStarted = false;
5780
- const appConfig = extractAppConfig(app);
5781
- this.firebaseDependencies = {
5782
- app,
5783
- appConfig,
5784
- installations,
5785
- analyticsProvider
5786
- };
5787
- }
5788
- _delete() {
5789
- return Promise.resolve();
5790
- }
5791
- }
5792
-
5793
- /**
5794
- * @license
5795
- * Copyright 2020 Google LLC
5796
- *
5797
- * Licensed under the Apache License, Version 2.0 (the "License");
5798
- * you may not use this file except in compliance with the License.
5799
- * You may obtain a copy of the License at
5800
- *
5801
- * http://www.apache.org/licenses/LICENSE-2.0
5802
- *
5803
- * Unless required by applicable law or agreed to in writing, software
5804
- * distributed under the License is distributed on an "AS IS" BASIS,
5805
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5806
- * See the License for the specific language governing permissions and
5807
- * limitations under the License.
5808
- */
5809
- async function registerDefaultSw(messaging) {
5810
- try {
5811
- messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {
5812
- scope: DEFAULT_SW_SCOPE
5813
- });
5814
- // The timing when browser updates sw when sw has an update is unreliable from experiment. It
5815
- // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw
5816
- // is stuck with the old version. For example,
5817
- // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates
5818
- // sw if there was an update.
5819
- messaging.swRegistration.update().catch(() => {
5820
- /* it is non blocking and we don't care if it failed */
5821
- });
5822
- await waitForRegistrationActive(messaging.swRegistration);
5823
- }
5824
- catch (e) {
5825
- throw ERROR_FACTORY.create("failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {
5826
- browserErrorMessage: e?.message
5827
- });
5828
- }
5829
- }
5830
- /**
5831
- * Waits for registration to become active. MDN documentation claims that
5832
- * a service worker registration should be ready to use after awaiting
5833
- * navigator.serviceWorker.register() but that doesn't seem to be the case in
5834
- * practice, causing the SDK to throw errors when calling
5835
- * swRegistration.pushManager.subscribe() too soon after register(). The only
5836
- * solution seems to be waiting for the service worker registration `state`
5837
- * to become "active".
5838
- */
5839
- async function waitForRegistrationActive(registration) {
5840
- return new Promise((resolve, reject) => {
5841
- const rejectTimeout = setTimeout(() => reject(new Error(`Service worker not registered after ${DEFAULT_REGISTRATION_TIMEOUT} ms`)), DEFAULT_REGISTRATION_TIMEOUT);
5842
- const incomingSw = registration.installing || registration.waiting;
5843
- if (registration.active) {
5844
- clearTimeout(rejectTimeout);
5845
- resolve();
5846
- }
5847
- else if (incomingSw) {
5848
- incomingSw.onstatechange = ev => {
5849
- if (ev.target?.state === 'activated') {
5850
- incomingSw.onstatechange = null;
5851
- clearTimeout(rejectTimeout);
5852
- resolve();
5853
- }
5854
- };
5855
- }
5856
- else {
5857
- clearTimeout(rejectTimeout);
5858
- reject(new Error('No incoming service worker found.'));
5859
- }
5860
- });
5861
- }
5862
-
5863
- /**
5864
- * @license
5865
- * Copyright 2020 Google LLC
5866
- *
5867
- * Licensed under the Apache License, Version 2.0 (the "License");
5868
- * you may not use this file except in compliance with the License.
5869
- * You may obtain a copy of the License at
5870
- *
5871
- * http://www.apache.org/licenses/LICENSE-2.0
5872
- *
5873
- * Unless required by applicable law or agreed to in writing, software
5874
- * distributed under the License is distributed on an "AS IS" BASIS,
5875
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5876
- * See the License for the specific language governing permissions and
5877
- * limitations under the License.
5878
- */
5879
- async function updateSwReg(messaging, swRegistration) {
5880
- if (!swRegistration && !messaging.swRegistration) {
5881
- await registerDefaultSw(messaging);
5882
- }
5883
- if (!swRegistration && !!messaging.swRegistration) {
5884
- return;
5885
- }
5886
- if (!(swRegistration instanceof ServiceWorkerRegistration)) {
5887
- throw ERROR_FACTORY.create("invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */);
5888
- }
5889
- messaging.swRegistration = swRegistration;
5890
- }
5891
-
5892
- /**
5893
- * @license
5894
- * Copyright 2020 Google LLC
5895
- *
5896
- * Licensed under the Apache License, Version 2.0 (the "License");
5897
- * you may not use this file except in compliance with the License.
5898
- * You may obtain a copy of the License at
5899
- *
5900
- * http://www.apache.org/licenses/LICENSE-2.0
5901
- *
5902
- * Unless required by applicable law or agreed to in writing, software
5903
- * distributed under the License is distributed on an "AS IS" BASIS,
5904
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5905
- * See the License for the specific language governing permissions and
5906
- * limitations under the License.
5907
- */
5908
- async function updateVapidKey(messaging, vapidKey) {
5909
- if (!!vapidKey) {
5910
- messaging.vapidKey = vapidKey;
5911
- }
5912
- else if (!messaging.vapidKey) {
5913
- messaging.vapidKey = DEFAULT_VAPID_KEY;
5914
- }
5915
- }
5916
-
5917
- /**
5918
- * @license
5919
- * Copyright 2020 Google LLC
5920
- *
5921
- * Licensed under the Apache License, Version 2.0 (the "License");
5922
- * you may not use this file except in compliance with the License.
5923
- * You may obtain a copy of the License at
5924
- *
5925
- * http://www.apache.org/licenses/LICENSE-2.0
5926
- *
5927
- * Unless required by applicable law or agreed to in writing, software
5928
- * distributed under the License is distributed on an "AS IS" BASIS,
5929
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5930
- * See the License for the specific language governing permissions and
5931
- * limitations under the License.
5932
- */
5933
- async function getToken$1(messaging, options) {
5934
- if (!navigator) {
5935
- throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
5936
- }
5937
- if (Notification.permission === 'default') {
5938
- await Notification.requestPermission();
5939
- }
5940
- if (Notification.permission !== 'granted') {
5941
- throw ERROR_FACTORY.create("permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */);
5942
- }
5943
- await updateVapidKey(messaging, options?.vapidKey);
5944
- await updateSwReg(messaging, options?.serviceWorkerRegistration);
5945
- return getTokenInternal(messaging);
5946
- }
5947
-
5948
- /**
5949
- * @license
5950
- * Copyright 2019 Google LLC
5951
- *
5952
- * Licensed under the Apache License, Version 2.0 (the "License");
5953
- * you may not use this file except in compliance with the License.
5954
- * You may obtain a copy of the License at
5955
- *
5956
- * http://www.apache.org/licenses/LICENSE-2.0
5957
- *
5958
- * Unless required by applicable law or agreed to in writing, software
5959
- * distributed under the License is distributed on an "AS IS" BASIS,
5960
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5961
- * See the License for the specific language governing permissions and
5962
- * limitations under the License.
5963
- */
5964
- async function logToScion(messaging, messageType, data) {
5965
- const eventType = getEventType(messageType);
5966
- const analytics = await messaging.firebaseDependencies.analyticsProvider.get();
5967
- analytics.logEvent(eventType, {
5968
- /* eslint-disable camelcase */
5969
- message_id: data[CONSOLE_CAMPAIGN_ID],
5970
- message_name: data[CONSOLE_CAMPAIGN_NAME],
5971
- message_time: data[CONSOLE_CAMPAIGN_TIME],
5972
- message_device_time: Math.floor(Date.now() / 1000)
5973
- /* eslint-enable camelcase */
5974
- });
5975
- }
5976
- function getEventType(messageType) {
5977
- switch (messageType) {
5978
- case MessageType.NOTIFICATION_CLICKED:
5979
- return 'notification_open';
5980
- case MessageType.PUSH_RECEIVED:
5981
- return 'notification_foreground';
5982
- default:
5983
- throw new Error();
5984
- }
5985
- }
5986
-
5987
- /**
5988
- * @license
5989
- * Copyright 2017 Google LLC
5990
- *
5991
- * Licensed under the Apache License, Version 2.0 (the "License");
5992
- * you may not use this file except in compliance with the License.
5993
- * You may obtain a copy of the License at
5994
- *
5995
- * http://www.apache.org/licenses/LICENSE-2.0
5996
- *
5997
- * Unless required by applicable law or agreed to in writing, software
5998
- * distributed under the License is distributed on an "AS IS" BASIS,
5999
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6000
- * See the License for the specific language governing permissions and
6001
- * limitations under the License.
6002
- */
6003
- async function messageEventListener(messaging, event) {
6004
- const internalPayload = event.data;
6005
- if (!internalPayload.isFirebaseMessaging) {
6006
- return;
6007
- }
6008
- if (messaging.onMessageHandler &&
6009
- internalPayload.messageType === MessageType.PUSH_RECEIVED) {
6010
- if (typeof messaging.onMessageHandler === 'function') {
6011
- messaging.onMessageHandler(externalizePayload(internalPayload));
6012
- }
6013
- else {
6014
- messaging.onMessageHandler.next(externalizePayload(internalPayload));
6015
- }
6016
- }
6017
- // Log to Scion if applicable
6018
- const dataPayload = internalPayload.data;
6019
- if (isConsoleMessage(dataPayload) &&
6020
- dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {
6021
- await logToScion(messaging, internalPayload.messageType, dataPayload);
6022
- }
6023
- }
6024
-
6025
- const name = "@firebase/messaging";
6026
- const version = "0.12.23";
6027
-
6028
- /**
6029
- * @license
6030
- * Copyright 2020 Google LLC
6031
- *
6032
- * Licensed under the Apache License, Version 2.0 (the "License");
6033
- * you may not use this file except in compliance with the License.
6034
- * You may obtain a copy of the License at
6035
- *
6036
- * http://www.apache.org/licenses/LICENSE-2.0
6037
- *
6038
- * Unless required by applicable law or agreed to in writing, software
6039
- * distributed under the License is distributed on an "AS IS" BASIS,
6040
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6041
- * See the License for the specific language governing permissions and
6042
- * limitations under the License.
6043
- */
6044
- const WindowMessagingFactory = (container) => {
6045
- const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));
6046
- navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));
6047
- return messaging;
6048
- };
6049
- const WindowMessagingInternalFactory = (container) => {
6050
- const messaging = container
6051
- .getProvider('messaging')
6052
- .getImmediate();
6053
- const messagingInternal = {
6054
- getToken: (options) => getToken$1(messaging, options)
6055
- };
6056
- return messagingInternal;
6057
- };
6058
- function registerMessagingInWindow() {
6059
- _registerComponent(new Component('messaging', WindowMessagingFactory, "PUBLIC" /* ComponentType.PUBLIC */));
6060
- _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
6061
- registerVersion(name, version);
6062
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
6063
- registerVersion(name, version, 'esm2020');
6064
- }
6065
-
6066
- /**
6067
- * @license
6068
- * Copyright 2020 Google LLC
6069
- *
6070
- * Licensed under the Apache License, Version 2.0 (the "License");
6071
- * you may not use this file except in compliance with the License.
6072
- * You may obtain a copy of the License at
6073
- *
6074
- * http://www.apache.org/licenses/LICENSE-2.0
6075
- *
6076
- * Unless required by applicable law or agreed to in writing, software
6077
- * distributed under the License is distributed on an "AS IS" BASIS,
6078
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6079
- * See the License for the specific language governing permissions and
6080
- * limitations under the License.
6081
- */
6082
- /**
6083
- * Checks if all required APIs exist in the browser.
6084
- * @returns a Promise that resolves to a boolean.
6085
- *
6086
- * @public
6087
- */
6088
- async function isWindowSupported() {
6089
- try {
6090
- // This throws if open() is unsupported, so adding it to the conditional
6091
- // statement below can cause an uncaught error.
6092
- await validateIndexedDBOpenable();
6093
- }
6094
- catch (e) {
6095
- return false;
6096
- }
6097
- // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing
6098
- // might be prohibited to run. In these contexts, an error would be thrown during the messaging
6099
- // instantiating phase, informing the developers to import/call isSupported for special handling.
6100
- return (typeof window !== 'undefined' &&
6101
- isIndexedDBAvailable() &&
6102
- areCookiesEnabled() &&
6103
- 'serviceWorker' in navigator &&
6104
- 'PushManager' in window &&
6105
- 'Notification' in window &&
6106
- 'fetch' in window &&
6107
- ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
6108
- PushSubscription.prototype.hasOwnProperty('getKey'));
6109
- }
6110
-
6111
- /**
6112
- * @license
6113
- * Copyright 2020 Google LLC
6114
- *
6115
- * Licensed under the Apache License, Version 2.0 (the "License");
6116
- * you may not use this file except in compliance with the License.
6117
- * You may obtain a copy of the License at
6118
- *
6119
- * http://www.apache.org/licenses/LICENSE-2.0
6120
- *
6121
- * Unless required by applicable law or agreed to in writing, software
6122
- * distributed under the License is distributed on an "AS IS" BASIS,
6123
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6124
- * See the License for the specific language governing permissions and
6125
- * limitations under the License.
6126
- */
6127
- function onMessage$1(messaging, nextOrObserver) {
6128
- if (!navigator) {
6129
- throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
6130
- }
6131
- messaging.onMessageHandler = nextOrObserver;
6132
- return () => {
6133
- messaging.onMessageHandler = null;
6134
- };
6135
- }
6136
-
6137
- /**
6138
- * @license
6139
- * Copyright 2017 Google LLC
6140
- *
6141
- * Licensed under the Apache License, Version 2.0 (the "License");
6142
- * you may not use this file except in compliance with the License.
6143
- * You may obtain a copy of the License at
6144
- *
6145
- * http://www.apache.org/licenses/LICENSE-2.0
6146
- *
6147
- * Unless required by applicable law or agreed to in writing, software
6148
- * distributed under the License is distributed on an "AS IS" BASIS,
6149
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6150
- * See the License for the specific language governing permissions and
6151
- * limitations under the License.
6152
- */
6153
- /**
6154
- * Retrieves a Firebase Cloud Messaging instance.
6155
- *
6156
- * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
6157
- *
6158
- * @public
6159
- */
6160
- function getMessagingInWindow(app = getApp()) {
6161
- // Conscious decision to make this async check non-blocking during the messaging instance
6162
- // initialization phase for performance consideration. An error would be thrown latter for
6163
- // developer's information. Developers can then choose to import and call `isSupported` for
6164
- // special handling.
6165
- isWindowSupported().then(isSupported => {
6166
- // If `isWindowSupported()` resolved, but returned false.
6167
- if (!isSupported) {
6168
- throw ERROR_FACTORY.create("unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */);
6169
- }
6170
- }, _ => {
6171
- // If `isWindowSupported()` rejected.
6172
- throw ERROR_FACTORY.create("indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);
6173
- });
6174
- return _getProvider(getModularInstance(app), 'messaging').getImmediate();
6175
- }
6176
- /**
6177
- * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud
6178
- * Messaging registration token that can be used to send push messages to that {@link Messaging}
6179
- * instance.
6180
- *
6181
- * If notification permission isn't already granted, this method asks the user for permission. The
6182
- * returned promise rejects if the user does not allow the app to show notifications.
6183
- *
6184
- * @param messaging - The {@link Messaging} instance.
6185
- * @param options - Provides an optional vapid key and an optional service worker registration.
6186
- *
6187
- * @returns The promise resolves with an FCM registration token.
6188
- *
6189
- * @public
6190
- */
6191
- async function getToken(messaging, options) {
6192
- messaging = getModularInstance(messaging);
6193
- return getToken$1(messaging, options);
6194
- }
6195
- /**
6196
- * When a push message is received and the user is currently on a page for your origin, the
6197
- * message is passed to the page and an `onMessage()` event is dispatched with the payload of
6198
- * the push message.
6199
- *
6200
- *
6201
- * @param messaging - The {@link Messaging} instance.
6202
- * @param nextOrObserver - This function, or observer object with `next` defined,
6203
- * is called when a message is received and the user is currently viewing your page.
6204
- * @returns To stop listening for messages execute this returned function.
6205
- *
6206
- * @public
6207
- */
6208
- function onMessage(messaging, nextOrObserver) {
6209
- messaging = getModularInstance(messaging);
6210
- return onMessage$1(messaging, nextOrObserver);
6211
- }
6212
-
6213
- /**
6214
- * The Firebase Cloud Messaging Web SDK.
6215
- * This SDK does not work in a Node.js environment.
6216
- *
6217
- * @packageDocumentation
6218
- */
6219
- registerMessagingInWindow();
6220
-
6221
1581
  const useFirebase = (firebaseConfig, vapidKey, onFirebaseMessage = () => {}) => {
6222
- const [app] = React.useState(initializeApp(firebaseConfig));
6223
- const [messaging, setMessaging] = React.useState();
1582
+ const [app$1] = React.useState(app.initializeApp(firebaseConfig));
1583
+ const [messaging$1, setMessaging] = React.useState();
6224
1584
  const [firebaseToken, setFirebaseToken] = React.useState();
6225
1585
  React.useEffect(() => {
6226
- isWindowSupported().then(supported => {
1586
+ messaging.isSupported().then(supported => {
6227
1587
  if (supported) {
6228
- setMessaging(getMessagingInWindow(app));
1588
+ setMessaging(messaging.getMessaging(app$1));
6229
1589
  }
6230
1590
  });
6231
- }, [setMessaging, app]);
1591
+ }, [setMessaging, app$1]);
6232
1592
  const notificationHandler = function (permission) {
6233
- console.log("Notification permission: ", permission, messaging);
6234
- if (permission === "granted" && messaging) {
6235
- getToken(messaging, {
1593
+ console.log("Notification permission: ", permission, messaging$1);
1594
+ if (permission === "granted" && messaging$1) {
1595
+ messaging.getToken(messaging$1, {
6236
1596
  vapidKey
6237
1597
  }).then(token => {
6238
1598
  setFirebaseToken(token);
@@ -6253,13 +1613,13 @@ const useFirebase = (firebaseConfig, vapidKey, onFirebaseMessage = () => {}) =>
6253
1613
  }
6254
1614
  }
6255
1615
  }
6256
- }, [messaging]);
1616
+ }, [messaging$1]);
6257
1617
  React.useEffect(() => {
6258
- if (messaging) {
6259
- const unsubscribe = onMessage(messaging, onFirebaseMessage);
1618
+ if (messaging$1) {
1619
+ const unsubscribe = messaging.onMessage(messaging$1, onFirebaseMessage);
6260
1620
  return () => unsubscribe();
6261
1621
  }
6262
- }, [messaging, onFirebaseMessage]);
1622
+ }, [messaging$1, onFirebaseMessage]);
6263
1623
  return {
6264
1624
  firebaseToken
6265
1625
  };