datastake-daf 0.6.710 → 0.6.712

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